text stringlengths 1 927k |
|---|
# Generated by Django 3.0.7 on 2020-06-15 11:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quiz', '0006_auto_20200615_1704'),
]
operations = [
migrations.AlterField(
model_name='quiz',
name='feelings_due_to_... |
import asyncio
import json
import logging
from aiohttp.web import Response
from aiohttp.web_exceptions import HTTPNoContent, HTTPOk
from database.dictionary import Definition, Word
from database.exceptions.http import WordAlreadyExistsException, WordDoesNotExistException, InvalidJsonReceivedException
from .routines i... |
from ducts.spi import EventHandler
from datetime import datetime
from io import BytesIO
import logging
logger = logging.getLogger(__name__)
class Handler(EventHandler):
def __init__(self):
super().__init__()
def setup(self, handler_spec, manager):
handler_spec.set_description('echo back tes... |
from __future__ import absolute_import
from collections import OrderedDict
EXAMPLE_PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQC1cd9t8sA03awggLiX2gjZxyvOVUPJksLly1E662tttTeR3Wm9
eo6onNeI8HRD+O4wubUp4h4Chc7DtLDmFEPhUZ8Qkwztiifm99Xo3s0nUq4Pygp5
AU09KXTEPbzHLh1dnXLcxVLmGDE4drh0NWmYsd/Zp7XNIZq2TRQQ3NTdV... |
import numpy as np
import pytest
import pandas as pd
import pandas.util.testing as tm
from .base import BaseExtensionTests
class BaseMethodsTests(BaseExtensionTests):
"""Various Series and DataFrame methods."""
@pytest.mark.parametrize('dropna', [True, False])
def test_value_counts(self, all_data, drop... |
import pytest
import os
from polyglotdb.io import inspect_maus
from polyglotdb import CorpusContext
from polyglotdb.exceptions import ParseError
def test_load_aus(maus_test_dir, graph_db):
with CorpusContext('test_mfa', **graph_db) as c:
c.reset()
testFilePath = os.path.join(maus_test_dir, "maus... |
import tensorflow as tf
from tensorflow.contrib import layers
from config import MovieQAPath
from raw_input import Input
_mp = MovieQAPath()
hp = {'emb_dim': 300, 'feat_dim': 512, 'dropout_rate': 0.1}
def dropout(x, training):
return tf.layers.dropout(x, hp['dropout_rate'], training=training)
def l2_norm(x, a... |
# Django settings for example_project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlTermreadkey(PerlPackage):
"""Term::ReadKey is a compiled perl module dedicated to prov... |
# Copyright 2016-2018, Pulumi Corporation. All rights reserved.
import pulumi
from pulumi_aws import ec2
from ami import get_linux_ami
size = 't2.micro'
group = ec2.SecurityGroup('web-secgrp',
description='Enable HTTP access',
ingress=[
{ 'protocol': 'tcp', 'from_port': 80, 'to_port': 80, 'cidr_bloc... |
#!/usr/bin/env python3
import glob # easiest thing I see
import json
total = 0
toprint = ""
for fn in glob.glob("info/0004*.txt"):
total += 1
with open(fn, "r") as f:
titleinfo = json.load(f)
toprint += "{0} | {1} | `{2}`\n".format(titleinfo[0].replace('\n', '<br>').replace('`', '\\`').replace... |
from djmodels.conf import settings
from djmodels.contrib.auth.models import User
from djmodels.contrib.flatpages.models import FlatPage
from djmodels.contrib.sites.models import Site
from djmodels.test import TestCase, modify_settings, override_settings
from .settings import FLATPAGES_TEMPLATES
class TestDataMixin:
... |
# -*- coding: utf-8 -*-
'''
The networking module for Non-RH/Deb Linux distros
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.ext.six.... |
import json
from datetime import datetime
EURO_WEI = 370816960785710
TICKET_PRICE_SHORT = EURO_WEI
TICKET_PRICE_MEDIUM = 2 * EURO_WEI
TICKET_PRICE_LONG = 3 * EURO_WEI
MIN_STATION_MEDIUM = 5
MIN_STATION_LONG = 13
class Ticket:
def __init__(self, start_station: str, end_station: str, station_num: int, date: str, u... |
from collections import defaultdict
def get_graph(filename):
graph = defaultdict(list)
rev_graph = defaultdict(list)
with open(filename) as f:
for line in f.readlines():
b = line.split(' bags contain ')
src = b[0]
dest = []
if b[1].strip() != "no oth... |
/anaconda3/lib/python3.6/imp.py |
import jax.numpy as jnp
import matplotlib.pyplot as plt
import jax
from jax import lax
from envs import Qaudrupedal
from agents import Deep_Qaudrupedal
import copy
import pickle
from time import gmtime, strftime
from jaxRBDL.Dynamics.ForwardDynamics import ForwardDynamics, ForwardDynamicsCore
import numpy as np
from j... |
#!/usr/bin/env python3
import sys
if len(sys.argv) != 5:
print("usage: program in.bed0 in.bed1 out.bed0 out.bed1")
exit
in0, in1, out0, out1 = sys.argv[1:]
badids = set()
with open(in0) as f:
for ids, line in enumerate(f):
if line[:2] == "NA":
badids.add(ids)
with open(in1) as f:
... |
import ctypes
import os
from _pydev_bundle import pydev_log, pydev_monkey
from _pydevd_bundle.pydevd_constants import get_frame, IS_PY2, IS_PY37_OR_GREATER, IS_CPYTHON, IS_WINDOWS, IS_LINUX, IS_MACOS, \
IS_64BIT_PROCESS, IS_PYCHARM_ATTACH
from _pydev_imps._pydev_saved_modules import thread, threading
try:
impo... |
'''
Django settings for settings project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
'''
from pathli... |
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
from urllib.parse import ... |
from random import randint
from time import sleep
def sorteia(lista):
print("Sorteando 5 valores da lista: ", end="")
for cont in range(0, 5):
n = randint(1, 10)
lista.append(n)
print(f"{n} ", end="")
sleep(0.3)
print("PRONTO!")
def somaPar(lista):
soma = 0
for va... |
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.views.generic.edit import FormView
from twilio.twiml.voice_response import Gather, VoiceResponse
from emojiweather.mixins import CsrfExemptMixin
from .forms import VoiceWeatherForm
cl... |
import FWCore.ParameterSet.Config as cms
from CondCore.Utilities.popcon2dropbox_job_conf import options, psetForRecord, setup_popcon
import CondTools.Ecal.db_credentials as auth
recordName = "EcalLaserAPDPNRatiosRcd"
tagTimeType = "timestamp"
process = setup_popcon( recordName, tagTimeType )
process.MessageLogger = ... |
I2C_ADR = 0x57
#DATA_IS_READY() ( DATA_READY == 0 )
#DATA_IS_NOT_READY() ( DATA_READY != 0 )
# registers' addresses
INT_STATUS = 0x00
INT_ENABLE = 0x01
FIFO_WRITE_PTR = 0x02
OVER_FLOW_CNT = 0x03
FIFO_READ_PTR = 0x04
FIFO_DATA_REG = 0x05
MODE_CONFIG = 0x06
SPO2_CONFIG = 0x0... |
#! /usr/bin/env python2
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING... |
# Generated by Django 3.0.7 on 2021-05-17 14:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quizapp', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='userparticipated',
name='status',
... |
from django.contrib.auth import get_user_model
from django.db import models
class Turma(models.Model):
nome = models.CharField(max_length=64)
slug = models.SlugField(max_length=64)
inicio = models.DateField()
fim = models.DateField()
alunos = models.ManyToManyField(get_user_model(), through='Matri... |
# This program reads a students
# exam result and determines
# if they have to repeat
# the test.
x = float(input("Please enter your exam result: "))
if x < 0 or x > 100:
print("Please re-execute code with correct test result.")
elif x < 40:
print("You scored a percentage of: ", x)
print("That is a Fail")... |
# coding=utf-8
# Copyright 2020 Google and The HuggingFace Inc. team.
#
# 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... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
"""
Boxlib frontend tests
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2017, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... |
# -*- coding:utf-8 -*-
from libs.yuntongxun.CCPRestSDK import REST
# 说明:主账号,登陆云通讯网站后,可在"控制台-应用"中看到开发者主账号ACCOUNT SID
_accountSid = '8a216da87291bbcd0172acc0f2950e35'
# 说明:主账号Token,登陆云通讯网站后,可在控制台-应用中看到开发者主账号AUTH TOKEN
_accountToken = '69b0e93b93fb402eb0ce3ff09bb012d9'
# 请使用管理控制台首页的APPID或自己创建应用的APPID
_appId = '8a216da... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0001_initial'),
('giftcertificate', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
str_ = str.split(" ")
dic_s = {}
dic_p = {}
res_s = []
res_p = []
for i in range(len(str_)):
if str... |
import itertools
__author__ = 'peter'
def cross_dict_dicts(*dicts):
"""
Combine two or more dictionaries of dictionaries by turning every pairwise combination of their keys, and creating a
new dict whose keys are tuples (containing these key-combinations) and whose values are the the combined dictioniona... |
from dataclasses import dataclass, field
from typing import Optional
from .script import Script
from .t_global_task import TGlobalTask
__NAMESPACE__ = "http://www.omg.org/spec/BPMN/20100524/MODEL"
@dataclass
class TGlobalScriptTask(TGlobalTask):
class Meta:
name = "tGlobalScriptTask"
script: Optiona... |
# Generated by Django 2.1.7 on 2019-08-18 20:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("app", "0033_gameplayer_loser")]
operations = [
migrations.AlterField(
model_name="move",
name="action_type",
field=mo... |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# -*- coding: utf-8 -*-
task = Task("cangbaotu",desc = u"藏宝图")
#task.addSetupActionSet("RefreshGame",tag="pre1",desc="RefreshGame")
task.addTeardownActionSet("TypeCommand", tag = "37", desc = u"清除任务标记", mp={'command':'$cleartask 1'})
task.addTeardownActionSet("TypeCommand", tag = "37", desc = u"清除任务标记", mp={'command':'... |
#!/bin/env python
from pmg.models import Bill, BillVersion, File, db, BillType
import json
import re
bills = json.load(open("data/bills-with-files.json"))
bill_pages = json.load(open("data/bill-pages.json"))
nids = json.load(open("data/nid_url.json"))
pages_by_nid = {p["nid"]: p for p in bill_pages}
nids_by_url = {n... |
from ray import workflow
@workflow.step
def hello(name: str) -> str:
return format_name.step(name)
@workflow.step
def format_name(name: str) -> str:
return "hello, {}".format(name)
@workflow.step
def report(msg: str) -> None:
print(msg)
if __name__ == "__main__":
workflow.init()
r1 = hello.s... |
#
# PySNMP MIB module HUAWEI-RSVPTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-RSVPTE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:48:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
"""
File that contains the declaration of the Rotation class (enumeration)
"""
import enum
class Rotation(enum.Enum):
LEFT = enum.auto()
RIGHT = enum.auto()
REVERSE = enum.auto() |
# Generated by Django 2.1.4 on 2018-12-24 08:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ConfirmString',
fields=[
... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: fbs
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class RuntimeOptimizationRecordContainerEntry(object):
__slots__ = ['_tab']
@classmethod
def GetRootAsRuntimeOptimizationRecordContaine... |
#!/usr/bin/python
# --------------------------------------------------------
# Multitask Network Cascade
# Modified from py-faster-rcnn (https://github.com/rbgirshick/py-faster-rcnn)
# Copyright (c) 2016, Haozhi Qi
# Licensed under The MIT License [see LICENSE for details]
# -------------------------------------------... |
def break_words(stuff):
words = stuff.split(' ')
return words
def sort_words(words):
return sorted(words)
def print_first_word(words):
word = words.pop(0)
print word
def print_last_word(words):
word = words.pop(-1)
print word
def sort_sentence(sentence):
words = break_words(sentence)
return sort_words(word... |
import asyncio
import logging
import time
from typing import Callable
from silicoin.protocols.protocol_message_types import ProtocolMessageTypes
log = logging.getLogger(__name__)
async def time_out_assert_custom_interval(timeout: int, interval, function, value=True, *args, **kwargs):
start = time.time()
las... |
from ftw import ruleset, errors
import pytest
def test_output():
with pytest.raises(errors.TestError) as excinfo:
output = ruleset.Output({})
assert(excinfo.value.args[0].startswith('Need at least'))
with pytest.raises(ValueError) as excinfo:
output = ruleset.Output({'status': 'derp'})
... |
import torch
import torch.nn.functional as F
import torchvision.transforms as transforms
from random import randint
import numpy as np
import cv2
from PIL import Image
import random
###################################################################
# random mask generation
############################################... |
# Copyright 2020 Axis Communications AB.
#
# For a full list of individual contributors, please see the commit history.
#
# 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.apac... |
# -*- coding: utf-8 -*-
###############################################################################
#
# GetStockQuote
# Retrieves information for the specified stock symbol from Yahoo Finance.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the ... |
# Generated by Django 3.1.6 on 2010-12-31 21:09
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0006_auto_20210302_1708'),
]
operations = [
migrations.AlterField(
model_name='orders',
nam... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from lakehouse import Column, computed_asset, computed_table, source_asset, source_table
def test_computed_asset_no_deps():
@computed_asset(storage_key="filesystem")
def casset() -> str:
return "a"
assert casset.computation
assert casset.path == ("casset",)
assert casset.computation.outpu... |
# coding: utf-8
#
# Copyright 2018 The Oppia 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 requi... |
# Test for Moody and White k-components algorithm
from nose.tools import assert_equal, assert_true, raises, assert_greater_equal
import networkx as nx
from networkx.algorithms.connectivity.kcomponents import (
build_k_number_dict,
_consolidate,
)
##
## A nice synthetic graph
##
def torrents_and_ferraro_graph()... |
## WAVE EQUATION
import numpy as np
import matplotlib.pyplot as plt
import pylan as pn
## constants and grid
H = 10
L = 1e5
g = 9.8
F = 0.01/1e3/H #tau/rho0/H
dx = 5e3
dt = 300
cfl = np.sqrt(g*H)*dt/dx
print('cfl = %1.3f' % cfl)
T = 48*3600
N = int(T/dt)+1
## staggered grid
xu = np.arange(0,L+dx,dx)
xe = xu[:-1]+... |
# DO NOT EDIT
# This file is generated by the updatebundle setup.py command
__plotlyjs_version__ = "1.49.1" |
# -*- coding: utf-8 -*-
__author__ = 'custer'
__date__ = '2017/7/27 11:41'
from random import Random
from django.core.mail import send_mail
from users.models import EmailVerifyRecord
from MxOnline.settings import EMAIL_FROM
def random_str(randomlength=8):
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqR... |
#!/usr/bin/env pytest
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test GRIB driver.
# Author: Frank Warmerdam <warmerdam@pobox.com>
#
#######################################################################... |
# coding: utf-8
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
from .cli_root import cli
from . import final_command_processor # noqa: F401
from . import cli_setup # noqa: F401
if __name__ == '__main__':
cli() |
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
q = [start]
n = len(arr)
while q:
node = q.pop()
if arr[node] == 0:
return True
if arr[node] < 0:
continue
for i in [node + arr[node], nod... |
#!/usr/bin/env python3
# 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.
from parlai.core.worlds import World
# ----- Baseline overworld that simply defers to the default world ----- #
class ... |
from setuptools import setup
from setuptools_rust import Binding, RustExtension
extras = {}
extras["testing"] = ["pytest", "requests", "numpy", "datasets"]
extras["docs"] = ["sphinx", "sphinx_rtd_theme", "setuptools_rust"]
setup(
name="tokenizers",
version="0.10.3",
description="Fast and Customizable Toke... |
import rospy
import smach
import smach_ros
import threading
from operator import itemgetter
import numpy as np
from apc_msgs.srv import DetectObject2D
from apc_msgs.srv import DetectObject2DRequest
from geometry_msgs.msg import Pose, Point, Quaternion
# ==========================================================
class... |
#!/usr/bin/env python
# Need to generate a shapefile with hourly rainfall totals in it!
# Daryl Herzmann 28 May 2004
import pg, shapelib, dbflib, re, mx.DateTime, sys
from Scientific.IO.ArrayIO import *
mydb = pg.connect("wepp", 'iemdb')
y = int(sys.argv[1])
m = int(sys.argv[2])
d = int(sys.argv[3])
day = mx.DateTime... |
import sqlite3
from connections_db.connections_cryptocurrencies import ConnectionDBCryptoCurrencies
dbTickers = sqlite3.connect("database/tickers.db")
dbTickers.execute("create table dataStock(nome text, logo text, info text, ticker text, dy number, precoMinimoCotaEmUmAno number, precoMaximoCotaEmUmAno number, dividen... |
# -*- coding: utf-8 -*-
"""
CNN model for text classification implemented in TensorFlow 2.
This implementation is based on the original paper of Yoon Kim [1] for classification using words.
Besides I add charachter level input [2].
# References
- [1] [Convolutional Neural Networks for Sentence Classification](https://... |
# Copyright 2016 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 wri... |
from django.contrib import admin
from models import *
# Register your models here.
class CategoryAdmin(admin.ModelAdmin):
list_display = ['id', 'title']
class GoodsInfoAdmin(admin.ModelAdmin):
list_display = ['id', 'title', 'price', 'unit', 'click', 'inventory', 'detail', 'desc', 'image']
admin.site.regis... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
from __future__ import absolute_import
import json
import awkward as ak
np = ak.nplike.NumpyMetadata.instance()
def from_iter(input):
if input is None:
return None
if ak._util.isstr(input):
return ak._... |
if node.os != 'ubuntu' and node.os != 'raspbian':
raise Exception('{} {} is not supported by this bundle'.format(node.os, node.os_version))
svc_systemd = {}
files = {}
svc_systemd['systemd-sysctl'] = {
'running': True,
'enabled': True,
}
files['/etc/sysctl.d/60-custom.conf'] = {
'content_type': 'mak... |
# Copyright 2019 BlueCat Networks (USA) Inc. and its affiliates
# -*- coding: utf-8 -*-
#
# 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
#
# Unle... |
_base_ = './upernet_beit-base_8x2_640x640_160k_ade20k.py'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(2560, 640),
img_ratios=[0.5, 0.75, 1... |
import requests
from heltour import settings
from collections import namedtuple
import logging
logger = logging.getLogger(__name__)
def _get_slack_token():
with open(settings.SLACK_API_TOKEN_FILE_PATH) as fin:
return fin.read().strip()
def _get_slack_webhook():
try:
with open(settings.SLACK_W... |
# by Kami Bigdely
# Consolidate duplicate conditional fragments
def add(mix, ingrediants):
mix.append(ingrediants)
return mix
def mixer_ice_with_cream():
print('mixed ice with cream.')
return ['ice', 'cream']
def if_milkskake(drink):
return 'strawberry milkshake' in drink
def if_coffee(drink)... |
# Copyright 2012 OpenStack Foundation.
# 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 requ... |
#!/usr/bin/env python
import pickle as pkl
import sys
import torch
from lars import *
if __name__ == "__main__":
input = sys.argv[1]
obj = torch.load(input, map_location="cpu")
if 'backbone' in obj:
obj = obj["backbone"]
elif 'state_dict' in obj:
obj = obj["state_dict"]
newmodel ... |
""" The location id and name of Taiwan in Opendata CWB """
LOCATIONS = {
# Taiwan
"F-D0047-091": ["%E5%AE%9C%E8%98%AD%E7%B8%A3","%E8%8A%B1%E8%93%AE%E7%B8%A3","%E8%87%BA%E6%9D%B1%E7%B8%A3","%E6%BE%8E%E6%B9%96%E7%B8%A3","%E9%87%91%E9%96%80%E7%B8%A3","%E9%80%A3%E6%B1%9F%E7%B8%A3","%E8%87%BA%E5%8C%97%E5%B8%82","%E6... |
"""419. Battleships in a Board
https://leetcode.com/problems/battleships-in-a-board/
"""
from typing import List
class Solution:
def countBattleships(self, board: List[List[str]]) -> int:
def helper(r: int, c: int):
found = False
board[r][c] = '.'
for dr, dc in ([0, 1],... |
"""SPL token instructions."""
from enum import IntEnum
from typing import Any, List, NamedTuple, Optional, Union
from solana.publickey import PublicKey
from solana.system_program import SYS_PROGRAM_ID
from solana.sysvar import SYSVAR_RENT_PUBKEY
from solana.transaction import AccountMeta, TransactionInstruction
from ... |
class Sources:
'''
Source class that defines source objects
'''
def __init__(self,id,name,description,url,category,language,country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.language = langu... |
#!/usr/bin/python3
def search_replace(my_list, search, replace):
return [replace if i == search else i for i in my_list] |
#Autor: Braulio Arturo Rodriguez Hernandez
#Fecha: 07/Septiembre/2021
#importamos las librerias necesarias
import json #esta biblioteca la utilizaremos para la gestion de credenciales de los usuarios
import lifestore_file as datos #importamos los datos contenidos en el archivo y lo nombramos como datos
from prettytabl... |
# noinspection PyShadowingBuiltins,PyUnusedLocal
def compute(x, y):
# raise NotImplementedError()
return x + y |
# coding: UTF-8
import time
import unittest
from src.bitmex_websocket import BitMexWs
class TestBitMexWs(unittest.TestCase):
account = "bitmex"
pair = "XBTUSD"
wait = False
def setUp(self):
self.wait = True
def complete(self):
self.wait = False
def wait_complete(self):
... |
"""Mock responses for alert queries."""
GET_ALERT_RESP = {
"type": "CB_ANALYTICS",
"id": "86123310980efd0b38111eba4bfa5e98aa30b19",
"legacy_alert_id": "62802DCE",
"org_key": "4JDT3MX9Q",
"create_time": "2021-05-13T00:20:46.474Z",
"last_update_time": "2021-05-13T00:27:22.846Z",
"first_event_... |
"""
Provide a dataset_func which builds a tensorflow dataset object for neural data
See below for an example about how to use this function
"""
import tensorflow as tf
from tfutils.imagenet_data import color_normalize
import os, sys
import numpy as np
import pdb
import h5py
class Generator(object):
"""
Calla... |
import logging
from rhasspy_weather.data_types.request import WeatherRequest
from rhasspy_weather.parser import rhasspy_intent
from rhasspyhermes.nlu import NluIntent
log = logging.getLogger(__name__)
def parse_intent_message(intent_message: NluIntent) -> WeatherRequest:
"""
Parses any of the rhasspy weathe... |
import torch
import torch.nn as nn
from time import time
import numpy as np
from models.pytorch_revgrad import RevGrad
class DoubleConvBN(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels, kernel_size, dropout):
super().__init__()
self.conv1 = n... |
#!/usr/bin/env python
'''
Entity Component System for Python
ecs.py provides a convenient library to utilize for the ECS pattern.
'''
from collections import OrderedDict as dict
import json
from uuid import uuid4
import sys
__version__ = '0.1.3'
__license__ = 'Apache 2.0'
__url__ = 'http://learnpythonandmakegames.gi... |
import json
import os
import sys
from io import IOBase as io
from . import app
from . import bdev
from . import blobfs
from . import env_dpdk
from . import idxd
from . import ioat
from . import iscsi
from . import log
from . import lvol
from . import nbd
from . import net
from . import notify
from . import nvme
from ... |
"""JSON implementations of proxy records."""
# pylint: disable=no-init
# Numerous classes don't require __init__.
# pylint: disable=too-many-public-methods,too-few-public-methods
# Number of methods are defined in specification
# pylint: disable=protected-access
# Access to protected methods allowed in pac... |
# SPDX-License-Identifier: Apache-2.0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 11:20:55 2021
@author: vukand
"""
from pyftdi.gpio import GpioAsyncController
"""
0x01 - write instruction
0x02 - acquire address instruction
0x03 - acquire data instruction
0x04 - read instruction
"""... |
# -*- coding: utf-8 -*-
"""
pyvisa-py.highlevel
~~~~~~~~~~~~~~~~~~~
Highlevel wrapper of the VISA Library.
:copyright: 2014 by PyVISA-py Authors, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
from __future__ import division, unicode_literals, print_function, abso... |
import streamlit as st
from src.utils import visual_def
from src.utils import uploaded_file
def app():
st.header("Advanced Exploratory Visual Data Analysis")
data = uploaded_file.read_datafolder()
try:
data_columns = data.columns
data_type = data.dtypes
visual = visual_def.Visual... |
class Solution:
def originalDigits(self, s: str) -> str:
tb = {
'zero':'0',
'one':'1',
'two':'2',
'three':'3',
'four':'4',
'five':'5',
'six':'6',
'seven':'7',
'eight':'8',
'nine':'9'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.