content stringlengths 5 1.05M |
|---|
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from django.utils.translation import gettext_lazy as _
CATEGORY = (
('Women', 'Women'),
('Men', 'Men'),
('Raw material', 'Raw material'),
('Life style', 'Life style'),
)
class Messages(models.Model):
"""
... |
import logging
from oidcmsg import oidc
from oidcmsg.message import Message
from oidcmsg.oauth2 import ResponseMessage
from oidcservice.service import Service
LOGGER = logging.getLogger(__name__)
class RegistrationRead(Service):
msg_type = Message
response_cls = oidc.RegistrationResponse
error_msg = R... |
import argparse
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
LOG_FILE_NAME = "log.csv"
def moving_avg(x, y, window_size=1):
if window_size == 1:
return x, y
moving_avg_y = np.convolve(y, np.ones(window_size) / window_size, 'valid')
re... |
import time
import math
import odrive
import contextlib
import odrive.enums
from configs.config import global_config as c
ANGLE_NORMALIZATION = 1 / math.pi
class KineticMazeMotor:
def __init__(self):
self.od = None
self.approx_cycles_per_revolution = None
self.init_odrive()
def axis(... |
#Programa que leia o nome de uma pessoa e diga se ela tem silva no nome
nome = input('Digite o seu nome completo: ').title()
splt = nome.split()
if 'Silva' in splt:
print('Seu nome possui Silva.')
else:
print('Seu nome não possui Silva.') |
import collections
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
m = collections.Counter(nums1)
result = []
for num in nums2:
if num in m:
result.append(num)
if m[num] == 1:
del m[num]
else:
m[num] -= 1
return r... |
# 140000000
LILIN = 1201000
sm.setSpeakerID(LILIN)
sm.sendNext("Alright, I've done enough explaining for now. Let's move on to the next stage. What's the next stage, you ask? I just told you. Train as hard as you can until you become strong enough to defeat the Black Mage with a single blow.")
sm.sendSay("You may have... |
class Range:
def __init__(self,start,stop=None,step=1):
if step==0:
raise ValueError("step cant be zero")
elif stop==None:
start,stop=0,start
self._length=max(0,(stop-start+step-1)//step)
self._start=start
self._step=step
def __len__(self):
... |
#!/usr/bin/env python3
total = 0
with open("input") as infile:
for line in infile:
output = line.split(" | ")[1].strip()
output = output.split(" ")
for value in output:
if len(value) in [2, 3, 4, 7]:
total += 1
print(total)
|
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
import numpy as np
from solutions import get_vals
cmap = plt.cm.coolwarm
cmap_r = plt.cm.coolwarm_r
def sqrt_riemann_surface_1():
"""riemann surface for real part of sqrt(z)"""
fig = plt.figure()
ax = Axes3D(fig)
X = np.ara... |
"""This module is used as a base for other integration tests"""
# To extract the logs from the Docker instance, override /tmp/logs
import inspect
import os
import shutil
import signal
import subprocess
import unittest
import tempfile
from collections import namedtuple
import logging
import sys
from chewie.chewie im... |
#!/usr/bin/env python3
from ideone import ideone_automation
from db_model import manage_db
import os
import time
import webbrowser
from datetime import datetime
usr = ideone_automation()
db = manage_db()
home_page = "https://ideone.com/"
def header():
print("----------------------------------------------------\n... |
"""empty message
Revision ID: 12ca023b94f8
Revises: e759ca20884f
Create Date: 2021-09-09 13:13:24.802259
"""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from project import dbtypes
# revision identifiers, used by Alembic.
revision = "12ca023b94f8"
down_revision = "e759ca20884f"
branch_lab... |
# vim: set sw=2 ts=2 softtabstop=2 expandtab:
from . RunnerBase import RunnerBaseClass
from .. Analysers.GPUVerify import GPUVerifyAnalyser
import logging
import os
import psutil
import re
import sys
import yaml
_logger = logging.getLogger(__name__)
class GPUVerifyRunnerException(Exception):
def __init__(self, msg)... |
from edmonds_karp import FlowNetwork, defaultdict
class CapacityScaler(FlowNetwork):
__slots__ = "U"
def __init__(self):
super().__init__()
self.U = -self.INF
self.discovered = defaultdict(lambda: False)
self.pred = defaultdict(lambda: None)
def insert_edges_from_iterabl... |
# -*- coding=utf-8 -*-
r"""
key(str)-value(str) database-files
https://docs.python.org/3/library/dbm.html
"""
from ._filebase import FileBase
import dbm
from typing import Union
_T = Union[str, bytes]
class DBFile(FileBase):
FILE_EXTENSION = '.dbm'
READY_ONLY = 'r' # only read from file
... |
from setuptools import setup
setup(name="hydrand", packages=["hydrand"])
|
from aria import workflow
from aria.orchestrator.workflows.api import task
from aria.orchestrator.workflows.exceptions import TaskException
INTERFACE_NAME = 'Custom'
DEPLOY_OPERATION_NAME = 'deploy'
@workflow
def deploy(ctx, graph):
"""
Custom workflow to call the operations on the Deploy interfac... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
import pytest
import feeds.notification_level as level
from feeds.exceptions import (
MissingLevelError
)
def test_register_level_ok():
class TestLevel(level.Level):
id=666
name="test"
level.register(TestLevel)
assert '666' in level._level_register
assert level._level_register['666'... |
import json
import os
from abc import ABC, abstractmethod
from src import DATA_FOLDER, UNZIPED_FOLDER_NAME
from src import settings
from src.db_models.models import dict_db_models
from src.io import CNAE_JSON_NAME, NATJU_JSON_NAME, QUAL_SOCIO_JSON_NAME, MOTIVOS_JSON_NAME, PAIS_JSON_NAME, \
MUNIC_JSON_NAME
... |
# Generated by Django 3.1.6 on 2021-02-04 20:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='News',
fields=[
('id', models.AutoField(aut... |
from torch.autograd import Variable
class Learner(object):
def __init__(self, DNN_AE, input, target, batch_size=1000, epochs=1000):
self.DNN_AE = DNN_AE
self.input = Variable(input)
self.input_dim = input.shape
self.target = Variable(target)
self.target_dim = target.... |
from __future__ import absolute_import
import http.client
# 2To3-division: this file is skipped as this is version specific implemetation.
def div(a, b):
try:
return a / b
except ZeroDivisionError as exc:
return None
class MyClass (object, metaclass=type):
pass
|
from .SpinConfiguration import *
from .Hamiltonian import *
def montecarlo_metropolis(N, ham, temp, montecarlo_steps, burn_steps=0):
"""
Performs metropolis sampling to determine thermal quantities at the specified temperature
for an N-spin system described by a particular Hamiltonian.
Parameters
... |
"""
[M] Given an array, find the sum of all numbers between the K1’th and K2’th
smallest elements of that array.
Example 1:
Input: [1, 3, 12, 5, 15, 11], and K1=3, K2=6
Output: 23
Explanation: The 3rd smallest number is 5 and 6th smallest number 15.
The sum of numbers coming
between 5 and 15 is 23 (11+12).
"""
... |
'''the main mod of ika'''
import random
from string import ascii_letters as al
import flask
from flask_bootstrap import Bootstrap
from frontend import frontend
from endpoint import app
from endpoint import get_topics
Bootstrap(app)
app.register_blueprint(frontend)
# app config for image upload
app.config['ALLOWED_EXT... |
import os
import sys
import functools
import platform
import textwrap
import pytest
IS_PYPY = '__pypy__' in sys.builtin_module_names
def popen_text(call):
"""
Augment the Popen call with the parameters to ensure unicode text.
"""
return functools.partial(call, universal_newlines=True) \
if ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'CustomImageOsType',
'EnableStatus',
'EnvironmentPermission',
'HostCachingOptions',
'LinuxOsStat... |
# Programmer: Konstantin Davydov
# Date of creation: 2021.05.03
import sys
import time
"""
Unbeatable TIC-TAC-TOE game vs Computer
"""
# global variables
def global_vars():
global empty_cell, hum_token, comp_token, turn, total_cells, legal_moves, turn_value
empty_cell = ' '
hum_token = 'X'
... |
#!/usr/bin/env python
import sys
import inspect
import cProfile
from pstats import Stats
from pathlib import Path
from argparse import ArgumentParser
from typing import List
from multiprocessing import cpu_count
from lib.io import export_csv
from lib.pipeline import PipelineChain
from lib.utils import ROOT
# Step 1:... |
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_choice, create_option
from discord import Client, Intents, Embed
import requests
from dotenv import load_dotenv
import os
load_dotenv(".env")
client = commands.Bot(command_prefi... |
from unittest import TestCase
from src.models.db import *
from src.models.research_group import *
from src.config import *
class TestResearchGroupDataAccess(TestCase):
def _connect(self):
connection = DBConnection(dbname='test_db', dbuser=config_data['dbuser'],
dbpass=con... |
"""Lock to prevent sending multiple command at once to Epson projector."""
import time
from .const import (TURN_ON, TURN_OFF, INV_SOURCES, SOURCE, ALL, TIMEOUT_TIMES)
class Lock:
def __init__(self):
"""Init lock for sending request to projector when it is busy."""
self._isLocked = False
s... |
import pygame, sys
from dashboard.view import DashboardView
from dashboard.arduino import ArduinoConnection
dashboard = DashboardView(size=(600,400))
def update_data(data):
print(data)
dashboard.components["temp"].set_value(data["temp"])
dashboard.components["volt"].set_value(data["voltage"])
dashboar... |
"""
RamondettiDavide Spa
====================
DuoConsole Python 20
DuoConsole is a free open source console in python and it execute some commands
"""
import sys
print("************************");
print("* RamondettiDavide Spa *");
print("* DuoConsole Python 20 *");
print("************************");
def CommandLine(... |
# -*- coding: utf-8 -*-
"""Top-level package for systeminfo."""
__author__ = """Darragh Crotty"""
__email__ = 'darragh@darraghcrotty.com'
__version__ = '0.1.0'
|
import json
from tqdm import tqdm
'''
ANEMONE的初版预测有很多很乐观的完全预测错了的情况
在新的结果跑出来之前,先用启发式方式对这个第一版结果筛选一下,防止结果太烂
'''
whole_simple_prediction_store_dir = 'C:/workspace/服务器备份/ANEMONE/whole_simple_prediction/'
whole_simple_prediction_file_path = f'{whole_simple_prediction_store_dir}all_predictions.json'
def ANEMONE_prediction... |
#-*- coding:utf-8 -*-
import time, threading
from SocketServer import TCPServer, BaseRequestHandler
import traceback
from PythonSocketBBS import SocketServerBBS
def loop(a):
print 'thread is running...'
#
time.sleep(1)
a.serve_forever()
print 'thread ended.'
def socketMethod():
print 'Method ... |
import requests
import json
import os
def get_wicked_data_before_src():
with open('final_output/remaining_list.csv') as file:
packages = [package.strip() for package in file.readlines()]
# write all the packages in a csv file for wicked input
... |
# Base class for "other" kinetic (radius + momentum + time) quantities
#
import matplotlib.pyplot as plt
import numpy as np
from . OutputException import OutputException
from . KineticQuantity import KineticQuantity
class OtherKineticQuantity(KineticQuantity):
def __init__(self, name, data, description, g... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description:TikTokMulti.py
@Date :2022/01/29 20:23:37
@Author :JohnserfSeed
@version :1.2.5
@License :(C)Copyright 2019-2022, Liugroup-NLPR-CASIA
@Github :https://github.com/johnserf-seed
@Mail :johnserfseed@gmail.com
'''
import requests,js... |
# This is a sample Python script.
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
from util.eplus_model_interface import EplusModelIndexedList
import os
import multiprocessing as mp
FILE_DIR = os.path.dirname(__file__... |
"""The CSDMS Standard Names"""
from ._version import get_versions
from .error import BadNameError, BadRegistryError
from .registry import NamesRegistry
from .standardname import StandardName, is_valid_name
__all__ = [
"StandardName",
"is_valid_name",
"NamesRegistry",
"BadNameError",
"BadRegistryEr... |
# -*- coding: utf-8 -*-
import argparse
import os
from ctypes import cdll
from fuse import FUSE
from girder_client import GirderClient
from girderfs.core import \
RESTGirderFS, LocalGirderFS
_libc = cdll.LoadLibrary('libc.so.6')
_setns = _libc.setns
CLONE_NEWNS = 0x00020000
def setns(fd, nstype):
if hasatt... |
"""
Django settings for webapp project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os,... |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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 ... |
# variable length argument
def add(*args):
sum = 0
for i in args:
sum+=i
return sum
# Keyword length argument
def what_to_do(farg,**kwargs):
sum = 0
sub = 0
if farg=='sum':
for i,j in kwargs.items():
sum+=j
if farg=='sub':
for k,v in kwargs.items():
... |
# This example is provided for informational purposes only and has not been audited for security.
from pyteal import *
"""Split Payment"""
tmpl_fee = Int(1000)
tmpl_rcv1 = Addr("6ZHGHH5Z5CTPCF5WCESXMGRSVK7QJETR63M3NY5FJCUYDHO57VTCMJOBGY")
tmpl_rcv2 = Addr("7Z5PWO2C6LFNQFGHWKSK5H47IQP5OJW2M3HA2QPXTY3WTNP5NU2MHBW27M")... |
from pyspark import keyword_only
from pyspark.ml.param import TypeConverters
from pyspark.ml.param.shared import Param, Params
from pyspark.ml.util import DefaultParamsReadable, DefaultParamsWritable
from pyspark.ml.wrapper import JavaTransformer
class OneHotDecoder(JavaTransformer, DefaultParamsReadable, DefaultPar... |
# -*- coding: utf-8 -*-
import requests
import json
import random
from twitchio.ext import commands
import config
bot = commands.Bot(
irc_token=config.OAUTH,
client_id=config.CLIENT_ID,
nick=config.BOT_NAME,
prefix=config.BOT_PREFIX,
initial_channels=[config.CHANNEL]
)
bms_list = [{'url': 'http:... |
from uuid import UUID
import pytest
import requests
from exporter.applications.forms import goods
application_id = UUID("2a199722-75fc-4699-abfc-ddfb30381c0f")
sub_case_type_siel = {"key": "standard", "value": "Standard Licence"}
@pytest.fixture(scope="session")
def good_template():
return {
"componen... |
from __future__ import print_function, division
import time
import datetime
import argparse
from pathlib import Path
import numpy as np
from cornell_dataset import CornellDataset, ToTensor, Normalize, de_normalize
def parse_arguments():
parser = argparse.ArgumentParser(description='Grasping detection system')
... |
import matplotlib.pyplot as plt
import datetime as dt
import time as ti
from astropy import time
from astropy import units as u
from poliastro.neos import neows
from poliastro.examples import molniya
from poliastro.plotting import plot, OrbitPlotter, BODY_COLORS
from poliastro.bodies import Sun, Earth, Mars
from poli... |
import datetime
import functools
import logging
import os
import sys
from collections import namedtuple
from datetime import date, timedelta
from logging import handlers
from time import sleep
def retry(exceptions, tries=2, wait=None):
""" Decorator factory creates retry-decorators which repeats the function
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 09:53:33 2021
@author: ljia
"""
if __name__ == '__main__':
tasks = [
{'path': '.',
'file': 'run_job_treelet.py'
},
]
import os
for t in tasks:
print(t['file'])
command = ''
command += 'cd ' + t['path'] + '\n'
command ... |
def mdc(m,n):
if n==0: return m
return mdc(n,m%n)
for k in range(int(input())):
A = input().split()
op = A[3]
A[0] = int(A[0])
A[1] = int(A[2])
A[2] = int(A[4])
A[3] = int(A[6])
res = [[],[]]
if op == '+':
res[0] = A[0]*A[3]+A[2]*A[1]
res[1] = A[1]*A[3]
elif ... |
"""
Tools for narrating the screenplay.
"""
from .narrator import Narrator
__all__ = [
"Narrator",
]
|
from bitmovin_api_sdk.encoding.encodings.muxings.ts.drm.aes.aes_api import AesApi
from bitmovin_api_sdk.encoding.encodings.muxings.ts.drm.aes.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.encodings.muxings.ts.drm.aes.aes_encryption_drm_list_query_params import AesEncryptionDrmListQueryPa... |
from .goal_emb import *
from .st_emb import *
from .st_enc import *
from .st_search import *
from .tac_sc import *
from .thm_emb import *
from .thm_sc import *
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-02-22 21:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('awards', '0068_merge_20170216_1631'),
]
operations... |
# 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
# d... |
# Copyright 2013 by Eric Suh
# Copyright (c) 2013 Theo Crevon
# This code is freely licensed under the MIT license found at
# <http://opensource.org/licenses/MIT>
import sys
import os
import errno
import atexit
import signal
import time
import pidfile
class daemon(object):
'Context manager for POSIX daemon proc... |
# I like this version FizzBuzz better than the standard :P
# sum of first "n" multiples of "d" (limited case of arithmetic series sum)
def sum_of_n_muls(d, n):
# (2*a1+(n-1)*d)*n/2 = (2*d+(n-1)*d)*n/2 = ((n+1)*d)*n/2
return (n+1)*d*n/2
# sum of all multiples of "d" below positive integer "number"
def sum_muls... |
# -*- coding:utf-8 -*-
#--
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
from elixir import using_options
from elixir import ManyToMany, ManyToOne
f... |
import regex as re
def remove_article(text):
return re.sub('^l[ea] ', '', text)
def remove_feminine_infl(text):
text = re.sub('(?<=\w+)\(e\)(?!\w)', '', text)
text = re.sub('(?<=\w+)\(ne\)(?!\w)', '', text)
return text
|
from queue import Queue
import logging
log = logging.getLogger(__name__)
class DependencyMapper:
SUMMARY_LOG_MESSAGE = "Dependencies tree for package {name}-{version} retrieved.{count} dependencies were found."
def __init__(self, cache):
self.cache = cache
@staticmethod
def _create_package_... |
# -*- coding: utf-8 -*-
"""Authentication methods."""
from typing import List
from ..exceptions import AlreadyLoggedIn
from ..http import Http
from .models import Mixins
class ApiKey(Mixins):
"""Authentication method using API key & API secret."""
def __init__(self, http: Http, key: str, secret: str, **kwar... |
import simplejson as json
from bamboo.controllers.calculations import Calculations
from bamboo.controllers.datasets import Datasets
from bamboo.core.summary import SUMMARY
from bamboo.lib.jsontools import df_to_jsondict
from bamboo.lib.mongo import MONGO_ID
from bamboo.models.dataset import Dataset
from bamboo.tests.t... |
import setuptools
setuptools.setup(use_scm_version={"write_to": "mbta_analysis/_version.py"})
|
# -*- coding: utf-8 -*-
# Copyright 2017-TODAY LasLabs Inc.
# License MIT (https://opensource.org/licenses/MIT).
import properties
from ..base_model import GeneralOverview, LinksModelWithImage
from .producer import Producer
from .strain import Strain
class AbstractItem(LinksModelWithImage):
"""Represents the b... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2021 Fetch.AI Limited
#
# 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 ... |
# Declare and initialize variables
even_count=0
odd_count=0
even_sum=0
odd_sum=0
# Main loop
while True:
Int_input = input("Input an integer (Enter '0' to End Entry) --> ")
Int = int(Int_input)
# check for 0 and exit loop
if Int == 0:
print("Ending Input")
break
# Check for negativ... |
import sys
import shutil
import os
from os import path
from subprocess import call as execute
from setuptools.command.build_ext import build_ext
from setuptools import setup, find_packages, Extension
PACKAGE_NAME = "MulticoreTSNE"
VERSION = '0.1'
class CMakeExtension(Extension):
def __init__(self, name, sourc... |
# *---------------------------------------------------------------
# * Copyright (c) 2018
# * Broadcom Corporation
# * All Rights Reserved.
# *---------------------------------------------------------------
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that ... |
def process(pid):
x = 6
y = 10
return pid + x + y
def main():
res = process(8)
print('res: {}'.format(res))
main() |
"""
Spectral transforms are used in order to estimate the frequency-domain
representation of time-series. Several methods can be used and this module
contains implementations of several algorithms for the calculation of spectral
transforms.
"""
import numpy as np
from nitime.lazy import matplotlib_mlab as mlab
from ... |
import numpy as np
from numpy.testing import assert_array_equal
import sys, os
my_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, my_path + '/../')
import pyidi
def test_multiprocessing():
video = pyidi.pyIDI(cih_file='./data/data_synthetic.cih')
video.set_method(method='lk', int_order=1,... |
import datetime
import random
import hashlib
basic = {
'一元微积分',
'多元微积分',
'高等微积分',
'几何与代数',
'随机数学方法',
'概率论与数理统计',
'线性代数',
'复变函数引论',
'大学物理',
'数理方程引',
'数值分析',
'离散数学',
'离散数学(Ⅱ)',
'随机过程',
'应用随机过程',
'泛函分析',
'代数编码理论',
'初等数论与多项式',
'应用统计',
'工程图学基础'... |
import deepspeed
import torch
from apex.optimizers import FusedAdam as Adam
from torch import distributed as dist
import mpu
from fp16 import FP16_Module, FP16_Optimizer, DynamicLossScaler
from learning_rates import AnnealingLR
from model import GLMModel, glm_get_params_for_weight_decay_optimization
from model import ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2020-02-18 10:01
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0430_briefofevidencedocument'),
('wildlifecompliance', '0427_merge_202... |
import os
from typing import Optional, Mapping, Callable, Union, Tuple, List
from functools import lru_cache
from torch.utils.data import Dataset
import torch
import numpy as np
import h5py
from scipy.integrate import cumtrapz
import matplotlib.pyplot as plt
Sample = Mapping[str, Union[np.ndarray, torch.Tensor, List... |
#
# Copyright 2017 the original author or authors.
#
# 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... |
import requests
payload = {'lat': '12.2334', 'lon': '39.23467' , 'crime_id' : '3'}
req = requests.post("http://192.168.1.2/AutomatedDrone/api/location.php", data=payload)
print(req.text)
|
# Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from django.test import RequestFactory, TestCase
from vs_listener.views import ListenerView
class ListenerViewTest(TestCase):
def test_missing_secret(self):
request = RequestFactory().post('/listener')
respons... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 appli... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pyramid.view import view_config, view_defaults
from pyramid.httpexceptions import HTTPFound, HTTPOk
from pyramid.httpexceptions import HTTPNotFound, HTTPBadRequest, HTTPRequestTimeout
#
# Network Interface Card の 情報を取得
#
import netifaces
from netaddr import IPAddress
... |
import datetime
class Employee:
num_of_employees = 0
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f"{first}.{last}@company.com"
Employee.num_of_employees += 1
def fullname(self):
... |
#!/usr/bin/env python3
# Day 1: Single Number
#
# Given a non-empty array of integers, every element appears twice except for one. Find that single one.
class Solution:
def singleNumber(self, nums: [int]) -> int:
seen = []
for num in nums:
if num in seen:
seen.remove(nu... |
# -*- coding: utf-8 -*_
#
# Copyright (c) 2020, Pureport, Inc.
# All Rights Reserved
from __future__ import absolute_import
from click import argument
from pureport_client.commands import (
CommandBase,
AccountsMixin
)
from pureport_client.util import JSON
class Command(AccountsMixin, CommandBase):
"... |
from random import randrange
from discord import Member,Role,utils
from .errors import *
class Games:
"""
A game class with different games.
Parameters
-----------
debugnum = Optional[int=None]
This is for debugging purposes.
"""
def __init__(se... |
n = "Hello"
# Your function here!
def string_function(s):
return s + 'world'
print(string_function(n))
|
# Generated by Django 3.0.3 on 2020-02-24 14:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0008_auto_20200223_1339'),
]
operations = [
migrations.CreateModel(
... |
import tensorflow.keras as keras
def BCDU_net_D3(input_size = (384,384,3)):
N = input_size[0]
#inputs1 = keras.layers.Input((256, 256, 1))
inputs1 = keras.layers.Input(input_size)
conv1 = keras.layers.Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs1)
co... |
"""Ensure that sort functions handle reasonably large test cases including
random, sorted, reversed, and identical data"""
from random import randint
import pytest
import algorithms.src.merge_sort as merge_sort
import algorithms.src.quick_sort as quick_sort
sorts = [merge_sort.out_of_place, merge_sort.in_place,
... |
#!/usr/bin/env python3
import fire
import json
import os
import sys
import numpy as np
import tensorflow as tf
import codecs
import base64
import model, sample, encoder
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
def interact_model(
model_name='',
seed=None,
length=40,
temperature=0.... |
import re
def process_token(token: str):
"""Makes sure a given token is valid for usage within the Discord API.
Args:
token (:class:`str`): The token to be processed.
Returns:
:class:`str`: The modified, adapted token.
Examples:
.. testsetup::
from serpcord.util... |
import sympy.physics.mechanics as me
import sympy as sm
import math as m
import numpy as np
x1, x2 = me.dynamicsymbols('x1 x2')
f1 = x1*x2+3*x1**2
f2 = x1*me.dynamicsymbols._t+x2*me.dynamicsymbols._t**2
x, y = me.dynamicsymbols('x y')
xd, yd = me.dynamicsymbols('x y', 1)
yd2 = me.dynamicsymbols('y', 2)
q1, q2, q3, u1,... |
# Copyright 2021 Tony Wu
#
# 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, soft... |
import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: sequence identifier
# value: neucleotide sequence
key = record[0]
value = record[1][:-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.