content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
'''utils -- contains utility/support members.
CertificateAuthority: class for faking SSL keys for any site
safe_split_http_response_line - parse HTTP response codes
safe_split_http_request_line - parse HTTP request
'''
import shutil
import os
import logging
import tempfile
import uuid
try:
import urlparse
except I... | python |
# Using single formatter
print("{}, My name is John".format("Hi"))
str1 = "This is John. I am learning {} scripting language."
print(str1.format("Python"))
print("Hi, My name is Sara and I am {} years old !!".format(26))
# Using multiple formatters
str2 = "This is Mary {}. I work at {} Resource department. I am {} y... | python |
import torch
import torch.nn as nn
from torch import distributions as dist
from .encoder import ResnetPointnet
from .decoder import DecoderONet
class Network(nn.Module):
def __init__(self,latent_size=256, VAE=False, decoder_insize=3, outsize=1):
super().__init__()
self.encoder = ResnetPointnet(d... | python |
import pg_utils.sound.SADLStreamPlayer
import pg_utils.sound.SMDLStreamPlayer
from pg_utils.rom.rom_extract import load_sadl, load_smd
class EventSound:
def __init__(self):
self.sadl_player = pg_utils.sound.SADLStreamPlayer.SADLStreamPlayer()
self.sadl_player.set_volume(0.5)
self.bg_player... | python |
"""test_backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')... | python |
import os
import os.path
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import scipy.spatial.distance
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def caption(track):
if track.title and track.artist:
return "%s - %s" % (track.artist, track.title)
... | python |
from sqlalchemy import text, UniqueConstraint
from werkzeug.security import check_password_hash, generate_password_hash
from db import db
from models.mixin import ModelMixin
class AppUserModel(ModelMixin, db.Model):
__tablename__ = 'app_user'
__table_args__ = (UniqueConstraint('username',
... | python |
import numpy as np
import pandas as pd
import os
from scipy.stats import linregress
from sympy import diff
from sympy.abc import P
def compute_diffusivity(gas_path, mode):
"""Obtém os dados dos arquivos de saída do lammps e calcula as difusividades corrigidas
Args:
gas_path (str): caminho da pasta do ... | python |
from core.management.functions.update_database import update_database
from core.management.functions.get_data_from_api import get_data_from_api
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Django command for updating the database from igdb API"""
def handle(self, *args, ... | python |
from enum import Enum
from django.contrib.auth import get_user_model
from django.db import models as m
from discuss_api.apps.tag.models import Tag
User = get_user_model()
class Updown(str, Enum):
UP = 'up'
DOWN = 'down'
class VoteChoice(Enum):
AGREE = 'agree'
NOT_AGREE = 'not_agree'
NOT_SURE... | python |
#!/usr/bin/env python
from rapidsms.contrib.handlers.handlers.keyword import KeywordHandler
class GenderHandler(KeywordHandler):
keyword = "gender"
def help(self):
self.respond("To save the child gender, send gender <M/F/O> where M for male, \
F for female and O for other")
def ha... | python |
# Radové číslovky
# Napíšte definíciu funkcie ordinal, ktorá ako argument prijme prirodzené číslo a vráti zodpovedajúcu radovú číslovku v angličtine (tj. 1st, 2nd, 3rd, 4th, 11th, 20th, 23rd, 151st, 2012th a pod.).
def ordinal(number: int) -> str:
"""
>>> ordinal(5)
'5th'
>>> ordinal(151)
'151st'
... | python |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from operacion import models as operacion
class Operario(User):
turno = models.ForeignKey(operacion.Turno)
# end class
| python |
import numpy as np
import random
import quanguru as qt
qub1Sz = qt.tensorProd(qt.sigmaz(), qt.identity(2))
qub2Sz = qt.tensorProd(qt.identity(2), qt.sigmaz())
# store the real and imaginary parts for each coeffiecient at each step
def comp(sim, states):
st = states[0]
sim.qRes.result = ("sz1", qt.expectation(q... | python |
# coding: utf-8
"""
Container Security APIs
All features of the Container Security are available through REST APIs.<br/>Access support information at www.qualys.com/support/<br/><br/><b>Permissions:</b><br/>User must have the Container module enabled<br/>User must have API ACCESS permission # noqa: E501
... | python |
from mnist import MNIST
from galaxies import Galaxies
from mnist_pca import MnistPca
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
def get_mnist_data(digits, num_per_digit):
mnist = MNIST()
x, y = mnist.get_flattened_train_data(digits, num_per_digit)
x_test, y_test = mnist.g... | python |
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="cloudfile",
version="0.2.10",
description="Upload and restore... | python |
import urllib.parse
import mlflow.tracking
from mlflow.exceptions import MlflowException
from mlflow.utils.uri import get_databricks_profile_uri_from_artifact_uri, is_databricks_uri
from mlflow.entities.model_registry.model_version_stages import ALL_STAGES
_MODELS_URI_SUFFIX_LATEST = "latest"
def is_using_databrick... | python |
from git_remote_dropbox.constants import (
PROCESSES,
CHUNK_SIZE,
MAX_RETRIES,
)
from git_remote_dropbox.util import (
readline,
Level,
stdout,
stderr,
Binder,
Poison,
)
import git_remote_dropbox.git as git
import dropbox
import multiprocessing
import multiprocessing.dummy
import m... | python |
# Copyright 2018 Capital One Services, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | python |
"""Module for fand exceptions"""
class FandError(Exception):
"""Base class for all exceptions in fand"""
class TerminatingError(FandError):
"""Daemon is terminating"""
# Communication related errors
class CommunicationError(FandError):
"""Base class for communication related errors"""
class SendRec... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Demographic',
fields=[
('raw_hispanic', models.... | python |
import random
import string
import time
import os
try:
import telepot
from telepot.loop import MessageLoop
except:
os.system('pip install telepot --user')
try:
import requests
except:
os.system('pip install requests --user')
class host:
def __init__(self, host):
h = ho... | python |
__all__ = ('ChannelMetadataGuildMainBase',)
from scarletio import copy_docs, include
from ...core import GUILDS
from ...permission import Permission
from ...permission.permission import (
PERMISSION_ALL, PERMISSION_MASK_ADMINISTRATOR, PERMISSION_MASK_VIEW_CHANNEL, PERMISSION_NONE
)
from ...permission.utils import... | python |
from django.shortcuts import render, redirect, get_object_or_404
from .forms import NoteModelForm
from .models import Note
# CRUD
# create, update, retrieve, delete
def create_view(request):
form = NoteModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.instance.user = request.user
... | python |
# Copyright 2020 KCL-BMEIS - King's College London
# 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... | python |
from csv import reader, writer
from datetime import date
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import db, create_app
from app.constants import FILE_HANDLES
from app.models import Users, RepExercisesTaxonomy, RepExercisesHistory, TimeExe... | python |
#!/usr/bin/env python
from setuptools import setup
from setuptools.extension import Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.egg_info import egg_info
from setuptools.command.sdist import sdist
from distutils import errors
import os
import sys
# ========================== c... | python |
import datetime
import email
# import time
from datetime import datetime
from email.utils import parsedate
def convert_to_http_date_format(date_time):
# def httpdate(dt)
# https://stackoverflow.com/questions/225086/rfc-1123-date-representation-in-python
# A manual way to format it which is identical with... | python |
from collections import OrderedDict
from types import MethodType
from django.db.models import Field
from django.db.models import sql
from django.db.models.sql.compiler import *
class SQLCompiler:
def get_return_fields(self):
cols, params = [], []
col_idx = 1
for _, (s_sql, s_params), alia... | python |
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.utils import six
from django.conf import settings
import json
class OpenIDConnectConfigurationTestCase(TestCase):
"""
Test OpenIDConnectConfiguration URI
"""
def setUp(self)... | python |
from asciisciit import lut
import pytest
@pytest.mark.parametrize("lut_name", ("simple", "binary", "\u3105\u3106\u3107"))
def test_bars(lut_name):
lut.bars(lut_name)
def test_linear_lut():
l = lut.linear_lut("123456789")
assert(len(l._chars) == 9)
assert(len(l._bins) == 8)
def test_get_lut():
... | python |
import asyncio
@asyncio.coroutine
def test_async():
print((yield from func()))
@asyncio.coroutine
def func():
return "Hello, async world!"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(test_async()) | python |
from math import copysign
import pxng
from pxng.colors import *
from pxng.keys import *
def update(window: pxng.Window):
handle_input(window)
window.draw_grid(tint=DARK_GREY)
window.draw_text(10, 10, 'Text Rendering', tint=LIGHT_BLUE)
# Use the bitmap font as something interesting to scroll through... | python |
import logging
from ..extended_properties import ExtendedProperty
from ..fields import BooleanField, ExtendedPropertyField, BodyField, MailboxField, MailboxListField, EWSElementField, \
CharField, IdElementField, AttachmentField
from ..properties import InvalidField, IdChangeKeyMixIn, EWSElement, ReferenceItemId, ... | python |
# ---------------------------------------------------------------------
# Iskratel.MSAN.get_version
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Pyth... | python |
"""Write a model protocol buffer to mat file."""
from deepnet import util
import numpy as np
import sys
import scipy.io
import scipy.io as sio
import gzip
import os
def Convert(mat_file, out_file):
""" Create the necesarry things"""
matfile = sio.loadmat(mat_file)
# get the weight matrix
weight = np.... | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import (absolute_import, division, print_function, unicode_literals)
| python |
import copy
import json
from pytests.basetestcase import BaseTestCase
from pytests.security.x509_multiple_CA_util import x509main, Validation
class MultipleCANegative(BaseTestCase):
def setUp(self):
super(MultipleCANegative, self).setUp()
self.x509 = x509main(host=self.master)
for server... | python |
# -*- coding=utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | python |
# Test file for each of the component of CRUD operation of API routers | python |
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# ALLOWED_HOSTS must be correct in production!
# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']
# Databases
DATABASES['default']['NAME'] = 'hobo'
DATABASES['default']['USER'] = 'hobo'
DATABASES[... | python |
import argparse
import sys
from datetime import datetime
import badget
def parse_args():
parser = argparse.ArgumentParser(
description='Simple transactional budget app',
epilog=f'Example: python3 {sys.argv[0]} "./budgets/2019" -w "2019-12-01 12:30:00" -sc -sa -v')
parser.add_argument('budget_... | python |
# coding: utf-8
"""
DFC
DFC is a scalable object-storage based caching system with Amazon and Google Cloud backends. # noqa: E501
OpenAPI spec version: 1.1.0
Contact: dfcdev@exchange.nvidia.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
... | python |
from segtypes.n64.segment import N64Segment
from segtypes.linker_entry import LinkerEntry
from util import options, log
class CommonSegLib(N64Segment):
def __init__(self, rom_start, rom_end, type, name, vram_start, extract, given_subalign, given_is_overlay, given_dir, args, yaml):
super().__init__(rom_st... | python |
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
if __name__ == '__main__':
number_of_trials = [0, 2, 10, 20, 50, 500]
data = stats.bernoulli.rvs(0.5, size=number_of_trials[-1])
x = np.linspace(0, 1, 100)
for i, N in enumerate(number_of_trials):
heads = data[:N].sum... | python |
import enum
class appErrorCodes(enum.Enum):
OK = 0
METER_NOT_FOUND = 431
MISSING_INPUT = 432
INVALID_INPUT = 433
BAD_DB_INSERT = 434
| python |
from pytorch_lightning import LightningModule
import torch
from torch.utils.data import Dataset
class RandomDataset(Dataset):
def __init__(self, size, num_samples):
self.len = num_samples
self.data = torch.randn(num_samples, size)
def __getitem__(self, index):
return self.data[index]
... | python |
# Generated by Django 3.0.13 on 2021-04-08 09:59
import django.db.models.deletion
import i18nfield.fields
from django.db import migrations, models
import pretix.base.models.base
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0184_customer'),
]
operations = [
mi... | python |
# Contains dictionaries that map English letters to braille.
letters = {
"a": chr(10241),
"b": chr(10243),
"c": chr(10249),
"d": chr(10265),
"e": chr(10257),
"f": chr(10251),
"g": chr(10267),
"h": chr(10259),
"i": chr(10250),
"j": chr(10266),
"k": chr(10245),
"l": chr(10... | python |
import os
import pandas as pd
import numpy as np
import warnings
import math
from sklearn.ensemble import ExtraTreesRegressor, AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor
from sklearn.model_selection import KFold, LeaveOneGroupOut, GroupKFold
from sklearn.model_selection import cross_val_score,... | python |
# -*- coding: utf-8 -*-
import numpy as np
def main():
lst = [1,2,3,4,5]
lst_01 = get_average_by_sum(lst)
print('by sum(): ')
print(lst_01)
lst_02 = get_average_by_numpy(lst)
print('by numpy: ')
print(lst_02)
# Using sum()
def get_average_by_sum(lst):
average = sum(lst)/len... | python |
import configparser
import os
con=configparser.ConfigParser()
def readconf(n):
con.read('step.ini')
step=con.get("config",n)
step=int(step)
return step
def writestep(num,n):
con.read('step.ini')
con.set("config",n,str(num))
con.write(open('step.ini','w'))
| python |
import pygame
import sys
import serial
ser = serial.Serial('/dev/cu.usbmodem14202', 115200, timeout = 1000)
serial_buffer = ''
pygame.init()
pygame.display.set_mode((320,200))
pygame.display.set_caption('Serial communication')
clock = pygame.time.Clock()
while True:
clock.tick(60)
serial_data = ser.read()
... | python |
from recorder import Recorder
from twitch import TwitchClient, constants as tc_const
# Checker class
# It's check streams and
import logging
class Checker:
# Twitch client from main.py
client: TwitchClient = None
# Twitch user id for check
id = None
# Twitch user name for check
username = ""... | python |
#!/usr/bin/env python3
import argparse
import os
import requests
import sys
import sqlite3
import time
__author__ = "pacmanator"
__email__ = "mrpacmanator at gmail dot com"
__version__ = "v1.0"
def get_file():
"""
Downloads a list of OUIs.
"""
url = "https://linuxnet.ca/ieee/oui/nmap-mac-prefixe... | python |
# GENERATED FILE - DO NOT EDIT
VERSION = '201909061227'
BUILDS = {}
| python |
"""Choice type.
A union type similar to the `Result` type. But also allows for higher
number of choices. Usually you would most likekly want to use the
`Result` type instead, but choice can be preferered in non-error cases.
"""
from abc import ABC
from typing import Any, Generic, Iterable, TypeVar, get_origin, overloa... | python |
from . import utils
class ContinuousScale(object):
def __init__(self, data_lim, svg_lim):
self.data_0 = data_lim[0]
self.data_len = utils.lims2len(data_lim)
self.svg_0 = svg_lim[0]
self.svg_len = utils.lims2len(svg_lim)
def __call__(self, value):
return self.svg_0 + s... | python |
#!/usr/bin/python3
# Copyright 2020 Uraniborg authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | python |
import tensorflow as tf
import numpy as np
with tf.Session() as sess:
with tf.gfile.GFile('./artifacts/model2.pb', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def)
input_node = sess.graph.get_tensor_by_name('import/inpu... | python |
from PIL import Image
from PIL import ImageFilter
def resizeImgInsta(imgOrig,useBGBlurInsteadOfWhiteBG=False,fotoSeries=False):
#from PIL import Image
#from PIL import ImageFilter
MAX_INSTA_IMG_PortSide_HEIGHT = 1350;
MAX_INSTA_IMG_LandSide_SIZE=1080;
MIN_INSTA_ING_LANDSIZE_HEIGHT=608;
BG_COL... | python |
#
# PySNMP MIB module TIARA-NETWORKS-CONFIG-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIARA-NETWORKS-CONFIG-MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:16:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... | python |
"""
Demonstration handle dump for CMIP/ESGF files ..
USAGE
=====
-h: print this message;
-v: print version;
-t: run a test
-f <file name>: examine file, print path to replacement if this file is obsolete, print path to sibling files (or replacements).
-id <tracking id>: examine handle record of tracking id.
-V:... | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | python |
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$ 1.250,00, calcule um aumento de 10%. Para salários inferiores ou iguais o aumento é de 15%.
nome = str(input('Informe o seu nome: '))
salario = float(input('Informe o seu salário: '))
salariom... | python |
from test.apps.openapi._fastapi.app import app
import pytest
import schemathesis
from schemathesis import Case
from schemathesis.constants import SCHEMATHESIS_TEST_CASE_HEADER, USER_AGENT
schema = schemathesis.from_dict(app.openapi())
@pytest.mark.parametrize("headers", (None, {"X-Key": "42"}))
@schema.parametrize... | python |
import torch, os
def mask_(matrices, maskval=0.0, mask_diagonal=True):
"""
Masks out all values in the given batch of matrices where i <= j holds,
i < j if mask_diagonal is false
In place operation
:param tns:
:return:
"""
b, h, w = matrices.size()
indices = torch.triu_indices(h, ... | python |
# coding: utf-8
"""
Encoding DER to PEM and decoding PEM to DER. Exports the following items:
- armor()
- detect()
- unarmor()
"""
from __future__ import unicode_literals, division, absolute_import, print_function
import base64
import re
import sys
from ._errors import unwrap
from ._types import type_name, str... | python |
# Copyright (c) 2021, erpcloud.systems and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
import frappe, erpnext, json
from frappe import _, scrub, ValidationError, throw
from frappe.utils import flt, comma_or, nowdate, getdate, cint
from erpne... | python |
from django.contrib import admin
from .models.board_model import Board
# Register your models here.
from .models.todo_model import TblTodo
admin.site.register(TblTodo)
admin.site.register(Board)
| python |
from flask import Flask, jsonify, request
import docker
from flask_cors import CORS
DEBUG = True
CONTAINERS = []
app = Flask(__name__)
app.config.from_object(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
def remove_container(container_id):
container = client.containers.get(container_id)
container... | python |
def read_file_and_convert_to_list(file_path, ignore_comment=True):
"""
This method read in file and convert it to list, separated by line-breaker
:param file_path: path to the file
:param ignore_comment: if True, will ignore the line start with '#'; if False, read all.
:return: list of strings
... | python |
# -*- coding: utf-8 -*-
# coding: utf8
"""
/***************************************************************************
coller
A QGIS plugin
Paste selected vetors to vector layer
-------------------
begin : 2017-12-01
git sh... | python |
import numpy as np
from colors import bcolors
from os import listdir
from sklearn.externals import joblib
from os.path import isfile, join
from neural_net_trainer import Collision_NN_Trainer
import os
class Config_Engine:
def __init__(self, collision_graph, vars, config_fn='', override=False):
self.collis... | python |
# License: MIT
import time
import os
import numpy as np
import pickle as pkl
from openbox.utils.logging_utils import get_logger, setup_logger
from openbox.core.message_queue.master_messager import MasterMessager
PLOT = False
try:
import matplotlib.pyplot as plt
plt.switch_backend('agg')
PLOT = True
except... | python |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/ubuntu/catkin_ws/src/rosserial/rosserial_server/include;/usr/include".split(';') if "/home/ubuntu/catkin_ws/src/rosserial/rosserial_server/include;/usr/include" != "" else []
PROJECT_CATKIN_DEPEN... | python |
CID=0
CFROM=1
CTO=2
CSPEED=3
CPLANTIME=4
RID=0
RLENGTH=1
RSPEED=2
RCHANNEL=3
RFROM=4
RTO=5
RISDUPLEX=6
XID=0
XXY=0
XUP=1
XRIGHT=2
XDOWN=3
XLEFT=4
X=0
Y=1
global cars
global roads
global crosses
global crossxy
global crossid
cars={}
roads={}
crosses={}
crossxy={}
crossid={}
with open('car.txt','r') as f:
for i in f.... | python |
"""PyTorch implementation of the LARNN, by Guillaume Chevalier."""
import math
import copy
from collections import deque
import torch
from torch import nn
import torch.nn.functional as F
from multi_head_attention import MultiHeadedAttention, PositionalEncoding
__author__ = "Guillaume Chevalier"
__license__ = "MIT... | python |
#!/usr/bin/python2.5
#
# Copyright 2009 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... | python |
"""Example package for generating stardoc from rules_nodejs at source"""
load("@build_bazel_rules_nodejs//packages/typescript:index.bzl", "ts_library")
def custom_ts_library(name, deps = [], **kwargs):
"""
Helper wrapper around ts_library adding default attributes and dependencies
Args:
name: The... | python |
from app import db
class Player(db.Model):
__tablename__ = "players"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(128))
# TODO maybe make uid and provider TOGETHER be unique
# UniqueConstraint('col2', 'col3', name='uix_1')
uid = db.Column(d... | python |
from tempConversions import *
def test_temp_conversions_fToC_32_0():
assert fToC(32.0) == 0.0
def test_temp_conversions_fToC_212_100():
assert fToC(212.0) == 100.0
def test_temp_conversions_cToF_0_32():
assert cToF(0.0) == 32.0
def test_temp_conversions_cToF_100_212():
assert cToF(100.0) == 212.0
| python |
range(5, 10) # 5, 6, 7, 8, 9
range(0, 10, 3) # 0, 3, 6, 9
range(-10, -100, -30) # -10, -40, -70
range(-10, -101, -30) # -10, -40, -70 -100
| python |
# -*- coding: utf-8 -*-
#
# Poio Tools for Linguists
#
# Copyright (C) 2009-2014 Poio Project
# Author: Peter Bouda <pbouda@cidles.eu>
# URL: <http://media.cidles.eu/poio/>
# For license information, see LICENSE.TXT
from __future__ import unicode_literals
import os
import poioapi.io.mandinka
import poioapi.data
impo... | python |
#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
# @Author skillnull
# @Function 获取网易云音乐评论
import os
import random
import sys
import json
import time
import base64
import codecs
import requests
import multiprocessing # 多进程
from Crypto.Cipher import AES
import re # 正则表达式库
import numpy as np # numpy数据处理库
import co... | python |
import os
import sys
import base64, json, re
import time
import requests
import api
from time import sleep as timeout
from requests import get
R='\033[1;31m'; B='\033[1;34m'; C='\033[1;37m'; Y='\033[1;33m'; G='\033[1;32m'; RT='\033[;0m'
os.system('git pull && clear')
a='aHR0cDovL3d3dy5qdXZlbnR1ZGV3ZWIubXRlL... | python |
"""
Copyright (c) 2018-2021 Intel 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 in w... | python |
input_data = list(map(int, input().split()))
row = input_data[0]
column = input_data[1]
graph = []
result = 0
for i in range(row):
graph.append(list(map(int, input())))
def dfs(x, y):
if x < 0 or x > row - 1 or y < 0 or y > column - 1:
return False
if graph[x][y] == 1:
return False
graph[x][... | python |
# Generated by Django 2.2 on 2019-05-19 12:29
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... | python |
from justgood import imjustgood
media = imjustgood("YOUR_APIKEY_HERE")
tgl = "17-08-1945" # example birth date
data = media.lahir(tgl)
# Get attributes
result = "Lahir : {}".format(data["result"]["lahir"])
result = "\nHari : {}".format(data["result"]["hari"])
result = "\nZodiac : {}".format(data["result"]["zodiak"])
... | python |
from keras.models import Sequential
from keras.layers import Embedding
import numpy as np
model = Sequential()
model.add(Embedding(1000, 1, input_length=10))
# the model will take as input an integer matrix of size (batch, input_length).
# the largest integer (i.e. word index) in the input should be no larger than 999... | python |
"""Redis: Delete emote hashes
Revision ID: 5f746af0a82d
Revises: 186928676dbc
Create Date: 2019-06-04 19:07:25.109751
"""
from pajbot.managers.redis import RedisManager
from pajbot.streamhelper import StreamHelper
# revision identifiers, used by Alembic.
revision = '5f746af0a82d'
down_revision = '186928676dbc'
br... | python |
from django.conf.urls import url
from wagtailnetlify.views import success_hook, redirects
urlpatterns = [
url(r"^success$", success_hook, name="success_hook"),
url(r"^redirects$", redirects, name="redirect_builder"),
]
| python |
from reversion.revisions import create_revision, set_user, set_comment, deactivate
class RevisionMiddleware:
"""Wraps the entire request in a revision."""
manage_manually = False
using = None
atomic = True
def __init__(self, get_response):
self.get_response = get_response
def __c... | python |
#!/usr/bin/env python -*- coding: utf-8 -*-
from config import *
from flask import Flask, render_template, Response, jsonify, request, redirect, url_for
from jinja2 import Template
import json
import pigpio
from i2c import I2c
from motor import Motor
import time
from threading import Thread
import sys
import sqlite3
im... | python |
from PyDictionary import PyDictionary
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
dictionary=PyDictionary()
s = ""
old_s = ""
while(s != "0"):
s = input("Word / option: ")
print("")
if s == "1":
if old_s == "":
print("No previous records")
else:
print(dict... | python |
import os
import numpy
import tensorflow as tf
import scipy as scp
import scipy.misc
KITTI_TRAIN_DIR_PREFIX = '/usr/local/google/home/limeng/Downloads/kitti/data_road/training/image_2/'
KITTI_GT_DIR_PREFIX = '/usr/local/google/home/limeng/Downloads/kitti/data_road/training/gt_image_2/'
UM_TRAIN_TEMPLATE = "um_0000%02... | python |
from urllib.parse import urlparse, unquote
from records_mover.url.gcs.gcs_directory_url import GCSDirectoryUrl
from typing import IO
from records_mover.url import BaseFileUrl
from smart_open.gcs import open as gs_open
import google.cloud.storage
from google.cloud.storage.blob import Blob
import google.api_core.exceptio... | python |
# -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp.osv import orm, fields
class PaymentTransaction(orm.Model):
_inherit = 'payment.transaction'
_columns = {
# link with the sale order
'sale_order_id': fields.many2one('sale.order', 'Sale Order'),
}
def form_feedbac... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.