content stringlengths 5 1.05M |
|---|
# Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# 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
from requests.exceptions import MissingSchema
from bs4 import BeautifulSoup as soup
import re
import sys
import time
agent = requests.utils.default_headers()
agent.update({
"User-Agent":'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',... |
#
# Copyright 2019 BrainPad Inc. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... |
# ***** Minimum Pick-up Heuristic Function *****
# using Floyd-Warshall algorithm implemented on state, we compute the minimum distance to go in between all nodes
# then, this function will evaluate each node with the sum of the mimimun distance from current position to each pickup and from... |
import os
import sys
from pathlib import Path
root_dir = Path(__file__).resolve().parent.parent
sys.path.append(root_dir)
BASE_DIR = Path(__file__).resolve().parent.parent
root_dir_content = os.listdir(BASE_DIR)
PROJECT_DIR_NAME = 'foodgram_project'
if (
PROJECT_DIR_NAME not in root_dir_content
or no... |
from .metrics import (cd, fscore, emd)
from .mm3d_pn2 import (nms, RoIAlign, roi_align, get_compiler_version, get_compiling_cuda_version,
NaiveSyncBatchNorm1d, NaiveSyncBatchNorm2d, sigmoid_focal_loss, SigmoidFocalLoss, ball_query, knn,
furthest_point_sample, furthest_point_sample_with_dist, three_interpolate... |
from libmuscle.outbox import Outbox
from libmuscle.mcp.message import Message
from copy import copy
import pytest
from ymmsl import Reference
@pytest.fixture
def outbox():
return Outbox()
@pytest.fixture
def message():
Ref = Reference
return Message(
Ref('sender.out'), Ref('receiver.in'),
... |
from django.urls import path
from django.contrib.auth.views import LoginView
from . import views
urlpatterns = [
path('donorlogin', LoginView.as_view(template_name='donor/donorlogin.html'), name='donorlogin'),
path('donorsignup', views.donor_signup_view, name='donorsignup'),
path('donor-dashboard', views.d... |
from baseline.tf.tfy import *
import json
import os
import sys
from google.protobuf import text_format
from tensorflow.python.platform import gfile
from tensorflow.contrib.layers import fully_connected, xavier_initializer
from baseline.model import Tagger, create_tagger_model, load_tagger_model
import tensorflow as tf
... |
import unittest
from request_build_helper import RequestBuildHelper
from boofuzz import *
from configuration_manager import ConfigurationManager
class RequestBuilderHelperTests(unittest.TestCase):
def setUp(self):
# Just init block for boofuzz
s_initialize(self.id())
Configurat... |
from django.db import models
# Create your models here.
class Route(models.Model):
original_url = models.URLField(help_text= "Add the original URL that you want to shorten.")
key = models.TextField(unique= True, help_text= "Add any random characters of your choice to shorten it.")
def __str__(self):
... |
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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 requi... |
import websockets
import asyncio
import utils
from constants import SERVER_HOST,LOCAL_SERVER_PORT
from answerable_channels import FunctionalChannel,remote, RemoteException
import logging
import aioconsole
import pathlib
import authenticate_box
class Client(FunctionalChannel):
async def send_ac_message(self,m)... |
import json
import os
import gym
import ray
from ray.tune import run_experiments
from ray.tune.registry import register_env
from sagemaker_rl.ray_launcher import SageMakerRayLauncher
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.exception import UnityWorkerInUseException
from mlagents_envs... |
from __future__ import absolute_import
from infi.gevent_utils.os import path
import sys
import os
sys.path.append(os.path.dirname(__file__))
from utils import GreenletCalledValidatorTestCase
class PathTestCase(GreenletCalledValidatorTestCase):
def test_exists(self):
self.switch_validator.assert_called(0)... |
###################################################################
# This file is a modification of the file "camera.py" from the #
# RPi Telecine project. I've included that project's header and #
# copyright below. #
##############################################... |
from __future__ import absolute_import
import os, re, collections
import requests, nltk
import numpy as np
import pandas as pd
import tensorflow as tf
import xml.etree.ElementTree as ET
from TF2.extract_features_Builtin import *
type = 'bert'
if type == 'bert':
bert_folder = 'Pretrained/uncased_L-12_H-768_A-12/... |
import cv2
import os
import math
import numpy as np
import random
import h5py
sequences = ['Basketball', 'Bird1', 'BlurCar1', 'Bolt2', 'Box', 'Car1', 'CarDark',\
'ClifBar', 'Diving', 'DragonBaby', 'FaceOcc1', 'Freeman1', 'Freeman4', 'Girl', 'Girl2', 'Human3', 'Human6',\
'KiteSurf', 'Liquor', 'Ironman', 'Sk... |
import logging
import traceback
from flask import Blueprint
from flask_restplus import Api
from sqlalchemy.orm.exc import NoResultFound
import settings
log = logging.getLogger(__name__)
api_blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(
app=api_blueprint,
version='1.0.0',
title='M... |
import torch
import torch.nn as nn
import math
class DotProductAttention(nn.Module):
def __init__(self, clip = None, return_logits = False, head_depth = 16, **kwargs):
super().__init__(**kwargs)
self.clip = clip
self.return_logits = return_logits
self.inf = math.inf# = 1e+10
self.scale = math.sqrt(head_dep... |
"""
riotgears plugin manager
Manages the plugins
"""
from abc import abstractmethod
import importlib.util
from importlib.util import spec_from_file_location
import inspect
import os.path
import sys
from pathlib import Path
class Registry(object):
# Singleton instance
_instance = None
def __new__(cls,... |
"""
FactSet Ownership API
FactSet’s Fund Ownership API gives access to both **Holdings** and **Holders** data.<p> Factset's Holdings endpoints gives access to all the underlying securities and their position detils held within a given fund. Fund Types supported include Open-End Mutual Funds, Closed-end Mutual ... |
# -*- coding: utf-8 -*-
"""Runs featurization and computes feature statistics"""
import os
import warnings
import matplotlib.cm as cm
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
from pymatgen import Structure
from scipy import stats
from .predict import RUNNER
THIS_DIR = os.path.dirna... |
import os
from dbutils import create_connection
from dbutils import insert_data
from dbutils import read_schema
from dbutils import set_time_zone
from dbutils import EXAMPLE_DATA
INGEST_EXAMPLES = False
if __name__=='__main__':
with create_connection() as con:
# create tables
cur = con.cursor()
... |
from __future__ import absolute_import, print_function
import pytest
from moment_polytopes import *
def test_two_three_six(algorithm):
R = external_tensor_product([2, 3, 6])
T = ressayre_tester(R, algorithm=algorithm)
# one of the many inequalites for 2 x 3 x 6 (cf. Wernli/Klyachko)
assert T.is_ressa... |
n = int(input())
A = []
B = []
C = []
D = []
S = 0
L = []
dt = dict()
for i in range(n):
a,b,c,d = map(int,input().split())
A.append(a)
B.append(b)
C.append(c)
D.append(d)
for i in A:
for j in B:
L.append(i+j)
for i in C:
for j in D:
try:
dt[i+j] +=1
e... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from optparse import OptionParser
import os
import sys
import re
import json
import hoi4tools.parser
def main():
parser = OptionParser()
parser.add_option("-d", "--stats-directory", dest="directory",
help="directory containing the stats files of hoi4... |
import lark
import itertools
from collections import defaultdict as dd
preorder = (
'class_',
'method',
'and_exp',
'or_exp',
'ternary',
'if_stmt',
'while_lp',
'typecase',
'store_field',
'ret_exp'
)
#generate assembly code from the parse tree
class Generator(lark.visitors.Visit... |
import sys
import torch
import torch.nn as nn
import dgl.function as fn
from .labels import role_codec, frame_codec
class Embedding(nn.Module):
"""Linear -> BatchNorm -> Activation"""
def __init__(
self,
in_feats=64,
out_feats=64,
activation='relu',
... |
import requests
import bs4
import typing
import pathlib
class Libgen:
def __init__(
self,
site: str = "libgen.is",
verbose: bool = False,
headers: dict = {"User-Agent": "Not A Bot"},
):
self.site = site
self.url = f"https://{self.site}"
self.headers = h... |
from datetime import datetime
import json
colors = {
"❤️": 731625542490783814, # red
"💛": 731625689660522556, # yellow
"💚": 731625734338248775, # green
"💙": 731625764981702716, # blue
"💜": 731625799307755660, # purple
}
# with open("data/db/guilds/1","w") as f:
# json.dump(colors,f)
#... |
import mpl_toolkits.mplot3d
import matplotlib.pyplot as plt
import numpy as np
def fn(x, y):
"""f(x, y) = (1/20) * x**2 + y**2"""
return x**2 / 20 + y**2
def fn_derivative(x, y):
return x/10, 2*y
if __name__ == '__main__':
x = np.linspace(-10, 10, 100) # x 좌표들
y = np.linspace(-10, 10, 100) # y... |
"""Portal.
The entrypoint is Portal, a rule that teleports a sprite from one portal sprite
position to another.
"""
from . import abstract_rule
import numpy as np
class Portal(abstract_rule.AbstractRule):
"""Makes a sprite teleport if it enters a portal sprite."""
def __init__(self, teleporting_layer, port... |
# -*- encoding: utf-8 -*-
{
'name': 'Odooku Amazon S3',
'description': 'Amazon S3 integration for Odoo',
'version': '0.1',
'category': 'Hidden',
'author': 'Raymond Reggers',
'depends': ['base'],
'data': [],
'auto_install': True,
'post_init_hook': '_force_s3_storage',
}
|
description = 'vacuum system monitoring'
group = 'lowlevel'
tango_base = 'tango://phys.kws3.frm2:10000/kws3/'
s7_analog = tango_base + 's7_analog/'
devices = dict(
pi2_1 = device('nicos.devices.tango.Sensor',
description = 'pressure in selector',
tangodevice = s7_analog + 'pi2_1',
unit = ... |
# @filename:generate_conformers.py
# @usage:
# @author: AbhiramG
# @description: generates conformers for each mol2 file in folder
# @tags:Docking
# @version: 1.0 beta
# @date: Tuesday Jan 13 2015
import os
import sys
import mds
import glob
import time
start_time = time.time()
library_ligand = []
# read all the molecu... |
num1 = 10
mum2 = 20
num3 = 30
num4 = 40
|
from numpy import concatenate, hstack, ones, zeros
from numpy.random import permutation, rand, randn
# Fonction carré
def fcarre(x):
return x * x
# Génère n vrais échantillons
def generate_real_samples(n):
# Génère un vecteur d'entrées entre -0.5 et 0.5
X = rand(n) - 0.5
# Génère le vecteur de sortie... |
# coding=utf-8
#
# pylint: disable = wildcard-import, unused-wildcard-import
# pylint: disable = missing-docstring, invalid-name
# pylint: disable = too-many-statements, protected-access, unused-variable
"""
Copyright (c) 2019, Alexander Magola. All rights reserved.
license: BSD 3-Clause License, see LICENSE for mo... |
import os
import json
import numpy as np
import torchvision
from .util import read_image, read_image_resize, resize_bbox
class NoAnnotaion(Exception):
pass
class VRDBboxDataset:
def __init__(self, data_dir, split='train'):
self.data_dir = data_dir
json_file = os.path.join... |
class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
stack = []
s3 = -float("inf")
for n in nums[::-1]:
if n < s3: return True
while stack and stack[-1] < n: s3 = stack.pop()
sta... |
# Un-comment the line for your Lab to run the tests.
# Do NOT commit this file, since it will lead to CONFLICTS with teammates.
# import labs.lab1_drive_system
# import labs.lab2a_touch_sensor |
"""
Created on Fri May 7 2021
Copyright (c) 2021 - Joshua Sizer
This code is licensed under MIT license (see
LICENSE for details)
"""
def merge_sort(arr, low=0, high=None):
"""Sort the given array using merge sort.
Runtime average and best case is O(nlog(n)).
Arguments:
arr: The array to sort.
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# Copyright (c) 2018 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 app... |
import requests
r = requests.get("https://newsapi.org/v1/sources?category=general")
#print(r.json())
sources = r.json()["sources"]
ids = []
for source in sources:
ids.append(source["id"])
print(ids) |
#!/usr/bin/env python3
# Foundations of Python Network Programming, Third Edition
# https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter01/getname.py
import socket
if __name__ == '__main__':
hostname = 'maps.google.com'
addr = socket.gethostbyname(hostname)
print('The IP address of {} is {}'.format(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.utils.timezone import utc
import datetime
class Migration(migrations.Migration):
dependencies = [
('movietrailer', '0019_auto_20170320_2009'),
]
operations = [
migrations... |
import codecs
from datetime import datetime
from influxdb_client import WritePrecision, InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
with InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org", debug=False) as client:
query_api = client.query_api()
p = Po... |
from greshunkel.build import POSTS_DIR
from greshunkel.utils import parse_variable
from greshunkel.slimdown import Slimdown
from greshunkel.review_loader import ReviewLoader
import subprocess
from os import listdir
DEFAULT_LANGUAGE = "en"
# Question: Hey qpfiffer, why is this indented all weird?
# Man I don't know le... |
import sys
import traceback
from discord.ext.commands import *
import discord
import bot_database
import bot_errors
import bot_helpers
f = open("data/token.txt")
TOKEN = f.readline().strip()
f.close()
# Fallback for reaction adds / removes when Bot is offline:
# 1. For every combination of {messageID + Emoji} that ... |
#!/usr/bin/env python3
from .utils import *
from .base import Wrapper
from .runner_wrapper import Runner
from .logger_wrapper import Logger
from .torch_wrapper import Torch
from .openai_atari_wrapper import OpenAIAtari
from .reward_clipper_wrapper import RewardClipper
from .timestep_wrapper import AddTimestep
from .mo... |
import mysql.connector
import pytest
import socket
import threading
import time
from httplib2 import Http
from json import dumps
import requests
_total = 0
_executed = 0
_pass = 0
_fail = 0
_skip = 0
_error = 0
_xpass = 0
_xfail = 0
_current_error = ""
_suite_name = None
_test_name = None
_test_status = None
_test_sta... |
"""
#@Author: Frankln Kenghagho
#@Date: 04.04.2019
#@Project: RobotVA
"""
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
#select a GPU if working on Multi-GPU Systems
#Several GPUs can also be selected
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
from TaskManager import *
"""Template To Train RobotVQ... |
#coding=utf-8
import os
import json
from os.path import sameopenfile
showCount = 4
def update():
with open("songlist.json", encoding="utf-8") as f:
songlist = json.loads(f.read())
result = ""
if len(songlist) == 0:
result = "当前队列为空"
else:
result = "【正在唱】\n{}\n".format(songlis... |
import numpy as np
import tensorflow as tf
from t3f import nn
class _NeuralTest():
def testKerasDense(self):
# Try to create the layer twice to check that it won't crush saying the
# variable already exist.
x = tf.random_normal((20, 28*28))
layer = nn.KerasDense(input_dims=[7, 4, 7, 4], output_dim... |
import os
import mido
from mido import MidiFile
for file_name in os.listdir('schubert_lieder'):
if '.mid' in file_name:
# print file_name
full_path = './schubert_lieder/' + file_name
print('==========================================================')
print(full_path)
mid = MidiFile(full_path)
# create a... |
load("@bazel_skylib//lib:paths.bzl", "paths")
# py_test_module_list creates a py_test target for each
# Python file in `files`
def py_test_module_list(files, size, deps, extra_srcs, name_suffix="", **kwargs):
for file in files:
# remove .py
name = paths.split_extension(file)[0] + name_suffix
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 20 09:48:12 2021
@author: leyuan
"""
import numpy as np
import matplotlib.pyplot as plt
# def _numerical_gradient_no_batch(f, x):
# h = 1e-4 # 0.0001
# grad = np.zeros_like(x)
# for idx in range(x.size):
# tmp_val = x[idx]
# x[idx] = f... |
from flask_pymongo import PyMongo
from pymongo_inmemory import MongoClient
from bson import ObjectId
USE_REAL_DB = False
def get_db(app):
games = None
if (USE_REAL_DB):
# Actual original code
mongo = PyMongo(app)
games = mongo.db.get_collection('games')
else:
# In Memory... |
import pyaudio
import time
import numpy as np
class Player:
def __init__(self, module):
self.module = module
self.stream = None
self.output = np.zeros([self.module.framesize], dtype=np.float32)
def __enter__(self):
self.pyaudio = pyaudio.PyAudio()
return self
def ... |
import math
from collections import Iterable
import game.game_data.cells.Cell as cell
import game.game_data.units.Unit as unit
from game import pygame_
from game.logs.Logs import Logs
from .Command import Command
# устанавливаем цвет логов
from ..game_data.Data import Player
log = Logs("Green")
def all_elements(val... |
from argparse import ArgumentParser
import sys
from gather import (
__version__,
core,
handlers,
log,
params,
util,
)
DEFAULT_EPILOG = "The default is %(default)s."
def get_arg_parser():
p = ArgumentParser(
description = """Detect sets of files named with incrementing numbers,
... |
from __init__ import app, db, socketio, config
import requests, time
from include import websocket
from classes.user import UserData
from classes.user_details import UserDetailData
from classes.images import ImagesData
from classes.consultations import ConsultationData
from classes.site_settings import site
from cl... |
# Copyright 2020 Hieu Nguyen
#
# 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, ... |
"""This module contains custom serializer classes."""
import copy
import inspect
from collections import OrderedDict
import inflection
from django.db import models, transaction
from django.utils import six
from django.db.models.fields.files import FieldFile
from django.utils.functional import cached_property
from rest... |
c = input().strip()
fr = input().split()
n = 0
for i in fr:
if c in i: n += 1
print('{:.1f}'.format(n*100/len(fr)))
|
import pygame
from spritesheetparser import Spritesheet
class Player(pygame.sprite.Sprite):
def __init__(self,engine):
pygame.sprite.Sprite.__init__(self)
self.engine = engine
self.friction = -0.09
self.image = Spritesheet('resources/Blockz').get_sprite('white.png')
self.image = pygame.transform.scale(self.... |
import inspect
import rhetoric.config.predicates
from rhetoric.exceptions import ConfigurationError
from rhetoric.util import viewdefaults
class ViewsConfiguratorMixin(object):
@viewdefaults
def add_view(self,
view=None,
route_name=None,
request_method=None... |
from os import listdir
from datetime import datetime
from os.path import isfile, join
import zipfile
import json
def extract_data_from_zip(target_file):
"""unzip the file, parse the data and return a list of CVEs"""
file = zipfile.ZipFile(target_file, "r")
json_file = file.open(file.namelist()[0])
d... |
import datetime
from itertools import chain
import json
import re
from urllib.parse import quote as urlquote
from django.utils.html import format_html, mark_safe
from actionkit.api.event import AKEventAPI
from actionkit.api.user import AKUserAPI
from actionkit.utils import generate_akid
from event_store.models import... |
import tensorflow as tf
import tensorflow.contrib.layers as layers
import sys
import numpy as np
def build_q_func(network, num_experts, hiddens=[256], dueling=True, layer_norm=False, **network_kwargs):
assert isinstance(network, str)
if isinstance(network, str):
from baselines.common.models import get... |
#Made by Andreas L. Vishart
#Give the script an input (.com) or output (.out/.log) file with fragments in it.
#Then the vector and distace between the donor and the acceptor will be printed.
#------------------------Packages------------------------
import numpy as np
import argparse
#------------------------Parameter... |
import cv2
import utils
img_left_original = cv2.imread("./MyData06/IMG/left_2019_08_11_15_35_48_328.jpg")
img_center_original = cv2.imread("./MyData06/IMG/center_2019_08_11_15_35_48_328.jpg")
img_right_original = cv2.imread("./MyData06/IMG/right_2019_08_11_15_35_48_328.jpg")
img_l_o_rgb = utils.bgr2rgb(img_left_orig... |
# -*- coding: utf-8 -*-
from pyramid_oereb.standard.xtf_import.util import parse_string, parse_multilingual_text, get_tag
class LegendEntry(object):
TAG_LEGEND = 'Legende'
TAG_LEGEND_ENTRY = 'OeREBKRMtrsfr_V1_1.Transferstruktur.LegendeEintrag'
TAG_SYMBOL = 'Symbol'
TAG_SYMBOL_BIN = 'BINBLBOX'
TAG... |
# Copyright (c) 2014-2018, Dr Alex Meakins, Raysect Project
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... |
"""
usage:
pv relationship create --typeName=<val> --end1Guid=<val> --end1Type=<val> --end2Guid=<val> --end2Type=<val> [--status=<val>]
pv relationship read --relationshipGuid=<val> [--extendedInfo]
pv relationship update --relationshipGuid=<val> [--status=<val>]
pv relationship delete --relationshipGu... |
import sys
from collections import defaultdict, deque
def distance(nodes, start, target):
queue = deque()
visited = dict()
queue.append((start, 0, start))
queue.append((target, 0, target))
visited[start] = (0, start)
visited[target] = (0, target)
while queue:
node, dist, path_id ... |
from rlbot.agents.base_agent import SimpleControllerState
from maneuvers.maneuver import Maneuver
from util.curves import curve_from_arrival_dir
from util.rlmath import sign
from util.vec import Vec3, norm, proj_onto_size
def choose_kickoff_maneuver(bot) -> Maneuver:
# Do we have teammates? If no -> always go fo... |
#!/usr/bin/env python
#
# Autotune flags to LLVM to optimize the performance of apps/raytracer.cpp
#
# This is an extremely simplified version meant only for tutorials
#
import adddeps # fix sys.path
import opentuner
from opentuner import ConfigurationManipulator
from opentuner import EnumParameter
from opentuner imp... |
import sys
import os
from setuptools import setup
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
from scarab import version
def get_version():
return version
setup(
name="Scarab",
version=get_version(),
packages=["scarab"],
install_requires=[
"falcon",
"jinja2",... |
#!/usr/bin/python
import sys
from Tkinter import *
import socket
import struct
import comms
class comms_link:
CMD_QUERY_ALL = 0
CMD_TRIGGER = 1
CMD_EXIT = 2
STATUS_OK = 0
STATUS_FAIL = 1
ENCODE_ASCII = 0
ENCODE_UTF8 = 1
def __init__(self, server_loc):
self.server_loc... |
import os, uuid, sys,logging
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__
from azure.core.exceptions import ResourceExistsError
from pathlib import Path
import configparser
TOP_DIR = Path(__file__).resolve().parent.parent
config = configparser.ConfigParser()
config.read(s... |
# Copyright 2021 Sony Group Corporation.
#
# 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 ... |
# Generated by Django 2.2.2 on 2019-08-02 13:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0068_auto_20190802_1315'),
]
operations = [
migrations.CreateModel(
name='ProjectOrgani... |
import pytest
import os
import re
import tempfile
import shutil
# hacky way to use a different upload_dir when testing
tmpd = tempfile.mkdtemp()
os.environ['UPLOAD_DIR'] = tmpd
from werkzeug.datastructures import FileStorage
from starter_1 import create_app
@pytest.fixture()
def app():
db_fd, db_file = tempfile.... |
from metrics_test import MetricsTest
import matplotlib.pyplot as plt
import os
import numpy as np
# locals
import utils
class DecTest(MetricsTest):
def __init__(self):
super().__init__()
def check_config(self, config):
super().check_config(config)
def collect_data(self, config):
... |
import grp
import os
import pwd
import pytest
from unit.applications.lang.go import TestApplicationGo
from unit.option import option
from unit.utils import getns
class TestGoIsolation(TestApplicationGo):
prerequisites = {'modules': {'go': 'any'}, 'features': ['isolation']}
def unpriv_creds(self):
n... |
import logging
import signal
import threading
import time
import pika
from pika import exceptions
import gromozeka.app
from gromozeka.brokers.base import BrokerInterface
from gromozeka.primitives import Task
APP_ID = 'gromozeka'
CONSUMER_ID_FORMAT = "{exchange}.{exchange_type}.{queue}.{routing_key}"
PIKA_CONNECTION_... |
#!/usr/bin/env python
# DickServ IRC Bot - Developed by acidvegas in Python (https://acid.vegas/dickserv)
# cryptocurrency.py
import httplib
def get(coin):
api = httplib.get_json('https://api.coinmarketcap.com/v1/ticker/?limit=500')
data = [item for item in api if (coin.lower() == item['id'] or coin.upper() == ite... |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: 0.0
@author: hailang
@Email: seahailang@gmail.com
@software: PyCharm
@file: snake_env.py
@time: 2018/6/21 15:45
"""
import numpy as np
import gym
from gym.spaces import Discrete
class SnakeEnv(gym.Env):
SIZE=100
def __init__(self,ladder_num,dices):
... |
import dlib
from dfd import assets
def test_face_landmarks_model_loads():
dlib.shape_predictor(str(assets.FACE_LANDMARKS_MODEL_PATH)) |
from setuptools import setup
__version__ = ''
#pylint: disable=exec-used
exec(open('pman/version.py').read())
setup(
name='panda3d-pman',
version=__version__,
keywords='panda3d gamedev',
packages=['pman', 'pman.templates'],
setup_requires=[
'pytest-runner'
],
tests_require=[
... |
# -*- coding: utf-8 -*-
from vindauga.constants.command_codes import wnNoNumber, wpCyanWindow
from vindauga.constants.window_flags import wfGrow, wfZoom
from vindauga.gadgets.calendar import Calendar
from vindauga.types.rect import Rect
from vindauga.widgets.window import Window
class CalendarWindow(Window):
nam... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def top_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):
""" Filter a distribution of logits using top-k, top-p (nucleus) and/or threshold filtering
Args:
logits: logits distribution shape (vocabulary size)
... |
#!/usr/bin/env python
import sys
import argparse
import json
from typing import List
from decimal import Decimal
try:
from pymultisig.btc_utils import estimate_transaction_fees
except ModuleNotFoundError:
from btc_utils import estimate_transaction_fees
def generate_outputs(address: str,
... |
from oarepo_model_builder.builders import process
from oarepo_model_builder.builders.python import PythonBuilder
from oarepo_model_builder.builders.utils import ensure_parent_modules
from oarepo_model_builder.stack import ModelBuilderStack
class PythonStructureBuilder(PythonBuilder):
TYPE = 'python_structure'
... |
""" All modules that use the TimeSeriesMediator.
The classes inherit from the AbstractTimeSeriesModel.
Each model is kept as its own class so new behavior can be added
individually as needed.
"""
from gamebench_api_client.models.dataframes.time_series.abstract_time_series import AbstractTimeSeriesModel
... |
factor = int(input())
n = int(input())
numbers = []
for x in range(1, (n * factor) + 1):
if x % factor == 0:
numbers.append(x)
print(numbers) |
# coding=utf-8
# !/usr/bin/env python
"""
:mod:"chempiler_client" -- User interface for the Chempiler
===================================
.. module:: chempiler_client
:platform: Windows, Unix
:synopsis: User interface for the Chempiler
.. moduleauthor:: Graham Keenan <1105045k@student.gla.ac.uk>
.. moduleauthor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.