content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import unittest, time, ConfigParser, HTMLTestRunner, sys
from lib import gateway_func
reload(sys)
sys.setdefaultencoding('utf-8')
class test_iax_endpoint(unittest.TestCase):
def setUp(sel... |
num1, num2 = list(map(int, input().split()))
userlist1 = []
for i in range(num2):
user_list = list(map(float, input().split()))
userlist1.append(user_list)
zipped = list(zip(*userlist1))
print(zipped)
for i in zipped:
print(sum(i)/num2)
|
from connector import create_connection
def associated_animals(owner):
animal_data =[]
animals = associated_animal_info(owner)
for items in animals:
animal_data.append(items)
animal_data.append(' ')
return animal_data
def associated_animal_info(owner:str):
cnx2 = create_c... |
import Q
from Q.p_vector import PVector
def test_mk_col():
"""Test the Q.mk_col() functionality
Input is list, output is PVector"""
in_vals = [1, 2, 3, 4]
vec = Q.mk_col(in_vals, Q.I1)
assert(isinstance(vec, PVector))
assert(vec.length() == len(in_vals))
assert(vec.qtype() == Q.I1)
pr... |
"""Jira issues collector."""
import re
from typing import Union
from base_collectors import SourceCollector
from collector_utilities.type import URL, Value
from source_model import Entities, Entity, SourceMeasurement, SourceResponses
class JiraIssues(SourceCollector):
"""Jira collector for issues."""
SPRIN... |
import logging
from .suncg_eval import do_suncg_evaluation
def suncg_evaluation(dataset, predictions, iou_thresh_eval, output_folder, box_only, epoch=None, is_train=None, eval_aug_thickness=None, **_):
logger = logging.getLogger("maskrcnn_benchmark.inference")
if box_only:
logger.warning("evaluation ... |
from typing import Any, List, Optional
import torch
from torch import LongTensor, Tensor
from torch_geometric.data import Data, Batch
from torch_geometric.nn.pool.consecutive import consecutive_cluster
from torch_geometric.nn.pool.pool import pool_edge, pool_batch, pool_pos
from torch_scatter import scatter, scatter_s... |
from django.core.exceptions import ValidationError
from django.test import TestCase
from ..models import ApplicationToken, AuthorizedService
class ApplicationTokenTest(TestCase):
def test_text_representation(self):
service = AuthorizedService.objects.create(
data={"service": "authorized_serv... |
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, NoReturn
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
from src.constants import ROOT_DIR
from src.logger import get_logger
logger = get_... |
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Fotolito(models.Model):
FINALIDADE_CHOICES = (
('OFFSET', 'Impressão Off Set'),
('VERNIZ', 'Reserva Verniz'),
('SILK', 'Silk Scren'),
)
CAMADA_CHOICES = (
('LEGI... |
from difflib import context_diff
import sys
# sys.stdout = open('output_3.txt', 'w')
fw = open('output_3.txt', 'w')
with open('document_1.txt', 'r', encoding='UTF-8') as f1:
with open('document_2.txt', 'r', encoding='UTF-8') as f2:
diff = context_diff(f1.readlines(), f2.readlines(), fromfile='f1', t... |
from __future__ import absolute_import
import json
import logging
import datetime as dt
import calendar
import decimal
from .util.serialization import transform_series, transform_array
import numpy as np
try:
import pandas as pd
is_pandas = True
except ImportError:
is_pandas = False
try:
from dateut... |
"""
Tests for the
:module`regression_tests.parsers.c_parser.exprs.binary_ops.div_op_expr`
module.
"""
from tests.parsers.c_parser import WithModuleTests
class DivOpExprTests(WithModuleTests):
"""Tests for `DivOpExpr`."""
def test_div_op_expr_is_div_op(self):
div_op_expr = self.get_expr('... |
import setuptools
with open("README.md","r",encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="BIT_framework",
version="0.0.1",
author="wxl",
author_email="847084723@qq.com",
description="A dialog framework",
#packages=setuptools.find_packages(),
packages=['BI... |
from numpy import tanh
def tanh_based_scaleup(shape, inflection_time, lower_asymptote, upper_asymptote=1.0):
"""
return the function t: (1 - sigma) / 2 * tanh(b * (a - c)) + (1 + sigma) / 2
:param shape: shape parameter
:param inflection_time: inflection point
:param lower_asymptote: lowest asympt... |
def Letter_Applier(string):
letters = ['A','C','T','G']
rearanged_list = [string]
string2 = list(string)
for values1 in range(len(string2)):
for values2 in letters:
string2 = list(string)
string2[values1] = values2
string2 = ''.join(string2)
... |
"""
Created on 19/09/2012
@author: victor
"""
import os
import json
import shutil
import pyproct.tools.scriptTools as scripts_common
from pyproct.driver.observer.observable import Observable
from pyproct.driver.parameters import ProtocolParameters
class WorkspaceHandler(Observable):
def __init__(self, workspace_... |
# Django
from django.contrib.auth.models import Group, User
# Rest Framework
from rest_framework.viewsets import ReadOnlyModelViewSet
# Project apps
from rest_framework_include_mixin import QueryOptimizerMixin
# This app
from .models import UserProfile
from .serializers import GroupSerializer, ProfileSerializer, Use... |
from django import forms
from .models import *
class SportsRegForm(forms.ModelForm):
class Meta:
sem=(
('',"Select Year of study"),
('1st',"1st Year"),
('2nd',"2nd Year"),
('3rd',"3rd Year"),
)
model = SportsParticipant
fields = '__all__'
exclude... |
# Examples
food = {"vegetables": ["carrots", "kale", "cucumber", "tomato"]}
print(food["vegetables"][1])
for veg in food["vegetables"]:
print(veg)
cars = {"sports": {"Porsche": "Volkswagon", "Viper": "Dodge", "Corvette": "Chevy"}}
print(cars["sports"]["Corvette"])
for auto in cars["sports"]:
print(auto, cars["... |
import os
from os import listdir
from os.path import isfile, join
import sys
rep_dir = sys.argv[1]
def get_files_in_dir(dir_path):
return [ f for f in listdir(dir_path) if isfile(join(dir_path,f)) ]
dir_path = os.path.dirname(os.path.realpath(__file__)) + "/" + rep_dir + "/"
file_paths = get_files_in_dir(dir_pat... |
#
# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl
#
# This file is part of acado... |
import django
#Para saber que version de django tengo instalada
print(django.get_version()) |
# Copyright 2020 Joseph T. Iosue
#
# 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... |
"""
This module contains classes used for inserting whitespace into the appropriate
places in the pdf, the last stage of processing.
"""
from typing import Any, Tuple
import numpy as np
class WhitespaceInserter:
"""Inserts whitespace into numpy array images."""
def __init__(self, whitespace_length: int, add_... |
import unittest
import autograd.numpy as anp
import numpy as np
from pymoo.model.problem import Problem
class ElementwiseEvaluationTest(unittest.TestCase):
def test_elementwise_evaluation(self):
X = np.random.random((100, 2))
F = MyProblemElementwise().evaluate(X)
_F = MyProblem().eval... |
# pylint: skip-file
# pylint: disable=too-many-instance-attributes
class FirewallRule(GCPResource):
'''Object to represent a gcp forwarding rule'''
resource_type = "compute.v1.firewall"
# pylint: disable=too-many-arguments
def __init__(self,
rname,
project,
... |
import json
import re
import aiofiles
from config import Config as c
from . import http
async def get_race(raceid, complete=False):
# if we're developing locally, we want to have some artifical data to use that isn't from SRL
if c.DEBUG:
if raceid == "test":
async with aiofiles.open('te... |
#@ UIService uiService
#@ LogService log
#@ File(label="Select a directory", style="directory", value="/Volumes/LaCie_DataStorage/xiaochao_wei_STORM imaging/STORM_imaging", persist=false) path
#@ String(label="Folder for output", value = "analysis_20190308", persist=false) dir_output
#@ String(label="Folder for raw ima... |
# Copyright 2019 Xilinx 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 agreed to in writing, ... |
'''
Copyright (c) 2020 WEI.ZHOU. All rights reserved.
The following code snippets are only used for circulation and cannot be used for business.
If the code is used, no consent is required, but the author has nothing to do with any problems and consequences.
In case of code problems, feedback can be made through the... |
'''
Fabio Romano <fabio.romano1990@outlook.it>
Relations File parser
'''
import pickle
import os
from ternaryOperations import delta,relationParser
def rowParsing(subRowKey,rowString,startIndex,endIndex):
subRowKeysValue=dict()
def readFile():
fname=os.path.join(os.path.dirname(__file__),"data","ta... |
from datetime import datetime
from pathlib import Path
from typing import Tuple
import click
from src.data.forecast import CAMSProcessor
PATH = click.Path(exists=True, path_type=Path)
DATE_TYPE = click.DateTime()
from src.logger import get_logger
logger = get_logger("CAMS Forecast Extraction")
@click.command()
@... |
"""
A scraper which pulls zone WHOIS servers from IANA's root zone database.
"""
import argparse
import logging
import socket
import sys
from urllib.parse import urljoin
import xml.etree.ElementTree as etree
from bs4 import BeautifulSoup
import requests
from . import utils
IPV4_ASSIGNMENTS = (
"http://www.iana... |
# -*- coding: utf-8 -*-
from django.apps import AppConfig
class TrainingAppConfig(AppConfig):
name = "app.training"
verbose_name = 'Учебные курсы'
def ready(self):
import app.training.signals
|
# -*- coding: utf-8 -*-
"""
Parses an XML file in order to evaluate sites
"""
__author__ = "Noah W. Garfinkle"
__copyright__ = "Copyright 2018, Noah W. Garfinkle"
__credits__ = ["Dr. Ximing Cai", "Dr. George Calfas", "Thomas 'Max' Foltz",
"Juliana McMillan-Wilhoit", "Matthew Hiett",
... |
'''
Peça ao usuário digitar uma opção:
1 equivale a papel,
2 equivale à pedra e
3 equivale à tesoura.
Se ele digitar qualquer valor que não seja um desses valores, sairá do jogo.
Assim que ele digitar uma jogada, gere um número aleatório entre 1 e 3. Dica: pesquise pela função randint.
Com base na op... |
from abc import abstractmethod
from telegraf.protocol import Line
import socket
class ClientBase(object):
def __init__(self, host='localhost', port=8094, tags=None):
self.host = host
self.port = port
self.tags = tags or {}
def metric(self, measurement_name, values, tags=None, timesta... |
import os
import sys
import shutil
import argparse
from build.sdk_build_utils import *
ANDROID_TOOLCHAINS = {
'armeabi': 'arm-linux-androideabi',
'armeabi-v7a': 'arm-linux-androideabi',
'x86': 'x86',
'mips': 'mipsel-linux-android',
'arm64-v8a': 'aarch64-linux-android',
'x86_64': '... |
from django.http.response import JsonResponse
from admin import settings
import requests
from Kusa.models import SteamUser
from .serializers import SteamUserSerializer
from Kusa.authentication import validate_token
conf = settings.CONF
v2 = "/v0002"
v1 = "/v0001"
format = "JSON"
interface = "/ISteamUser"
def get_pla... |
import os
from glob import glob
import pandas as pd
import numpy as np
from tqdm import tqdm
tqdm.pandas(ascii=True)
import os
curr_path = os.path.dirname(__file__)
class data(object):
def __init__(self, df, smiles_col, target_cols, task_name, task_type, description):
assert type(... |
import pytest
import pandas as pd
import numpy as np
from ramprate.build_features import _find_uptime
def test__find_uptime_start_and_end_nonzero():
dt_idx = pd.date_range(start="2020-01-01 00:00", periods=6, freq="h", tz="UTC")
data = [2, 2, 0, 0, 0, 2]
# downtime=True
# first zero after non-zero
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright SquirrelNetwork
from core.utilities.menu import build_menu
from languages.getLang import languages
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
def init(update,context):
bot = context.bot
chat = update.effective_message.chat_id
l... |
#!/usr/bin/env python3
###########
#
# Created by Bruno Costa @ITQB
# 24/04/2017
# This allows the extraction of specific coordinates from a fasta file
#
############
import argparse
import re
parser = argparse.ArgumentParser(description='This allows the extraction of specific coordinates from a fasta file')
## bla... |
# Generated by Django 2.0 on 2018-09-17 04:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_... |
'''
Descripttion:
version:
Author: HuSharp
Date: 2021-02-09 12:01:25
LastEditors: HuSharp
LastEditTime: 2021-02-09 12:08:55
@Email: 8211180515@csu.edu.cn
'''
def list_create(n):
'''
>>> list_create(3)
[0, 1]
>>> list_create(4)
[0, 1, 2]
>>> list_create(8)
[0, 1, 2, 4]
>>> list_create(1... |
import signal
from jotify.state_ui import UI
import gi
gi.require_version( 'Gtk', '3.0' )
gi.require_version( 'AppIndicator3', '0.1' )
from gi.repository import Gtk as gtk
from gi.repository import GLib
from gi.repository import AppIndicator3 as appindicator
APPINDICATOR_ID = 'jotify-widget'
LABEL_GUIDE = '-'*20
... |
# Generated by Django 2.1.9 on 2019-06-25 09:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0004_marketplacelogic_setup_count'),
]
operations = [
migrations.RenameField(
model_name='marketplacelogiccomment',
... |
# Generated by Django 2.2.20 on 2021-08-10 22:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("course_flow", "0063_auto_20210728_2238"),
]
operations = [
migrations.AddField(
model_name="outcome",
name="code",
... |
from .AcceptanceCriterion import AcceptanceCriterion
class HillClimbing(AcceptanceCriterion):
"""
Hill climbing only accepts progressively better solutions, discarding those
that result in a worse objective value.
"""
def accept(self, rnd, best, current, candidate):
return candidate.objec... |
import json, os.path, traceback
class Stats(object):
def __init__(self, path):
self.Path = path
self.Data = {}
def __getitem__(self, name):
return self.Data[name]
def overwrite(self, key, value):
self.Data[key] = value
self.save()
... |
def getQ3V2(name, owner, cursor = None):
return """
query {
repository(name: "%(name)s", owner: "%(owner)s") {
pullRequests(first: 50, states: MERGED, %(cursor)s) {
pageInfo {
hasNextPage
endCursor
}
edges {
cursor
... |
from setuptools import setup
NAME = "skr"
VERSION = "0.1.0"
URL = "https://github.com/chenjiandongx/skrskr"
AUTHOR = "chenjiandongx"
AUTHOR_EMAIL = "chenjiandongx@qq.com"
LICENSE = "MIT"
REQUIRES = ["pywin32"]
MODULES = ["skr"]
DESC = "SkrSkr in Python."
setup(
author=AUTHOR,
author_email=AUTHOR_EMAIL,
na... |
'''
Classes for serializing and deserializing redis data into json
'''
import redistools
from redistools.conn import Conn
class RedisUtils:
def __init__(self, **kwargs):
self.conn = Conn(**kwargs)
self.ex = 604800
def keys(self, filter=""):
if (filter):
if (type(filter) ==... |
from node import Node
class UnorderedList:
def __init__(self):
self.head = None
def is_empty(self):
self.head == None
def add(self,item):
temp = Node(item)
temp.set_next(self.head)
self.head = temp
def size(self):
current = self.head
count = 0
... |
def Fibonacci(n):
# Check if input is 0 then it will
# print incorrect input
if n < 0:
print("Incorrect input")
# Check if n is 0
# then it will return 0
elif n == 0:
return 0
# Check if n is 1,2
# it will return 1
elif n == 1 or n == 2:
return 1
els... |
# -*- coding: utf-8 -*-
# Copyright 2021 Google 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... |
from typing_extensions import Required
from flask_mongoengine import MongoEngine
from mongoengine.queryset.transform import update
db = MongoEngine()
class User(db.Document):
email = db.StringField(required=True, unique=True)
password = db.StringField(required=True, min_length=6)
created = db.DateTimeFie... |
"""Command line scripts."""
# Standard Library
import os
import sys
import typing as t
from textwrap import dedent
from pkg_resources import load_entry_point
# Websauna
from websauna.system import SanityCheckFailed
from websauna.system.devop.cmdline import prepare_config_uri
FAIL_MSG = """Sanity check failed
Reaso... |
import random
import time
import numpy as np
import pandas as pd
from board import Board
from agent import Agent
# Frame length [s]
s = 0.05
def build_world():
board = Board(10)
board.set_goal(position=(8, 4))
# board.show(s)
board.add_wall(position=(4, 2))
board.add_wall(position=(4, 3))
b... |
# biblioteca para realizar copias profundas
import copy
# variaveis para os valores maximos e minimos do algoritmo
MAX_VAL = 100000
MIN_VAL = -100000
# variaveis para a profundidade da avaliação
MAX_DEPTH = 3
INITIAL_DEPTH = 0
# variavel para representar um movimento nulo
NO_MOVES = (-1,-1)
def make_move(the_board,... |
import spacy
from sacrerouge.common.testing import FIXTURES_ROOT
from sacrerouge.common.testing.metric_test_cases import ReferenceBasedMetricTestCase
from sacrerouge.common.testing.util import sacrerouge_command_exists
from sacrerouge.io import JsonlReader
from sacrerouge.metrics import DecomposedRouge
class TestDec... |
def convert(n, base):
T = "0123456789ABCDEF"
q, r = divmod(n, base)
if q == 0:
return T[r]
else:
return convert(q, base) + T[r]
def solution(n, t, m, p):
answer = ''
i = 0
while True:
if len(answer) > m * t:
break
answer += str(convert(i, n))
... |
"""
Server capabilities
"""
CLIENT_LONG_PASSWORD = 1
CLIENT_FOUND_ROWS = 2
CLIENT_LONG_FLAG = 4
CLIENT_CONNECT_WITH_DB = 8
CLIENT_NO_SCHEMA = 16
CLIENT_COMPRESS = 32
CLIENT_ODBC = 64
CLIENT_LOCAL_FILES = 128
CLIENT_IGNORE_SPACE = 256
CLIENT_PROTOCOL_41 = 512
CLIENT_INTERACTIVE = 1024
CLIENT_SSL = 2048
CLIENT_IGNORE_SI... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import getpass
LOGIN_PAGE = 'https://streaming.settrade.com/realtime/streaming-login/login.jsp?noPopUp=true'
uid = input("User ID: ")
pwd = getpass.getpass("Password: ")
# Initialize driver
driver = webdriver.Firefox(... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
QGIS plugin 'Graphium'
/***************************************************************************
*
* Copyright 2020 Simon Gröchenig @ Salzburg Research
* eMail graphium@salzburgresearch.at
*
* Licensed... |
import os.path
import pytest
from pprint import pprint as pp
from virtbuilder import api
@pytest.mark.parametrize("fixture_filename", ["valid.yml", "minimum.yml"])
def test_validate(get_fixture, fixture_filename):
input_file = get_fixture(fixture_filename)
api.validate(input_file)
@pytest.mark.parametrize(... |
from copy import deepcopy
from tkinter import Toplevel, Button, Entry, Label, DISABLED
class ParameterWindow():
def __init__(self):
self.window = Toplevel()
self.window.title("Parameters")
self.parameters = {}
self.labels = []
self.entries = []
# get screen wi... |
# Generated by Django 3.1.1 on 2020-09-11 06:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0004_userinfo_registered_on'),
]
operations = [
migrations.AddField(
model_name='userinfo',
name='total_... |
# Clustering example using LFW data:
import os
import pandas as pd
from matplotlib import pyplot as plt
import argparse
import json
import scipy.io as sio
from clustering import cluster
from evaluation import calculate_pairwise_pr
def plot_histogram(lfw_dir):
"""
Function to plot the distribution of cluster s... |
from big_sleep import Imagine
import sys
text = sys.argv[1]
train = Imagine(
text = text,
lr = 0.07,
save_every = 10,
save_progress = True,
epochs = 1
)
train()
|
# This file lists some Python functions for rotating a list
# to the left. The emphasis is functions that don't use extra
# space.
# For an explanation, see
# http://eli.thegreenplace.net/2008/08/29/space-efficient-list-rotation/
#
# Based on chapter 2 of "Programming Pearls" by Jon Bentley
#
# Eli Bendersky (http:/... |
leastsqr_err = 0.0
penalty = 0.0
lamb = 0.5
for v in graph.getVertices():
lassov = v.value
if lassov.vtype == 0:
penalty += lamb * abs(lassov.value)
else:
leastsqr_err += pow(lassov.observed - lassov.curval,2)
print("Objective:", penalty + leastsqr_err) |
from typing import Optional, Tuple
import numpy as np
from mne.preprocessing.bads import _find_outliers
from numpy.typing import ArrayLike, NDArray
from ._checks import _check_type
from ._logs import logger
def generate_async_timings(
sequence_timings: ArrayLike,
zscore: float = 2.0,
valid_perc: float =... |
""" Tests the duct component. """
import unittest
import os
import numpy as np
from openmdao.api import Problem, Group, IndepVarComp
from openmdao.utils.assert_utils import assert_rel_error, assert_check_partials
from pycycle.constants import AIR_MIX, AIR_FUEL_MIX
from pycycle.elements.mixer import Mixer
from pycy... |
# base.py
#
# This file defines many of the base classes for classifier
# modules.
#
# If you are looking to define an sklearn classifier or ensemble,
# you may look into subclassing the SKLearnClassifierModule first.
# If that does not fit your needs, subclassing the ClassifierModule
# provides some convenience functi... |
# 차트 데이터 관리 모듈
class Environment:
PRICE_IDX = 4 # 종가의 위치
# __init__ 은 파이썬 컨스트럭터, 자동으로 호출됨, chart_data 2차원 배열, Pandas의 DataFrame임
def __init__(self, chart_data=None):
self.chart_data = chart_data # 주식 종목의 차트 데이터
self.observation = None # 현재 관측치 (행)
self.idx = -1 # 차트 데이터에서의 ... |
# Copyright (c) 2019 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... |
#https://github.com/soheillll/Parts-of-Speech-Tagging/blob/master/HMM%20Tagger.ipynb
import numpy as np
import random
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_blobs
np.random.seed(123)
# install matplotlib
# this line for ipython mac only
import matplotlib
matplotlib.... |
#!/usr/bin/env python
###############################################################################
# Copyright (c) 2012, Sergej Srepfler <sergej.srepfler@gmail.com>
# 2014, PGW client tests are added by L.Belov <lavrbel@gmail.com>
# February 2012 - March 2014
# Version 0.1.0, Last change on Ma... |
import sys
input_filename = sys.argv[1]
with open(input_filename) as f:
input = f.read()
password = list('fbgdceah')
def rotate(l, n):
n %= len(l)
return l[-n:] + l[:-n]
for line in reversed(input.split('\n')):
if line.startswith('rotate left'):
offset = int(line.split()[2])
passw... |
"""
If you find this code useful, please cite our paper:
Mahmoud Afifi, Marcus A. Brubaker, and Michael S. Brown. "HistoGAN:
Controlling Colors of GAN-Generated and Real Images via Color Histograms."
In CVPR, 2021.
@inproceedings{afifi2021histogan,
title={Histo{GAN}: Controlling Colors of {GAN}-Generated and R... |
from bot_loader import BotLoader
from discord.ext import commands
import logging
import discord
import config
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] [%(levelname)s - %(name)s] %(message)s")
logging.getLogger("discord").setLevel(logging.WARNING)
bot = BotLoader(commands.when_mentioned_or(*confi... |
from .console import console
|
###############################################################################
# PyDial: Multi-domain Statistical Spoken Dialogue System Software
###############################################################################
#
# Copyright 2015 - 2019
# Cambridge University Engineering Department Dialogue Systems Grou... |
import hashlib
import logging
import os
import pathlib
from struct import pack, unpack
from typing import Callable, Tuple, Any, List, Dict
import albumentations as albu
import lmdb
import numpy as np
import pandas as pd
import torch
from PIL import Image
from PIL.Image import Image as Img
from numpy.random.mtrand impo... |
import pygame
clock = pygame.time.Clock()
clock.tick(5)
pygame.init()
WIDTH, HEIGHT = 610, 670
TOP_BOTTOM_SPACE = 10
MAP_WIDTH, MAP_HEIGHT = WIDTH - TOP_BOTTOM_SPACE, HEIGHT - TOP_BOTTOM_SPACE
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
T... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import babel
import os
from babel import Locale
from utils import country_info, lang_info
import pandas as pd
import re
import pycountry
import pytz
import json
import io
basepath = os.path.dirname(__file__)
"""
取得所有語系以及語系代碼 (ISO-639-1) ########################################... |
from cards import combinations
def handvalues(combs):
# iterate over all combinations scoring them
scores = {comb: score_hand(comb, False) for comb in combs}
return scores
def check_four_of_a_kind(numbers):
for num in numbers:
if numbers.count(num) == 4:
# Four of a Kind → 105 to... |
from aiogram.dispatcher.filters.state import StatesGroup, State
from aiogram.types import ParseMode
from aiogram_dialog import Window
from aiogram_dialog.widgets.text import Jinja
class DialogSG(StatesGroup):
ANIMALS = State()
# let's assume this is our window data getter
async def get_data(**kwargs):
retu... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import pygame
import pygame.locals
import pygame.font
import os.path
def draw_9patch_background(target_surface, target_dimensions):
target_width, target_height = target_dimensions
background_panel = pygame.image.load(os.path.join('Data'... |
from scoda.app import app
import time
from flask import request, url_for, redirect, flash, make_response, session, render_template
from flask_security import current_user
from .models import db
from .models.user import UserAnalysis
from .models.files import UserSet
from itertools import zip_longest
def grouper(iterabl... |
#! coding = utf-8
import logging
import sqlite3
from persistqueue import sqlbase
log = logging.getLogger(__name__)
class PDict(sqlbase.SQLiteBase, dict):
_TABLE_NAME = 'dict'
_KEY_COLUMN = 'key'
_SQL_CREATE = ('CREATE TABLE IF NOT EXISTS {table_name} ('
'{key_column} TEXT PRIMARY KEY,... |
a=[1, 7, 90, 33, 67, 56, 20, 39, 10, 30]
b=int(input())
for i in range(0,b):
d=input()
d=d.split()
for j in range(0,3):
d[j]=int(d[j])
if((a[d[0]]>a[d[1]])and(a[d[0]]>a[d[2]])):
print(a[d[0]])
elif((a[d[1]]>a[d[0]])and(a[d[1]]>a[d[2]])):
print(a[d[1]])
else:
print... |
import itertools
import random
import networkx as nx
import sys
import pandas as pd
sys.setrecursionlimit(2000)
def globalAllignment(str1, str2):
errorMat = pd.read_csv('inputs/PAM250.txt', delim_whitespace=True)
len1 = len(str1) + 1
len2 = len(str2) + 1
mat = []
path = []
mat.append([0 for _ i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('vendors', '0009_portfolioitem'),
]
operations = [
migrations.AlterField(
model_name='vendorcategories',
... |
def do_four(f, v):
"""
Takes a function and values as arguments and calls it four times.
:param func f: Function to be called
:param object v: Value to be passed as argument to f
:return: None
:Example:
>>> do_four(print, "more spam")
more spam
more spam
more spam
more spam... |
from distutils.core import setup, Extension
splh_module = Extension('splh',
sources = ['splhmodule.cpp'])
setup ( name = 'SPLH',
version = '0.01',
description = 'Sample module for SPLH classification.',
ext_modules = [ splh_module ])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import time
import conf # noqa
from decorators import timelog
@timelog
def doit(n=None):
"""Returns the n argument or prints Done.
>>> [doit(5) for n in range(3)]
[5, 5, 5]"""
time.sleep(1)
if n is None:
print('Done')
re... |
#from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter, ChannelNameRouter
#from channels import route
from channels.auth import AuthMiddlewareStack
#from sensorData.consumers import MqttConsumer #, on_mqtt_message
from realtime.consumers import EventSenderConsumer
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.