content stringlengths 5 1.05M |
|---|
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""argparse.ArgumentParser for the mini_installer test suite.
The provided parser is based on that created by typ.
"""
import typ
def ArgumentParser(host=... |
import random
import sys
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR
from data_prepare import make_data,make_data_2th
from algo_utils import *
np.random.seed(0)
random.seed(0)
# glo... |
from .group_chat_bot import WeGroupChatBot as GroupChatBot, WeGroupChatBots as GroupChatBots
|
from sqlalchemy import Column, create_engine, DateTime, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
Base = declarative_base()
class Pet(Base):
__tablename__ = "pets"
id = Column(String(20), primary_key=True)
name = Column(String(1... |
from datetime import date, datetime
from pynonymizer.database.exceptions import UnsupportedColumnStrategyError
from pynonymizer.strategy.update_column import UpdateColumnStrategyTypes
from pynonymizer.fake import FakeDataType
"""
All Static query generation functions
"""
_FAKE_COLUMN_TYPES = {
FakeDataType.STRING: ... |
#from __future__ import print_function
import json
from flask import Flask, request, redirect, make_response
app = Flask(__name__)
app.debug = True
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
s = "<html><pre>"
f = "</pre></html>"
sep = '\n============================\... |
#!/usr/bin/env python
from minibus import MiniBusTwistedClient
import sys
sys.DONT_WRITE_BYTECODE = True
class ServiceServer(MiniBusTwistedClient):
def __init__(self):
MiniBusTwistedClient.__init__(self, name="ServiceServer")
self.service_func_server("echoback", { }, { }, self.echo)
def echo(s... |
# This program is free software; you can redistribute it and/or modify it under
# the terms of the (LGPL) GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will b... |
"""
Main module of the server file
"""
# 3rd party moudles
from flask import render_template
# local modules
import app_config
# Get the application instance
connex_app = app_config.connex_app
# Read the swagger.yml file to configure the endpoints
connex_app.add_api("swagger.yaml", strict_validation=True,
... |
#!/usr/bin/env python
from pwn import *
def add_note(title, content_size, content):
p.sendline('1')
p.recvuntil('please input title: ')
p.send(title)
p.recvuntil('please input content size: ')
p.sendline(str(content_size))
p.recvuntil('please input content: ')
p.send(content)
def view_not... |
from torch.utils.data import DataLoader
from typing import NamedTuple
class Loaders(NamedTuple):
"""
Container for the data loaders
"""
train: DataLoader
test: DataLoader
|
"""
day4-part1.py
Created on 2020-12-04
Updated on 2020-12-09
Copyright © Ryan Kan
"""
# INPUT
with open("input.txt", "r") as f:
contents = f.read()[:-1]
passports = [passport.replace("\n", " ") for passport in contents.split("\n\n")]
f.close()
# COMPUTATION
# Process each passport
noValid = 0
for passp... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from signal import signal, SIGINT
from sys import exit
import psycopg2
import airly
from getkey import getkey, keys
import write_on_display
import bme280
import smbus2
import datetime
from time import sleep
conn = psycopg2.connect(
host="localhost",
database="weather_station",
user... |
from django.test import TestCase
from medicus import models as medi_models
class TestRating(TestCase):
def test_000_new_rating(self):
country = medi_models.Country.objects.create(name='Rumania')
province = medi_models.Province.objects.create(country=country, name='bla')
postal_code = medi... |
"""
Binomial Models
"""
from metrics_base import *
class H2OBinomialModel(ModelBase):
"""
Class for Binomial models.
"""
def __init__(self, dest_key, model_json):
"""
Create a new binomial model.
"""
super(H2OBinomialModel, self).__init__(dest_key, model_json,H2OBinomialModelMetrics)
def F... |
#!/usr/bin/env python
'''
Republishes ultrasonic sensors data from Arduino to normal Range messages
Rebublished bump sensors data from Arduino to fixed distance ranger Range message
_____9___0_____
| 8 1 |
|7 2|
| SONAR |
|6 3|
\ /
\5 ... |
#!/usr/bin/env python
__author__ = 'Sergei F. Kliver'
import argparse
from RouToolPa.Tools.Samtools import VariantCall
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--bam_list", action="store", dest="bam_list", type=lambda s: s.split(","), required=True,
help="Comma-separated list ... |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import torch.nn.functional as F
import cv2
from pysot.utils.bbox import corner2center
from ... |
from Music import app, OWNER
import os
import subprocess
import shutil
import re
import sys
import traceback
from Music.MusicUtilities.database.sudo import (get_sudoers, get_sudoers, remove_sudo, add_sudo)
from pyrogram import filters, Client
from pyrogram.types import Message
@app.on_message(filters.command("addmsudo... |
import requests
import json
# import dataset4
class ShopifyScraper():
def __init__(self,baseurl):
self.baseurl = baseurl
def downloadJson(self,pageNumber):
r= requests.get(self.baseurl + f'products.json?limit=250&page={pageNumber}',timeout=20)
if r.status_code !=200... |
import torch
import argparse
import os
import glob
from torch.utils.data import DataLoader, SequentialSampler
from tqdm import tqdm
from nsmc_modeling import RobertaForSequenceClassification
from bert.tokenizer import Tokenizer
from dataset import NSMCDataSet
def _get_parser():
parser = argparse.ArgumentParser(... |
from cryptography.fernet import Fernet
from faker import Faker
key = Fernet.generate_key()
f = Fernet(key)
text = Faker().text()
print('Text to encrypt:', text, '\n')
token = f.encrypt(text.encode())
print('Encrypted text:', token, '\n')
decrypted = f.decrypt(token)
print('Decrypted text:', decrypted)
|
"""
Implements command line ``python -m td3a_cpp_deep <command> <args>``.
"""
import sys
def main(args, fLOG=print):
"""
Implements ``python -m td3a_check check <command> <args>``.
"""
from pyquickhelper.cli import cli_main_helper
try:
from . import check
except ImportError: # pragma:... |
class Solution(object):
def str2int(self,s):
res=0
for i in xrange(len(s)):
res=(res<<3)+(ord(s[i])&7)
return res
def findRepeatedDnaSequences(self, s):
"""
:type s: str
:rtype: List[str]
"""
mapping={'A':0,'C':1,'G':2,'T':3}
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline ... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
from skimage import color
from sklearn.cluster import KMeans
import os
from scipy.ndimage.interpolation import zoom
def create_temp_directory(path_template, N=1e8):
print(path_template)
cur_path = path_template % np.random.randint(0, N)
while(o... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from secretpy import Gronsfeld, CryptMachine, alphabets as al
from secretpy.cmdecorators import UpperCase, Block, SaveAll
alphabet = al.GERMAN
plaintext = u"schweißgequältvomödentextzürnttypografjakob"
key = (4, 17, 9)
cipher = Gronsfeld()
print(plaintext)
enc = cipher.e... |
# -*- coding: utf-8 -*-
"""
Test programmatically setting log transformation modes.
"""
import initExample ## Add path to library (just for examples; you do not need this)
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
app = QtGui.QApplication([])
w = pg.GraphicsLayout... |
# Copyright (c) 2021-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import logging
from typing import List
import gym
import numpy as np
from dm_control import mjcf
from bisk.base import BiskEnv
from bisk.feature... |
class Solution:
def specialArray(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
if nums[0] >= n: return n
for i in range(1, n + 1):
if nums[n - i - 1] < i <= nums[n - i]: return i
return -1
|
"""
********************************************************************************
compas.utilities
********************************************************************************
.. currentmodule:: compas.utilities
animation
=========
.. autosummary::
:toctree: generated/
:nosignatures:
gif_from_im... |
import math
import networkx as nx
from src.util.gen_files import *
from src.util.virtual_run import *
def caculate_tail(S, C, totalContents):
N = len(S)
result = 0
if N * C > totalContents:
result = totalContents
else:
result = N * C
for i in range(0, N-1):
result -= ... |
from jip.dist import setup
requires_java = {
'dependencies':[
## (groupdId, artifactId, version)
('org.slf4j', 'slf4j-api', '1.7.21'),
('ch.qos.logback', 'logback-core', '1.2.2'),
('org.lucee', 'commons-lang', '2.6.0'),
('org.apache.commons', 'commons-math3', '3.6.1'),
# ... |
from typing import List, Optional
from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.responses import JSONResponse
from webapi.db.dals.user_dal import User, UserDAL
from webapi.db.schemas.token import Token
f... |
#!/usr/bin/env python3
"""
face.py
---
Face detection and landmarking utilities.
Relies on `dlib` for face-detection and `PRNet + PyTorch` for landmarking.
"""
import os
import time
import dlib
import numpy as np
import src.utils.utility as _util
from src.models.face.prnet import PRN
_mouth = slice(48, 68)
_righ... |
import warnings
import tempfile
import os
import numpy as np
import pytest
from starfish.constants import Indices
from starfish.codebook import Codebook
from starfish.intensity_table import IntensityTable
# don't inspect pytest fixtures in pycharm
# noinspection PyUnresolvedReferences
from starfish.test.dataset_fixtu... |
import modeli
def izberi_moznost(moznosti):
"""
Funkcija, ki izpiše seznam možnosti in vrne indeks izbrane možnosti.
Če na voljo ni nobene možnosti, izpiše opozorilo in vrne None.
Če je na voljo samo ena možnost, vrne 0.
>>> izberi_moznost(['jabolko', 'hruška', 'stol'])
1) jabolko
2) hruš... |
import pygame
import pygame.freetype
import src.shared_constants as sc
KEYBOARD_MOVE_DISTANCE = 1
KEYBOARD_ROTATE_ANGLE = 0.1
class App:
def __init__(self, patterns, pattern_name):
pygame.init()
self.window = pygame.display.set_mode(sc.WINDOW_SIZE)
pygame.display.set_caption("Moiré")
... |
config_DMLPDTP2_linear = {
'lr': 8.703567590317672e-06,
'target_stepsize': 0.017250397502053975,
'beta1': 0.99,
'beta2': 0.99,
'epsilon': 1.727973356862063e-08,
'lr_fb': 0.0007959054461775743,
'sigma': 0.09857259200102354,
'feedback_wd': 5.782689838884453e-06,
'beta1_fb': 0.99,
'beta2_fb': 0.9,
'epsilon_fb': 3.10816623... |
# Copyright (c) 2013 Rackspace, Inc.
# Copyright (c) 2013 Red Hat, 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 b... |
from django.shortcuts import render
from .models import City
from django.views.generic import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from .forms import CityForm
from django.urls import reverse_lazy
from django.core.paginator import Paginator
from django.contrib.messages.view... |
import json
import logging
import os
from lib_yolo import yolov3, train, utils
def main():
config = {
'training': True, # edit
'resume_training': False, # edit
'resume_checkpoint': 'last', # edit: either filename or 'last' the resume a training
'priors': yolov3.ECP_9_PRIORS, #... |
import kazoo
from prompt_toolkit.completion import Completer, Completion
from .lexer import KEYWORDS, ZK_FOUR_LETTER_WORDS
class ZkCompleter(Completer):
def __init__(self, zkcli, *args, **kwargs):
super().__init__(*args, **kwargs)
self.zkcli = zkcli
self.command = None
self.prev... |
"""
deploy cluster service to kubernetes via the API server
"""
import base64
from datetime import datetime, timedelta
import getpass
import logging
import os
import random
import re
import socket
import string
import subprocess as sp
import sys
import urllib3
from pkg_resources import resource_filename, Requirement
f... |
#!c:\users\shahe\courses\profiles-rest-api\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
"""
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list.
Note:
Return 0 if there is no such transformation sequence.
... |
import sys
import pandas as pd
from keras.preprocessing.text import Tokenizer
TABELA = sys.argv[1]
SEQCOL = 'sequence'
LABCOL = 'class'
# Declare tokenizer
tkz_seq = Tokenizer(num_words = None, split = ' ', char_level = True, lower = True)
tkz_lab = Tokenizer()
# Read file
df = pd.read_csv(TABELA)
sequencias = df[SE... |
'''
Author: ZHAO Zinan
Created: 30-Oct-2018
136. Single Number
https://leetcode.com/problems/single-number/description/
'''
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums):
result = nums[0]
... |
#-*-coding=utf8-*-
import sklearn
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
def buildClassifier_score(tra... |
import re
from typing import Optional, Tuple, TYPE_CHECKING, Dict, Union, cast
from typing_extensions import TypedDict
from collections import namedtuple
import numpy as np
from qcodes import InstrumentChannel
from .message_builder import MessageBuilder
from . import constants
from .constants import ModuleKind, SlotNr... |
import numpy as np
import sys
sys.path.append(".")
from ai.action.movement.movements.basic import *
from ai.action.movement.movements.poweron import *
import ai.actionplanner
def main(mars, times=5):
rub_object(mars, times)
def rub_object(mars, times):
for i in range(times):
rand_speed_1... |
from sanic import Sanic, response
from app.bot import bot_register
# https://api.telegram.org/bot{your_bot_token}/setWebhook?url={your_vercel_domain_url}/api/bot
app = Sanic(__name__)
@app.route("/api/bot", strict_slashes=False)
async def bot(request):
return response.text("This endpoint is meant for bot and t... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import collections
from dataclasses import dataclass
import gtn
import importlib
import logging
import numpy as np
import os
import struct
im... |
from pypixiv.ranking.body import ContentBody
from typing import Any
from pypixiv.abc import BaseRanking
class RankingInfo(BaseRanking):
def __init__(self, response: Any):
super().__init__(response)
@property
def contents(self) -> list[ContentBody]:
return [ContentBody(content) for content... |
import time
from pynput import keyboard
class StopException(Exception):
pass
class Callbacks:
"""
不同的监听方式仍然有相同的回调函数
"""
scripts = []
current_time = int(time.time())
@classmethod
def on_mouse_move(cls, x, y):
print(x, y)
@classmethod
def on_mouse_click(cls, x, y, bu... |
import logging
from kalliope.core.Lifo.LIFOBuffer import LIFOBuffer
from six import with_metaclass
from kalliope.core.Models import Singleton
logging.basicConfig()
logger = logging.getLogger("kalliope")
class LifoManager(with_metaclass(Singleton, object)):
lifo_buffer = LIFOBuffer()
@classmethod
def g... |
"""Print project status report."""
from datetime import datetime
import pandas as pd
from jinja2 import Environment, FileSystemLoader
import lib.db as db
import lib.util as util
def generate_reports():
"""Generate all of the reports."""
cxn = db.connect()
now = datetime.now()
sample_wells = get_well... |
import glob
import math
import os
import os.path as osp
import random
import time
from collections import OrderedDict
import json
import cv2
import json
import numpy as np
import torch
from ..models.model import create_model,load_model
import torch.nn.functional as F
import torchvision
class Dataset(): # for traini... |
import math
import random
from collections import namedtuple
import anytree
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import seaborn as sns
from giskard.plot import soft_axis_off
def hierarchy_pos(
G,
root=None,
width=1.0,
vert_gap=0.2,
vert_loc=0,
leaf_vs_root_... |
# 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
# distribu... |
from .default import *
from .abc import ABCRule
|
"""
Contains constants with informative error messages
"""
MALFORMED_JSON = 'Malformed JSON sent with request. Make sure you include something' \
' like the following in the request body: {"name": "playernametovalidate"}'
INVALID_NAME = 'This name is invalid. Please pick a name that is exclusi... |
import datetime
from typing import Optional, Literal
import discord
import re
from discord.ext import commands, menus
__all__ = [
"CannotPunish",
"embed_create",
"TimeConverter",
"IntentionalUser",
"IntentionalMember",
"CustomMenu",
"user_friendly_dt"
]
class CannotPuni... |
import torch.optim as optim
def get_optimizer(parameters, optim_args):
"""Get a PyTorch optimizer for params.
Args:
parameters: Iterator of network parameters to optimize (i.e., model.parameters()).
optim_args: Command line arguments.
Returns:
PyTorch optimizer specified by args_.... |
from gpiozero import MCP3008
from time import sleep
# Class
class PinPad:
# initialisation of class
def __init__(self, pin_digit_count=4, max_voltage=3.3):
self.pin_digit_count = pin_digit_count
self.max_voltage = max_voltage
self.keypad_adc_row_list = []
self.invalid_pin_digit... |
##############################################################################
# Copyright (c) 2020 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTW... |
import numpy as np
import torch
from PIL import Image
def imcascade(*imgs, savepath=None):
# imgs -- multiple pytorch tensors or numpy tensors
# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)
assert(isinstance(imgs[0], (np.ndarray, torch.Tensor)... |
from .analyzer import AnomalyAnalyzer
from .manager import AnomalyManager
from .storage import AnomalyStorage
from .generalanomaly import GeneralAnomaly
__all__ = (
'AnomalyAnalyzer',
'AnomalyManager',
'AnomalyStorage',
'GeneralAnomaly',
)
|
from django.conf.urls import patterns, url, include
from .views.staffing import (change_staffing_acl, change_staffing_acl_vendors,
search_vendors_and_people)
from .views.projects import (create_proposed_resource, delete_proposed_resource, edit_proposed_resource,
... |
from ..models import Record
from .base import BaseRepository
class RecordsRepository(BaseRepository):
__model__ = Record
|
import pytest
from brownie import interface
import brownie
def setup_uniswap(admin, alice, bank, werc20, urouter, ufactory, celo, cusd, ceur, chain, UniswapV2Oracle, UniswapV2SpellV1, simple_oracle, core_oracle, oracle):
spell = UniswapV2SpellV1.deploy(bank, werc20, urouter, celo, {'from': admin})
cusd.mint(a... |
from django.contrib import admin
from .models import CustomerReportTemplate
class CustomerReportTemplateAdmin(admin.ModelAdmin):
search_fields = [
'template_name',
]
list_display = [
'template_name',
'customer_id'
]
admin.site.register(CustomerReportTemplate, CustomerReportTem... |
#coding: utf-8
from django.db import models
# Create your models here.
class IDC(models.Model):
name = models.CharField(max_length=20, verbose_name=u'机房名称')
type = models.CharField(max_length=10, verbose_name=u'机房类型')
ips = models.CharField(max_length=60, verbose_name=u'公网IP地址')
address = models.CharFi... |
#!/usr/local/bin/python
########################################################
#
# File: AwayBot.py
# Author: Jamie Turner <jamwt@jamwt.com>
# Date: 4/11/02
#
# Description:
#
# Weird little bot that sets its away message
# according to viewers incoming IMs.
#
from toc impo... |
from __future__ import unicode_literals
from mopidy import backend as backend_api
from mopidy_spotify_tunigo import backend, library
class TestSpotifyTunigoBackend(object):
def get_backend(self, config):
return backend.SpotifyTunigoBackend(config=config, audio=None)
def test_uri_schemes(self, conf... |
from dqo.db.models import Table, Column, DataType, Database, ColumnStats, NumericStats
def employees_db_w_meta() -> Database:
table_employees = Table("employees",
[
Column("id", DataType.STRING, stats=ColumnStats(int(1e6), 0, int(1e6), True)),
... |
import time
from torch.distributions import Categorical
import torch
from torch import nn
import copy
import gym
import numpy as np
from collections import deque
import pytorch_drl.utils.model_utils as model_utils
from pytorch_drl.algs.base import Agent
from pytorch_drl.utils.memory.buffer import EpisodicBuffer
from py... |
import os
os.system("python 1_search_standard_box_spacer_0_16_greedy.py")
os.system("python 2_search_specific_box_spacer_0_16_greedy.py")
os.system("python 3_search_Epsilonproteobacteria_box_spacer_0_16_greedy.py")
os.system("python 4_concat_delete_repeat.py")
os.system("python 5_box1_box2.py")
os.system("pytho... |
import torch
from constant.readFile import getPredictData
from constant.constPath import modelPath, predictSize
def startPredict():
data = getPredictData()
l = data.shape[1]
net = torch.load(modelPath)
test_in = torch.from_numpy(data[:predictSize, :l - 1]).float()
test_out = net(test_in)
id ... |
#encoding:utf-8
import torch
import numpy as np
from ..common.tools import model_device, parse_idx
from ..callback.progressbar import ProgressBar
from pybert.train.metrics import MRR, Recall, NDCG, EIM, REIM, RIIM
from pybert.configs.basic_config import config
class Predictor(object):
def __init__(self,
... |
#!/usr/bin/python
import yaml
import requests
import requests
import csv
import sys
import json
from datetime import datetime, timedelta
from os.path import expanduser
import time
config_file = expanduser("~") + "/.datereminder/config.yml"
print config_file
mmdd = datetime.now().strftime("%m-%d")
yyyy = datetime.now()... |
print("how old are you", end=' ')
# end=' ' tells print line to not end line with new line character
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()
print(f"So, you're {age} years old, {height}cm tall and {weight}kg heavy.")
|
'''Functions to diff a local subtree with its remote.'''
import click
import requests
def repo_commits_since(repo, since_ref, headers):
if since_ref:
compare_url = repo['compare_url'].format(base=since_ref, head='master')
compare_resp = requests.get(compare_url, headers=headers)
compare_... |
import os
import os.path
import hashlib
from os.path import join as pjoin
def download_file(source, target):
return 'wget %s -O %s' % (source, target)
def get_file_list(base_path, include_list = None, exclude_list = None):
if not isinstance(include_list, (list, tuple)):
include_list = [ include_list ]
if n... |
import mock
import pytest
import unittest2
@pytest.mark.funnel
class FunnelTests(unittest2.TestCase):
def _get_class(self):
from kardboard.services.funnel import Funnel
return Funnel
def test_funnel_state(self):
config = {
'Build to OTIS': {
}
}
... |
#!/usr/bin/python3
"""
Copyright 2018-2019 Firmin.Sun (fmsunyh@gmail.com)
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 applic... |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PR... |
# Copyright 2019 UniversalQCompiler (https://github.com/Q-Compiler/UniversalQCompiler)
# 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
# Unles... |
import json
from chalice import Chalice
from chalicelib import webexteams
app = Chalice(app_name='whois_bot')
bot_email = 'whois_bot@webex.bot'
@app.route('/')
def hello():
return "Hi, this is working"
@app.route('/browsertest/{tech}')
def browser(tech):
name = webexteams.lookup(tech)
return "{name} ... |
import pygame, sys, config
import sprites
import audio
from screens.menu_settings import menu_settingsScreen
from screens.game_screen import gameScreen
from screens.menu_screen import menuScreen
from screens.choose_map_screen import chooseMapScreen
#Initialize pygame
pygame.init()
#load sprites
sprites.init()
#load au... |
#!/usr/bin/env python
import unittest
from day17 import open_doors, bfs
class TestFindsOpenDoorsFromHashAndPath(unittest.TestCase):
cases = (
('hijkl', '', ['U', 'D', 'L']),
('hijkl', 'D', ['U', 'L', 'R']),
('hijkl', 'DU', ['R']),
('hijkl', 'DUR', []),
)
def test_finds_op... |
from kafka import KafkaProducer
from kafka.errors import KafkaError
from kafka.future import log
import json
import random
import time
import re
import csv
def publish(producer, topic_name, metric_value, timestamp, unit, device_id, context):
value = {'records': [{ 'value': { 'metric_value':(metric_value), 'timesta... |
import unittest
from conans import tools
from conans.client.configure_build_environment import VisualStudioBuildEnvironment
from conans.test.utils.conanfile import MockConanfile, MockSettings
class BuildEnvironmentHelpers(unittest.TestCase):
def test_visual(self):
settings = MockSettings({})
con... |
import math
import os
from collections import defaultdict
import PIL
from PIL import Image
from tqdm import tqdm
import torch
from torch import nn, utils
from torchvision import models, datasets, transforms
from utils import *
from .vision import VisionDataset
image_types = ['full_image', 'person_full']
image_size ... |
"""Serialization strategy based on the Pickle protocol."""
from typing import Any, BinaryIO
from dagger.serializer.errors import DeserializationError, SerializationError
class AsPickle:
"""
Serializer implementation that uses Pickle to marshal/unmarshal Python data structures.
Reference: https://docs.p... |
def bubble_sort(array):
n = len(array)
for j in range(n - 1, 0, -1):
swapped = False
for i in range(j):
if array[i] > array[i + 1]:
swap(array, i, i + 1)
swapped = True
if not swapped:
break
def swap(array, i, j):
array[i], array[j] = array[j], array[i]
a = [5, 15, 10, 30, 3, 1, 8, 4]
bubble_... |
from distutils.core import setup
with open('README.rst') as f:
long_description = f.read()
setup(
name='dispatchonvalue',
version='0.9.9',
author='Ian Macinnes',
author_email='ian.macinnes@gmail.com',
packages=['dispatchonvalue', 'dispatchonvalue.test'],
url='https://github.com/minimind/di... |
"""
Module defining a Falcon resource to provide login session info
Copyright (C) 2016 ERT Inc.
"""
import falcon
import api.json as json
from api.auth import auth
route = "user"
class User():
"""
Falcon resource object providing API login session info
"""
def on_get(self, request, resp):
"... |
import util3d
import gentrack
import gentrackdata
import random
import MAIN
import pygame
enemyNumber = 20
happyNumber = 80
treeNumber = 50
class Terrain:
def __init__(self):
self.enemies = []
self.happy = []
self.trees =[]
self.lap_count = 0
gentrack.run()
self.pixe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.