content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
"""实现P2P代理,让非白名单的IP地址走代理"""
import pywind.evtframework.handler.handler as handler
import pywind.evtframework.handler.udp_handler as udp_handler
import pywind.lib.timer as timer
import socket, os
import freenet.lib.fdsl_ctl as fdsl_ctl
import fdslight_etc.fn_client as fnc_config
import fdslight_et... |
import numpy as np
import math
x = np.arange(0, 10, 0.00001)
y = []
for i in x:
y.append(math.sin(i)*math.cos(i))
|
#!/usr/bin/python3
import argparse
def bitflip(data_block, bitwidth=32):
if bitwidth == 0:
return data_block
bytewidth = bitwidth // 8
bitswapped = bytearray()
i = 0
while i < len(data_block):
data = int.from_bytes(data_block[i:i+bytewidth], byteorder='big', signed=False)
... |
"""
Various add-ons to the SciPy morphology package
"""
import numpy as np
from scipy.ndimage import morphology, measurements, filters
def label(image: np.ndarray, **kw) -> np.ndarray:
"""
Redefine the scipy.ndimage.measurements.label function to work with a wider
range of data types. The default functio... |
'''
A simple exercie sript to find out total pay by multiplying hours worked with
rate per hour.
'''
hr1 = input('Enter Hours: ')
rate1 = input('Enter Rate: ')
# made failure proof so if user inputs values other than number it won't crash
# and through an error. so the program will just quit with following warning
# ... |
description = 'Switching from one capillary to the other'
includes = ['virtual_capillary_motors']
group = 'lowlevel'
devices = dict(
capillary_selector = device('nicos_tuw.xccm.devices.capillary_selector.CapillarySelector',
description = 'change between the two capillaries or have no capillary',
... |
import numpy as np
from pydmd import DMD
import os
from collections import OrderedDict
import shutil
import warnings
import cv2
def dmd_prep(src_dir, dest_dir, window, svd_rank, overwrite=False):
train_dir = os.path.join(src_dir, 'train')
test_dir = os.path.join(src_dir, 'test')
# create dest directory
... |
class Planet:
# Instance [Accessible]
shape = 'round'
gravity = ''
def __init__(self, name, radius, gravity, system):
# Attributes [Not Accessible]
self.name = name
self.radius = radius
self.gravity = gravity
self.system = system
def orbit(self):
... |
from py_tests_common import *
def ExpectedReferenceValue_ForMove_Test0():
c_program_text= """
fn Foo()
{
auto imut x= 0;
move(x); // Expected mutable variable.
}
"""
errors_list= ConvertErrors( tests_lib.build_program_with_errors( c_program_text ) )
assert( len(errors_list) > 0 )
assert( errors_list[... |
# 04 Packages
# As our application grows we are going to organize it in folder. Separating the modules in folders for a better organization.
# Here we created a folder "ecommerce" and put the "esales.py" module there.
# We have to add a "__init__.py" file to the "ecommerce" folder.
# When we do that Python treats that... |
import os
class FileLogger:
def __init__(self, filename):
self.filename = filename
def update(self, data):
''' Append the latest measurement to file. If the file does not exist,
headers matching the columns in self.data are written first.
Args:
data (pan... |
import pickle
import argparse
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from pathlib import Path
from os import chdir
def create_gauth(auth_pickle_file, save=True):
# authenticate user
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
# store GoogleAuth object in a pickl... |
from django.apps import AppConfig
class SitesettingsConfig(AppConfig):
name = "sitesettings"
|
from bs4 import BeautifulSoup
import requests
import re
class Stockify:
"""Stockify class to scrape EGDAR and get data"""
headers = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'
def __init__(self, ticker):
self.ticker = ticker.upper()
self.CIK = self.get_... |
import pytest
pytestmark = pytest.mark.django_db
def test_admin_interface(client):
public_urls = [
'/admin/login/',
'/',
'/about/',
'/privacy/',
]
for url in public_urls:
response = client.get('/admin/login/')
assert response.status_code == 200
|
#!/usr/bin/python
#
# marvin.py
# Nintendo Wii Remote controller for Snap
# Circuits robot.
#
# Authors : Scarlett Madson, Solomon Madson, Quinn Madson
# Date : 02.22.2016
# Import required Python libraries
import cwiid
import time
import pygame.mixer
import RPi.GPIO as io
# Setup Raspberry Pi GPIO pins
io.setmode(... |
#!/usr/bin/env python3
# coding:utf-8
"""
__title__ = ''
__author__ = 'David Ao'
__mtime__ = '2018/6/12'
#
"""
import logging
import redis
import sys
import platform
import pymysql as moduledb
class RedisManage:
"""
redis
"""
def __init__(self):
host = '192.168.199.29'
port = '6379'... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 15 22:33:21 2016
@author: Dominik
"""
from datetime import datetime, timedelta
import time
import sys
sleep_secs = 0.3
def get_time_from_txt(filename):
written_yet = False
while not written_yet:
try:
with open("end_time.txt", "r") as f:
... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: 1.0
@author: liyao
@license: Apache Licence
@contact: yli@posbao.net
@site: http://www.piowind.com/
@software: PyCharm
@file: adminx.py
@time: 2017/7/4 17:04
"""
import xadmin
from .models import CaseNode
class CaseNodeAdmin(object):
pass
xadmin.site.regis... |
from typing import List, Tuple
"""
Design an algorithm and write code to remove the duplicate characters in
a string without using any additional buffer. NOTE: One or two additional
variables are fine. An extra copy of the array is not. [CTCI Q1.3]
"""
def remove(s):
# This takes O(n) time and O(m) spa... |
from django.urls import path
from .views import *
urlpatterns = [
path('', get_user),
path('login', sign_in),
path('logout', sign_out),
path('signup', sign_up),
path('dummy', get_dummy),
]
|
from abc import ABC, abstractmethod
from dataclasses import dataclass
from napari.utils.misc import StringEnum
class ROIBase(ABC):
@property
@abstractmethod
def name(self) -> str:
raise NotImplementedError()
@name.setter
@abstractmethod
def name(self, name: str) -> None:
pass... |
from Orange.classification import SklLearner, SklModel
import numpy as np
class DummyLearner(SklLearner):
def fit(self, X, Y, W):
rows = Y.shape[0]
value = Y[np.random.randint(0, rows)]
class_vals = np.unique(Y)
prob = (class_vals == value) * 0.8 + 0.1
return DummyPredictor... |
"""Util functions for name analysis."""
import collections
import itertools
import re
from flask.globals import current_app
from namex.services.name_request.auto_analyse import DataFrameFields
from namex.utils.common import parse_dict_of_lists
from . import porter
# TODO: Fix caps and stuff...
def data_frame_to_li... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 15:28:19 2019
@author: Ngawang Tenzin
"""
# Importing required PyQt5 classess and Matplotlib
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QAction, QWidget, QGroupBox, QLabel, QVBoxLayout,
QGridLayout, QFile... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on: 2021/07/23 17:40
@Author: Merc2
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on: 2021/07/22 17:44
@Author: Merc2
'''
from PIL import Image
from omegaconf import OmegaConf
from torch.utils.data import Dataset
from pathlib import Path
import t... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('rss_gen.views',
url(r'^(?P<owner>[\w,\-,\_]+)/(?P<repo>[\w,\-,\_]+)/.*$', 'feed_xml'),
url(r'^$', 'index'),
) |
import numpy as np
import matplotlib.pyplot as plt
import h5py
from scipy.stats import gaussian_kde
class kde():
def __init__(self,U):
data = np.reshape(U,(1,-1))
xx = np.linspace(np.min(data),np.max(data),500)
kernel = gaussian_kde(data,bw_method='scott')
bins = 25
... |
# Generated by Django 2.0.8 on 2019-03-21 05:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20190317_1344'),
]
operations = [
migrations.AddField(
model_name='user',
name='fcm_pushtoken',
... |
# coding: utf-8
from __future__ import unicode_literals
from decorators import on_command
@on_command(['ㅎㅇ', '하이', 'hi'])
def run(robot, channel, tokens):
'''헬로월드를 출력'''
return channel, 'hello world'
|
#!/usr/bin/env python
# Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that a failing postbuild step lets the build fail.
"""
from __future__ import print_function
import TestGyp
import sys
if s... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""
Moves an account to the specified OU.
"""
from organizations import Organizations
import boto3
from aws_xray_sdk.core import patch_all
from logger import configure_logger
patch_all()
LOGGER = configure_logg... |
import theano
import theano.tensor as tt
import Mariana.abstraction as MABS
__all__ = ["Cost_ABC", "Null", "NegativeLogLikelihood", "MeanSquaredError", "CrossEntropy", "CategoricalCrossEntropy", "BinaryCrossEntropy"]
class Cost_ABC(MABS.UntrainableAbstraction_ABC, MABS.Apply_ABC) :
"""This is the interface a Cost... |
# @Title: 二叉搜索树的第k大节点 (二叉搜索树的第k大节点 LCOF)
# @Author: 18015528893
# @Date: 2021-01-27 15:07:45
# @Runtime: 60 ms
# @Memory: 18.7 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
k =... |
from django.db import models
# Create your models here.
class Sidebar(models.Model):
name = models.CharField(max_length=50)
route = models.CharField(max_length=150, null=True, blank=True)
description = models.TextField()
icon = models.CharField(max_length=20)
group = models.CharField(max_length=4... |
from circuits import Component, handler
from events import ContextCreatedEvent, EntitiesPreprocessedEvent
class ContextComponent(Component):
def __init__(self, context_manager):
super(ContextComponent, self).__init__()
self.context_manager = context_manager
@handler("MessageReceivedEvent")
... |
#!/usr/bin/env python3
import re
import sys
import subprocess
flex = sys.argv[1]
out = subprocess.check_output([flex, '--version'], universal_newlines=True,
stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL)
print(re.search(r'(\d+\.\d+(\.\d+)?)', out).group())
|
from random import randrange
import time
import csv
import random
import boto3
import pandas as pd
from botocore.exceptions import NoCredentialsError
#1. to return random timestamp within a range
def randomize_time(start_timestamp,end_timestamp):
return time.strftime('%b %d %Y %H:%M:%S', time.localtime(randrang... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 12 16:58:58 2018
@author: ldh
此脚本更新日间数据。
"""
# daily_signal_update.py
import os
import datetime as dt
import yaml
from sqlalchemy.types import VARCHAR,DATETIME,DECIMAL,INT
from sklearn.externals import joblib
import pandas as pd
from podaci.guosen.data import (get_tra... |
import json
from kivy.app import App
from kivy.config import ConfigParser
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.slider import Slider
from kivy.metrics import dp
from ... |
import argparse
from pathlib import Path
from os import path, getcwd, environ
from shutil import copyfile, copytree
import io
import sys
import pkg_resources
from alembic.config import main as alembic_main, CommandLine, Config
from sqlalchemy.engine import create_engine
from sqlalchemy import MetaData
from modelgen i... |
#!/usr/bin/env python
class Common(object):
"""
"""
def execute(self):
"""
"""
raise Exception('Not implemented yet')
def print_performance(self):
"""
"""
raise Exception('Print performance function is not implemented yet')
@staticmethod
def de... |
from ast import literal_eval
from collections import defaultdict
from logging import getLogger
from .utils import markup_inline_keyboard
from .settings import Dungeon
logger = getLogger(__name__)
async def stats_button_reply_phase1(chat, **_):
return await chat.send_text('Di quale tipologia dungeon vuoi le stat... |
import json
import subprocess
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
Input
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for... |
from django.contrib import admin
# Register your models here.
from .models import JobSchedAlg, Adv
class AdvInline(admin.TabularInline):
model = Adv
extra = 3
class JobSchedAlgAdmin(admin.ModelAdmin):
inlines = [AdvInline]
admin.site.register(JobSchedAlg, JobSchedAlgAdmin)
|
class OSMObject(object):
def __init__(self):
self.tags = {}
self.attribs = {}
self.bounds = None
def __repr__(self):
out = "{type} {id}".format(
type=type(self).__name__,
id=self.attribs.get("id"))
if type(self) == Way:
out += " ({way... |
import mwclientcli.libs.mwinterface
class Command(object):
"""Meta-class for every command
"""
def __init__(self):
self.args = []
self.help = None
self.name = None
self.parser = None
self.site = None
def init_parser(self, subparsers):
self.parser = subp... |
#
# A minimalist test for MCS. It starts a controller, reads in a scene
# (randomly picked) and goes forward for 10 steps. On each step,
# it saves an image
#
#
import machine_common_sense as mcs
from ai2thor_docker.x_server import startx
import time
import sys
directory = "/home/ubuntu/"
unity_app_file_path = dir... |
import aspose.slides as slides
#ExStart:ExtractEmbeddedFileDataFromOLEObject
dataDir = "./examples/data/"
outDir = "./examples/out/"
with slides.Presentation(dataDir + "shapes_ole_objects.pptx") as pres:
objectnum = 0
for slide in pres.slides:
for shape in slide.shapes:
if type(shape) is... |
import os
import subprocess
import sys
import pandas as pd
from minedatabase import utils
from minedatabase.databases import MINE
from rdkit.Chem import AllChem
def load_cdmine_rxns(mine_db, excel_file, pic_dir=""):
abrv = {"hn": "[*]"}
if pic_dir and not os.path.exists(pic_dir):
os.mkdir(pic_dir)
... |
def Settings(**kwargs):
return {
'interpreter_path':
'/orion/u/jiangthu/anaconda3/envs/tf_py3/bin/python'
}
|
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
from sqlalchemy.orm import relation, relationship, sessionmaker
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.sql.expression import null
from sqlalchemy.sql.schema import ForeignKey, UniqueCo... |
class Fact(object):
def __init__(self, measure, attributes: list):
self.measure = measure
self.attributes = attributes
def __str__(self):
return self.measure + " -> " + str(self.attributes) |
### WARINING ###
### Pool is still not operational in this situation
### This file is incomplete
import os
from zxcvbn import zxcvbn
import time
from hashlib import sha1
from multiprocessing import Pool
def hashInput(inputData):
hash_object = sha1(inputData)
hex_dig = hash_object.hexdigest()
return hex_d... |
import glob
from pathlib import Path
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
DEMO_PAGES_PATH = Path('.circleci/demo_pages')
def create_browser() -> webdriver.Chrome:
# enable browser logging
d = DesiredCapabilities.CHROME
d['goog:logg... |
import datetime
from dateutil import relativedelta
from app.controllers.base_controller import BaseController
from app.repositories import (
UserRepo,
UserEducationRepo,
)
from app.utils.date_diff_functions import date_diff_string
class UserEducationController(BaseController):
def __init__(self, request)... |
from google_images_download import google_images_download
import sys
import cv2
import os
import json
from dbr import DynamsoftBarcodeReader
dbr = DynamsoftBarcodeReader()
dbr.initLicense('LICENSE-KEY')
def decodeFile(fileName, templateName=""):
# 1D, PDF417, QRCODE, DataMatrix, Aztec Code
barcodeTypes = 0x3F... |
from tChat.command_line_argument_parser import UserArgumentParser
from tChat.irc_connection import Client
from tChat.twitch_message_parser import Parser
from tChat.customizer import Customizer
from tChat.config import Configuration, config_file_exists
from configparser import ConfigParser
import asyncio
def receive_c... |
from openslides_backend.action.generics.create import CreateAction
from openslides_backend.action.generics.update import UpdateAction
from openslides_backend.action.util.action_type import ActionType
from openslides_backend.action.util.register import register_action
from openslides_backend.models import fields
from op... |
import time
from celery import task
@task(name='add')
def add(x, y):
print('Adding task called with {} and {}'.format(x, y))
time.sleep(1)
print('Finished task')
return x + y
|
"""
@author: acfromspace
"""
import math
import os
import random
import re
import sys
def sock_merchant(n, ar):
stock = set()
pairs = 0
for socks in ar:
if socks in stock:
stock.remove(socks)
pairs += 1
else:
stock.add(socks)
return pairs
n = int(... |
import numpy as np
import matplotlib.pyplot as plt
import csv
# from pulp import *
from scipy.interpolate import interp1d
from tabulate import tabulate
from pathlib import Path
import parameters_input as inp
import plot_generator as plot
import datareader
from tictoc import tic, toc
from aggregate_load_profiler import... |
import warnings
import logging
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import redirect_to_login
from django.core import serializers
from django.core.exceptions import ImproperlyConfigu... |
#! /usr/bin/env python
class Connect(object):
"""Connect API connection."""
def __init__(self, config_dict):
"""Initialisation of all configuration needed.
:param currency: currency to deal with ( BTC, etc...)
:param config_dict: configuration dictionary for connection
... |
import numpy as np
import chainer.links as L
from chainer import Variable
from lda2vec import dirichlet_likelihood
def test_concentration():
""" Test that alpha > 1.0 on a dense vector has a higher likelihood
than alpha < 1.0 on a dense vector, and test that a sparse vector
has the opposite character. ""... |
"""Contains layer-related utility functions.
"""
import tensorflow as tf
from tensorflow.keras.layers import Concatenate, Flatten, Layer, Activation
from typing import List, Any
from .activation import Dice
def _concat(inputs: List, axis: int = -1) -> tf.Tensor:
"""Concatenate list of input, handle the case when ... |
import argparse
import gym
import gym_2048
import pickle
from play_2048 import Play2048
import torch
import torch.optim as optim
from utils import device, ReplayMemory, XceptionLikeDuelingDQN
parser = argparse.ArgumentParser(description='Hyper-parameters for the DQN training')
parser.add_argument('--epsilon', ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, Q... |
import json
import os
import random
import re
# To avoid circular imports, util modules should only import a limited
# set of shakenfist modules, mainly exceptions, logutils, and specific
# other util modules.
from shakenfist.config import config
from shakenfist import exceptions
from shakenfist import logutil
from sh... |
# -*- coding: utf-8 -*-
from logging import getLogger
from plone import api
from plone.app.dexterity.behaviors import constrains
from plone.app.textfield.value import RichTextValue
from plone.namedfile.file import NamedImage
from Products.CMFPlone.interfaces import INonInstallable
from Products.CMFPlone.interfaces.cons... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-09-27 15:09:03
# @Author : Jiabo (Raymond) Huang (jiabo.huang@qmul.ac.uk)
# @Link : https://github.com/Raymond-sci
import torch
import torch.backends.cudnn as cudnn
import sys
import os
import time
from datetime import datetime
import models
import ... |
#!/bin/python3
import math
import os
import random
import re
import sys
from timeit import default_timer as timer
from collections import Counter
# Complete the substrCount function below.
def substrCount2(n, s):
igual_p = Counter(s)
print(igual_p)
s_palindrome = sum(igual_p.values())
print(s_palindr... |
#coding:utf-8
#
# id: bugs.core_2038
# title: New EXECUTE STATEMENT implementation asserts or throws an error if used both before and after commin/rollback retaining
# decription:
# tracker_id: CORE-2038
# min_versions: []
# versions: 2.5.0
# qmid: None
import pytest
from firebird.qa ... |
# vim: set ff=unix expandtab ts=4 sw=4:
from .TsTpField import TsTpField
class TsTpDeathRateField(TsTpField):
def __init__(self, arr, tss):
if arr.max() <= 1 and arr.min() >= 0:
super().__init__(arr, tss)
else:
raise (Exception("Death rates have to have values in [0,1] {mi}... |
__all__ = [
'download',
'get',
'post',
'search',
'tiles',
'stac',
]
from . import download, get, post, search, stac, tiles
|
from django.template.response import TemplateResponse
from django.http.multipartparser import MultiPartParserError
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import REDIRECT_FIELD_NAME
#borrow MultiPartParserError to convert a exception to redirect response
cl... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcls.models.backbones.vision_transformer import TransformerEncoderLayer
from mmcv.cnn import build_norm_layer
from mmcv.runner import BaseModule
from ..builder import NECKS
from ..utils import build_2d_sincos_position_embedding
... |
import pandas as pd
import numpy as np
import os
import json
from datetime import datetime
import glob
from pathlib import Path
#############Load config.json and get input and output paths
from fullprocess import find_csv_files
with open("config.json", "r") as f:
config = json.load(f)
input_folde... |
'''
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
'''
import math
my_primes = [2, 3, 5]
def gen_primes(cnt):
for i in range(7,9999999999999,2):
if not(any(i%j == 0 for j in range(3,int(math.sqrt(i))+1))):
... |
from dataclasses import dataclass
@dataclass
class WikiPage():
title: str
text: str
links: list
word_vector: dict
def __str__(self):
return f'{self.title}'
def __eq__(self, other):
if self.text == other.text:
return True
else:
return False
|
import fh
import polygon
import redgreen
import clock
import butterfly
import biasbox
import simulated
|
import boto3
import json
from botocore.exceptions import ClientError
from importlib import import_module
import inspect
from keydra import logging as km_logging
from keydra.clients.aws.secretsmanager import SecretsManagerClient
from keydra.exceptions import ConfigException, InvalidSecretProvider
from keydra.provi... |
import unittest
from src.marks import Marks
from parameterized import parameterized, parameterized_class
from src.exampleData import Data
class MarksAddParameterizedPackage(unittest.TestCase):
def setUp(self):
self.tmp = Marks(Data().example)
@parameterized.expand([
(4, "Alicja", "Zielonka",... |
#
# Copyright (c) 2015 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import subprocess
from time import sleep
class JarCommand:
def __init__(self, options):
self.JarFilePath = options['JarFilePath']
self.KeystoreFile = options['Keystorefile']
self.KeystorePass = options['KeystorePass']
if options... |
# Generated by Django 2.2.7 on 2019-11-23 18:49
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Image',
fields=[
('id', models.AutoField(pr... |
"""Random number distributions.
At the moment, this module is not thread-safe.
"""
import abc
import math
import torch # type: ignore
class Distribution(metaclass=abc.ABCMeta):
"""Abstract base class for all random number distributions."""
@abc.abstractmethod
def fill(self, tensor: torch.Tensor) -> N... |
## -------------------------------------- ##
## Damage Calculations
## calculates the damage
## -------------------------------------- ##
from FieldClass import Field
from TypeClass import Type
from PokemanClass import Pokeman
from MoveClass import Move
from Constants import *
from random import randint
str_prv_mov = ... |
import sys
from unittest import mock
from lambda_gateway import __main__
def test_get_opts_default():
sys.argv = [
'lambda-gateway',
'index.handler',
]
opts = __main__.get_opts()
assert opts.bind is None
assert opts.port == 8000
assert opts.timeout is None
assert opts.HAND... |
from layers import BiDAFAttention
import torch
torch.manual_seed(1)
torch.random.manual_seed(1)
c = torch.randn((2, 5, 10))
q = torch.randn((2, 3, 10))
c_mask = torch.ones((2, 5))
q_mask = torch.ones((2, 5))
attention = BiDAFAttention(hidden_size=10, drop_prob=0)
result = attention(c, q, c_mask, q_mask)
print(resu... |
#!/usr/bin/env python3
# Process RDR2 information from a source (http, https, file) to a destination (analyze display, file, warehouse)
# Can also subscribe from AMQP
#
import argparse
from datetime import datetime, tzinfo, timedelta
import http.client as httplib
import json
import logging
import logging.handlers
impo... |
#!/usr/bin/env python
import argparse
import csv
import math
import numpy
from numpy import random
from numpy import add
import random
import sys
parser = argparse.ArgumentParser()
parser.add_argument("--points", action="store", type=int, default=1000000, help="Total number of points in the dataset.")
parser.add_argu... |
# Generated by Django 3.1.7 on 2021-06-02 03:13
from django_datetime.datetime import datetime
from decimal import Decimal
from django.db import migrations, models
import django.db.models.deletion
import staff_management_models.staff_group_payments.class_apps.staff_payment_status_choice
class Migration(migrations.Mig... |
def solve_me_first(a, b):
return a + b
num1 = int(input())
num2 = int(input())
res = solve_me_first(num1, num2)
print(res)
|
"""change timestamps to timestamptzs
Revision ID: 90b5b84abc6a
Revises: 6fd1f5b43824
Create Date: 2017-08-31 16:46:16.785021
"""
from alembic import op
from sqlalchemy.types import DateTime
# revision identifiers, used by Alembic.
revision = '90b5b84abc6a'
down_revision = '6fd1f5b43824'
branch_labels = None
depends... |
from django.urls import path
from project_e.charts.views import(home_view, chart_data_view)
from project_e.dealers.views import (
dealer_creation_view,
dealer_detail_view,
dealer_user_verify_view,
dealer_analytics_view,
dealer_user_verify_view,
dealer_jobs_view,
dealer_employee_detail,... |
import unittest
from time import sleep
def sleeping_gen(x):
for i in x:
sleep(.01)
yield i
def sleeping_f(x):
sleep(.01)
return x
class SleepingEmptyIter:
def __iter__(self):
return self
def __next__(self):
sleep(.01)
raise StopIteration
class SleepingClass:
... |
#! usr/bin/env python3
from os import times
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import numpy... |
import sys
from time import strftime, localtime, sleep
from os import path, remove, makedirs, getcwd
from datetime import datetime, timedelta
import logging
from PyQt5 import QtWidgets, QtGui
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from... |
"""
Set up logging
"""
import logging
# base logger from which all loggers are propagated
LOGGER = logging.getLogger()
LOGFMT = "%(asctime)s.%(msecs)03d|%(threadName)s|%(levelname)s|%(name)s|%(message)s"
DATEFMT = "%Y-%m-%d %H:%M:%S"
def set_logger(level):
"""
Setup logger
Also used by unittests
""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.