content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""Test app factory method."""
from pytest import MonkeyPatch
from app import create_app
def test_app_factory_method(monkeypatch: MonkeyPatch) -> None:
"""Test that application test settings are correct."""
app = create_app(testing=True)
assert app.testing
class Recorder:
dsn: str
en... | python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import PIL
from PIL import Image
def display_network(A, filename='weights.jpg', opt_normalize = True):
"""
This function visualizes filters in matrix A. Each column of A is a
filter. We will reshape each column into a square image and vis... | python |
# Copyright 2012 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.
{
'variables': {
'chromium_code': 1,
'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/ios/chrome',
'ui_string_overrider_inputs': [
'<(SHARED_I... | python |
import json
from os import path
from subprocess import run, PIPE
from typing import Dict
def get_key_signer(key_name: str, keys_dir: str) -> Dict:
with open(path.join(keys_dir, key_name + ".json"), "r") as f:
return json.load(f)
def get_key_multisig_addr(key_name: str) -> str:
p = run(('secretcli', ... | python |
class BitVector(object):
"""docstring for BitVector"""
"""infinite array of bits is present in bitvector"""
def __init__(self):
self.BitNum=0
self.length=0
def set(self,i):
self.BitNum=self.BitNum | 1 << i
self.length=self.BitNum.bit_length()
def reset(self,i):
resetValue=1<<i
self.BitNum=self.BitNum ... | python |
#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals, print_function, division
import sys
import binascii
from diameterparser.decode_diameter import decode_diameter
def convertMac(octet):
mac = [binascii.b2a_hex(x) for x in list(octet)]
return "".join(mac)
class DiameterConn:
... | python |
# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC.
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering Solutions
# of Sandia, LLC, the U.S. Government retains certain rights in this software.
# standard library
import os
import hashlib
import pic... | python |
from materials_io.base import BaseParser, BaseSingleFileParser
from glob import glob
import pytest
import os
class FakeParser(BaseParser):
def parse(self, group, context=None):
return {'group': list(group)}
def implementors(self):
return ['Logan Ward']
def version(self):
return ... | python |
"""Base class for all linear models.
Subclasses must implement their own _fit_regression, _fit_classifier, and
_iter_minibatches functions. Everything else (prediction, generating
model summaries, saving, loading, one-vs-rest training) is handled by this.
"""
from __future__ import absolute_import
from __future__ im... | python |
# Copyright 2020 kubeflow.org
#
# 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... | python |
# import asyncio
# import requests
# import json
# import re
import os
import discord
from discord.ext import commands, tasks
from discord_slash import SlashCommand, SlashContext
from itertools import cycle
import keep_alive
# # grabbing the config file
# with open('config.json') as config_file:
# secrets = json.... | python |
from sys import exit
import json
from time import sleep
from confluent_kafka import Consumer, KafkaError
ERROR_CODE_ZERO = 0
ERROR_CODE_ONE = 1
EMPTY_ERROR_MESSAGE = ""
PAUSE = 3
class KafkaConsumer:
def __init__(self, settings, client_id, timeout, auto_commit):
self._settings = settings
self._t... | python |
#!/usr/bin/env python3
"""
both web service and mosquitto are running locally.
MENSHNET_UNITTEST="yes" is defined
1. simulate the okta routine that creates the api key by calling
the same endpoint in the server to generate an apiKey.
"""
import os
os.environ["MENSHNET_UNITTEST"] = "yes"
import menshnet
| python |
from abc import ABCMeta, abstractmethod
class Animal(metaclass=ABCMeta):
def walk(self):
print('Walking...')
def eat(self):
print('Eating...')
@abstractmethod
def num_legs():
pass | python |
class Solution:
def solve(self, n):
count = 1
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
count += 1
return count
| python |
# -*- coding: utf-8 -*-
from flask import Flask, jsonify
from flask.ext.cors import CORS, cross_origin
from pymongo import MongoClient
import os
app = Flask(__name__)
CORS(app)
mongodb_host = '172.16.0.2'
mongodb_port = 27017
client = MongoClient(mongodb_host,mongodb_port)
collection = client.conflict_db.events
@... | python |
# -*- 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... | python |
import os
import subprocess
from setuptools import find_packages, setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
def get_git_commit_number():
if not os.path.exists('.git'):
return '0000000'
cmd_out = subprocess.run(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE)
... | python |
from django.test.testcases import TestCase
from corehq.messaging.smsbackends.sislog.util import convert_raw_string
class GSM0338Portuguese(TestCase):
def test_decode(self):
raw_to_clean = {
# basic character test
"associa\x09\x7bo": "associa\u00e7\u00e3o",
# extended ... | python |
from finbert.finbert import predict
from pytorch_pretrained_bert.modeling import BertForSequenceClassification
import argparse
from pathlib import Path
import datetime
import os
import random
import string
import pandas as pd
import time
import pickle
import multiprocessing as mp
import gc
# globals
model = None
pars... | python |
import pytest
from fastapi.testclient import TestClient
from firedantic import ModelNotFoundError
from _pytest.monkeypatch import MonkeyPatch
import saatja.request_dependencies as request_dependencies
from saatja.db.task import ScheduledTask, DeliveredTask, TaskError
from saatja.utils import now_utc
SCHEDULER_HEADERS... | python |
from typing import Union
from discordmovies.attributes import DiscordMoviesAttributes
from typing import List
from discordmovies.outputmodules.filehelper import FileHelper
from discordmovies.inputmodules.input import Input
class DiscordMovies:
"""
A class for going through a discord movie recommendations chan... | python |
import os
import shutil
import datetime
from ebooklib import epub
from toolbox.tools import Now
from compiler import epub_html
now = Now()
css = """body{padding:0;margin:0;line-height:1.2;text-align:justify}
p{text-indent:2em;display:block;line-height:1.3;margin-top:0.6em;margin-bottom:0.6em}
div{margi... | python |
# loop3
userinput = input("Enter a letter in the range A - C : ")
while (userinput != "A") and (userinput != "a") and (userinput != "B") and (userinput != "b") and (userinput != "C") and (userinput != "c"):
userinput = input("Enter a letter in the range A-C : ")
| python |
import math
import numpy as np
year = input("Enter the year to be checked : ")
def check_leap(year):
print(type(year))
year = int(year)
if year%100==0:
print("Leap Year")
elif year%4 == 0:
print("Leap Year")
elif year % 400 == 0:
print("Leap Year")
else:
print("... | python |
# -*- coding: utf-8 -*-
__author__ = 'mariosky'
import json
import os
import time
print os.environ['REDIS_HOST']
from redis_cola import Cola, Task
server = Cola("perl6")
code = """
sub add($a, $b) {
say "Hi";
return $a+$b;
}
"""
test = """
# .... tests
is add(6,1), 9, 'Suma do... | python |
from .di import DI
from .standard_dependencies import StandardDependencies
from .additional_config import AdditionalConfig
| python |
from spyd.registry_manager import register
@register('client_message_handler')
class SayteamHandler(object):
message_type = 'N_SAYTEAM'
@staticmethod
def handle(client, room, message):
player = client.get_player()
room.handle_player_event('team_chat', player, message['text'])
| python |
# note:
from __future__ import absolute_import
from .click_models import *
from .data_utils import *
from .hparams import *
from .metric_utils import *
from .metrics import *
from .propensity_estimator import *
from .sys_tools import *
from .team_draft_interleave import *
from .RAdamOptimizer import *
| python |
import numpy as np
import joblib
from matplotlib import pyplot
import pandas as pd
import matplotlib.pyplot as plt
import math
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, f1_s... | python |
from random import choice
n = str(input('nome do 1° aluno: '))
n2 = str(input('nome do 2° aluno: '))
n3 = str(input('nome do 3° aluno: '))
n4 = str(input('nome do 4° aluno: '))
lista = (n,n2,n3,n4)
print(f'O aluno escolhido é: {choice(lista)}') | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-01-18 15:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SCIMPl... | python |
# -*- coding: utf-8 -*-
# Builtin Modules
import time
import traceback
import functools
# 3rd-party Modules
import redis
import six
# Project Modules
from worker.utils import toolkit, yaml_resources
from worker.utils.log_helper import LogHelper
CONFIG = yaml_resources.get('CONFIG')
def get_config(c):
config = ... | python |
from typing import Dict, Generator, Optional
import numpy as np
from netqasm.lang import instr as ins
from netqasm.lang.instr import core, nv
from netqasm.lang.instr.flavour import Flavour
from netsquid.components import Instruction as NetSquidInstruction
from netsquid.components.instructions import (
INSTR_CXDIR,... | python |
import math
from hurry.filesize import size
def convert_web_speed_size(size_bytes):
"""
Convert byte to other Units of information and show in xbit vs xbyte
:param size_bytes:
:return:
"""
if size_bytes == 0:
return "0B"
size_name = ("B", "Kbit/s", "Mbit/s", "Gbit/s", "... | python |
# Prime Number Sieve
# author: A1p5a
import math
def is_prime(num):
# Returns True if num is a prime number, otherwise False.
# Note: Generally, isPrime() is slower than primeSieve().
# all numbers less than 2 are not prime
if num < 2:
return False
# see if num is divisible by any num... | python |
from NewDouban import NewDouban
if __name__ == "__main__":
douban = NewDouban()
result = douban.search("知识考古学")
for book in result:
print(book)
| python |
#!/usr/bin/env python
import rospy
import actionlib
import tf
from math import radians, atan2, cos, sin
from fetch_manipulation_pipeline.msg import GrabBagAction, GrabBagGoal
import py_trees
import py_trees_ros
from geometry_msgs.msg import Pose
from copy import deepcopy
class GrabBagBehavior(py_trees_ros.actions.Ac... | python |
import logging
from pyradios.utils import setup_log_file
LOG_FILENAME = "pyradios.log"
logger = logging.getLogger(__name__)
formatter = logging.Formatter(
"[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s"
)
file_handler = logging.FileHandler(setup_log_file(LOG_FILENAME))
file_handler.setForm... | python |
import os
import argparse
from terminaltables import AsciiTable
def _format(number):
return '{:.4f}'.format(float(number))
parser = argparse.ArgumentParser(description='Display kitti results')
parser.add_argument('--results', type=str, required=True, help='path to a kitti result folder')
parser.add_argument('--no... | python |
import asyncio
import rlp
import ethereum.transactions
from ethereum import utils
from ethereum.utils import normalize_key, ecsign
from ethereum.transactions import unsigned_tx_from_tx, UnsignedTransaction
# NOTE: this is to hotfix a bug in pyethereum's signing functions
# fixed in https://github.com/ethereum/pyether... | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : spider.py
@Time : 2020-8-1 22:00:44
@Author : Recluse Xu
@Version : 1.0
@Contact : 444640050@qq.com
@Desc : 用Selenium处理SliderCaptcha
'''
# here put the import lib
from selenium.common.exceptions import TimeoutException
from selenium.webd... | python |
from __future__ import absolute_import, print_function
import tensorflow as tf
from tensorflow.keras import regularizers
from niftynet.network.highres3dnet import HighResBlock
from tests.niftynet_testcase import NiftyNetTestCase
class HighResBlockTest(NiftyNetTestCase):
def test_3d_increase_shape(self):
... | python |
# -*- coding: utf-8 -*-
"""
@created on: 4/19/20,
@author: Shreesha N,
@version: v0.0.1
@system name: badgod
Description:
..todo::
"""
from torch.utils.tensorboard import SummaryWriter
import torch
import torch.nn as nn
import torch.optim as optim
import pandas as pd
import numpy as np
from torch import tensor
impor... | python |
from django.db import models
from .Newsletterapi import *
# Create your models here.
"""class Summary_Art(models.Model):
url = models.TextField()
summary = get_summary(url)
text = summary[0]
summary = summary[1]
#user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #Option... | python |
"""empty message
Revision ID: dc0c3839e0c4
Revises: 962314b7ff85
Create Date: 2021-12-07 08:58:26.839235
"""
# revision identifiers, used by Alembic.
revision = 'dc0c3839e0c4'
down_revision = '962314b7ff85'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... | python |
import requests
from django.conf import settings
from django.test import TestCase, RequestFactory
from django.utils.six import text_type
from dps.transactions import make_payment
from dps.models import Transaction
from .models import Payment
class DpsTestCase(TestCase):
def setUp(self):
self.factory = R... | python |
import torch.nn as nn
from n3 import ExternNode
class Linear(ExternNode):
input_channels: int
output_channels: int
bias: bool
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._inner = nn.Linear(self.input_channels,
self.output_channels,
... | python |
#! /usr/bin/env python3
from scripts.fileReadWriteOperations import *
import copy
import math
import os
import sys
import pandas as pd
def mergeTwoTranscripts( whole_annotations, transcript_id_i, transcript_id_j, chromosome ):
"""
"""
# print("Merging",transcript_id_i,transcript_id_j)
chromosome = t... | python |
"""
85
maximal rectangle
hard
Given a rows x cols binary matrix filled with 0's and 1's,
find the largest rectangle containing only 1's and return its area.
"""
from typing import List
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
| python |
from src import chck_res
import pytest
@pytest.fixture(scope="module")
def base_chck():
data="sandwich"
return (chck_res(data))
| python |
import gym
import numpy as np
import threading
class FakeMultiThread(threading.Thread):
def __init__(self, func, args=()):
super().__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
... | python |
books = [
(1, "Learning Python", "", "Марк Лътз, Дейвид Асър", "O'Reily", 1999, 22.7),
(2, "Think Python", "An Introduction to Software Design", "Алън Б. Дауни", "O'Reily", 2002, 9.4),
(3, "Python Cookbook", "Recipes for Mastering Python 3", "Браян К. Джоунс и Дейвид М. Баазли", "O'Reily", 2011, 135.9)
]
d... | python |
import asyncio
import discord
from discord.ext import commands
from otherscipts.helpers import create_mute_role
class Moderator(commands.Cog):
def __init__(self, bot, theme_color):
self.bot = bot
self.theme_color = theme_color
self.warn_count = {}
@commands.command(name="warn")
@... | python |
"""
Credit to espnet: https://github.com/espnet/espnet/blob/master/espnet2/iterators/multiple_iter_factory.py
"""
import logging
from typing import Callable
from typing import Collection
from typing import Iterator
import numpy as np
from typeguard import check_argument_types
from muskit.iterators.abs_iter_factory i... | python |
import logging
import random
import time
from .exception import re_raisable
logger = logging.getLogger(__name__)
def retry(action, name, times=5):
try:
return action()
except Exception as e:
if times < 20:
throttle_seconds = min(pow(2, times * random.uniform(0.1, 0.2)), 30)
... | python |
import os
import sys
import logging
from typing import List, Type
from intents.language_codes import LanguageCode, LANGUAGE_CODES, FALLBACK_LANGUAGE
logger = logging.getLogger(__name__)
def agent_language_folder(agent_cls: Type["intents.model.agent.Agent"]) -> str:
main_agent_package_name = agent_cls.__module__.... | python |
import io, os
# CHANGE THIS to the path to your TN file, it might be in your downloads directory
filename = "C:/Users/benja/Documents/uwgit/en_tn/en_tn_02-EXO.tsv"
os.rename(filename,filename.replace('.tsv','.old'))
filename = filename.replace('.tsv','.old')
with io.open(filename, encoding='utf8') as f:
with io.o... | python |
"""
Provides classes that take protocol requests, send that request to
the server, and write a particular genomics file type with the results.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import pysam
import ga4gh.datamodel.reads... | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 28 19:43:57 2020
@author: Alok
"""
class Info:
def __init__(self,id_no,name,mobile,marks):
self.id_no=id_no
self.name=name
self.mobile=mobile
self.marks=marks
def merge_sort(arr):#time comp nlogn
if(len(arr)>1):
... | python |
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
name = None
if request.method == 'POST' and 'name' in request.form:
name = request.form['name']
return render_template('index.html', name=name)
if __name__ == '__main__':
... | python |
import matplotlib.pyplot as plt
import numpy as np
# save_zangle_width_file = '/home/ljm/NiuChuang/AuroraObjectData/zangle_width/agw_tr1058_te38044_arc_line (copy 1).txt'
save_zangle_width_file = '/home/ljm/NiuChuang/AuroraObjectData/zangle_width/agw_tr1058_te38044_arc_cnd2_line.txt'
f = open(save_zangle_width_file, 'r... | python |
import scrapy
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
def parse(self, response):
... | python |
import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from PIL import Image
def to_pil(img):
''' Transforms a 3 dimentional matrix into a PIL image '''
return Image.fromarray(img.astype('uint8'), 'RGB')
def to_cv2(img):
open_cv_image = np.array(img)
# Convert RG... | python |
#!/usr/bin/env python3
from setuptools import setup
from setuptools import find_packages
from codecs import open
from os import path
import sys
import shutil
import os
from ly_bar_incr import __version__
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
lo... | python |
#!/usr/bin/env python3
import pathfinder as pf
import math
if __name__ == "__main__":
points = [
pf.Waypoint(-4, -1, math.radians(-45.0)),
pf.Waypoint(-2, -2, 0),
pf.Waypoint(0, 0, 0),
]
info, trajectory = pf.generate(
points,
pf.FIT_HERMITE_CUBIC,
pf.SAMP... | python |
import os
import subprocess
import yaml
def run_command(
command,
shell=True,
env=None,
execute="/bin/sh",
return_codes=None,
):
"""Run a shell command.
The options available:
* ``shell`` to be enabled or disabled, which provides the ability
to execute arbitrary stings or not... | python |
from random import random, randrange
def ranksb ( N, K ) :
if N < K :
raise Exception, "N must be no less than K"
if K == 0 : return [ ]
L2 = K + 1
R = L2
A = K * [ 0 ]
while 1 :
M = 1 + int ( random ( ) * N )
I = 1 + ( M - 1 ) % K
breakthencontinue = 0
... | python |
import machine
import utime
import ntptime
from . import config as cfg
rtc = machine.RTC()
def set_rtc_from_ntp(config):
try:
mytime = utime.localtime(ntptime.time() + int(config['tz_offset']))
except:
mytime = utime.localtime()
year, month, day, hour, minute, second, weekday, yearday = my... | python |
"""
Objetivo: Resolver questão 2 do segundo laboratorio.
"""
def fibonachi(n): #n é o ordem do elemento, por exemplo se n=1 retorna o primeiro termo da serie
if n == 1 or n == 0:
return 0 # primeiro elemento é 0
elif n == 2:
return 1 # segundo elemento é 1
else:
f_anterior = 0
... | python |
'''
CIS 122 Fall 2019 Assignment 7
Author: Zoe Turnbull
Partner:
Description: List manager program.
'''
# VARIABLES
list_var = []
list_cmd = ["Add", "Delete", "List", "Clear"]
list_cmd_desc = ["Add to list.", "Delete Information.", "List information.", "Clear list."]
left = True
right = False
# FUNCTIONS... | python |
from jellylib.error import Error
EOF = object()
Newlines = frozenset("\n\r")
LineEnd = frozenset(['\n', '\r', EOF])
Whitespaces = frozenset(" \t")
Spaces = frozenset("\n\r\t ")
LowerLetter = frozenset("abcdefghijklmnopqrstuvwxyz")
UpperLetter = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
Digit = frozenset("0123456789")
P... | python |
from typing import Callable
import pytest
from django.db import connection
from ..models import (
AuditLogEntry,
MyAuditLoggedModel,
MyConvertedToAuditLoggedModel,
MyManuallyAuditLoggedModel,
MyNoLongerAuditLoggedModel,
MyNoLongerManuallyAuditLoggedModel,
)
@pytest.mark.usefixtures("db", "au... | python |
s = 0
for x in range(1000):
if x % 5 != 0 and x % 7 != 0:
s += 1
print(s)
| python |
# Entra na pasta onde está este arquivo, caso contrário ele faria tudo na pasta principal
import os
diretorio_geral = os.path.dirname(__file__)
diretorio_local = 'texto01.txt' # Local e nome do arquivo que eu quero criar
juntando_os_caminhos_do_diretorio_e_nome_do_arquivo_que_sera_criado = os.path.join(diretorio_geral... | python |
import pygame
import random
import sys
from pygame.locals import *
class TimedWordsTeamGame(object):
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (230, 230, 0)
GREEN = (0, 128, 0)
BLUE = (0, 0, 255)
INV_PLAY_TIME = 0.5
NUM_TEAM_MEMBERS = 30
def __init__(self... | python |
import numpy as np
# TODO: convert these to params files
# params used for the inverted pendulum system
m = 1.4 # mass of quadrotor (kg)
L = 0.3 # length from center of mass to point of thrust (meters)
gr = 9.81 # gravity (m/s^2)
I = m * L ** 2
b = 0.
max_torque = 1.0
max_speed = 8
states = 2 # theta and thetadot
... | python |
import os
from RouterConfiguration.Cisco.cisco_config_features import *
from utils import *
from network_features import *
def route_map_deny(rm, seq):
rm.perm[seq] = 'deny'
return f'{rm} {rm.perm[seq]} {seq}'
def route_map_permit(rm, seq):
rm.perm[seq] = 'permit'
return f'{rm} {rm.perm[seq]} {seq}... | python |
#################################################
# Implements a dynamical dense layer that allows
# both adding and removing both input and output
# features and a simple update step for both.
#
# Inspired by "Lifelong Learning with Dynamically
# Expandable Networks", ICLR, 2017 (arXiv:1708.01547)
####################... | python |
#Import Libraries
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import median_absolute_error
#----------------------------------------------------
#Applying Lasso Regression Model
'''
#sklearn.linear_model.... | python |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('search', views.tweets_search, name='tweets_search'),
path('articles', views.articles, name='articles'),
path('portals', views.portals, name='portals'),
path('graphics', views.graphics, name='graphics'),
... | python |
import torch
from torch import Tensor
from torch import nn
from typing import Union, Tuple, List, Iterable, Dict
import os
import json
class LayerNorm(nn.Module):
def __init__(self, dimension: int):
super(LayerNorm, self).__init__()
self.dimension = dimension
self.norm = nn.Lay... | python |
hp = __import__('heap');
#place heap.py (max_heap.py - name changed) in same directory
class HeapSort(object):
def __init__(self, arr):
super(HeapSort, self).__init__()
self.arr = arr
def printH(self):
print(self.arr)
def heapSort(self):
heap = hp.Heap()
heap.createHeap(*self.arr)
i = 0
while(heap.s... | python |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
requirements = [
'DAWG-Python==0.7.2',
'docopt==0.6.2',
'psycopg2==2.8.6',
'pymorphy2==0.9.1',
'pymorphy2-dicts-ru==2.4.417127.4579844'
]
setup(
name='search_engine_rishatsadykov',
version='1.... | python |
from collections import deque
from random import randint
import settings
from datatypes import Vector, Position, Draw
class Player:
HEAD_CHAR = "%"
BODY_CHAR = "@"
TAIL_CHAR = "*"
DEAD_HEAD_CHAR = "x"
DEAD_BODY_CHAR = "@"
DEAD_TAIL_CHAR = "+"
UP = Vector(0, -1)
DOWN = Vector(0, 1)
... | python |
# Copyright 2013-2018 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)
import pytest
from spack.main import SpackCommand, SpackCommandError
info = SpackCommand('env')
@pytest.mark.parametri... | python |
"""django_maps URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | python |
"""
Just a process to a centralized basic create user from password and username
"""
from flask import request, redirect, render_template, session, flash, abort, jsonify, Response, flash
import random
import json
from flask_babel import _
from datetime import datetime, timedelta
import uuid
from urllib.parse import u... | python |
import numpy as np
import pandas as pd
import os
import sys
"""
Storey Q-Values - https://github.com/StoreyLab/qvalue
--------------------
Python Wrapper
Author: Francois Aguet
https://github.com/broadinstitute/tensorqtl/blob/master/tensorqtl/rfunc.py
"""
def qvalue(p, lambda_qvalue=None):
"""Wrapper for qvalue::q... | python |
#-*- coding: utf-8 -*-
import json
import socket
import hashlib
import base64
import traceback
from threading import Thread, Event
from Queue import Queue, Empty
from defs import *
from protocol import parse_frame, make_frame
from utils import r_select
class _BaseWsSock(object):
def _handshake... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-09-21 18:55
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dep... | python |
__author__ = 'Will.Smith'
# -----------------------------------------------------------------------------
# Name: WeightMethod.py
# Purpose: Model for Weight Methods
#
# Author: Will Smith <will.smith@noaa.gov>
#
# Created: Jan 01, 2016
# License: MIT
# ------------------------------------------... | python |
import random
import torch
from sl_cutscenes.constants import SCENARIO_DEFAULTS, PI
from sl_cutscenes.objects.mesh_loader import MeshLoader
from sl_cutscenes.objects.occupancy_matrix import OccupancyMatrix
from sl_cutscenes.utils import utils as utils
class DecoratorLoader:
"""
Class to add random decorativ... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: proto/configuration.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database ... | python |
import pandas as pd
import numpy as np
from misc import data_io
DATA_DIR = 'data/ut-interaction/'
""" Folder structure
<'set1' or 'set2'>/keypoints
<video_name>/
<video_name>_<frame_num>_keypoints.json
...
Ex: DATA_DIR + 'set1/keypoints/0_1_4/0_1_4_000000000042_keypoints.json'
"""
VIDEOS = [
... | python |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/projects')
def projects():
return render_template('projects.html')
@app.route('/about')
def about():
return render_template('about.html')
app.run(debug=True) | python |
import sys
sys.path.append('/home/jwalker/dynamics/python/atmos-tools')
sys.path.append('/home/jwalker/dynamics/python/atmos-read')
import atmos as atm
import merra
from merra import calc_fluxes
scratchdir = '/net/eady/data1/jwalker/datastore/scratch/'
def filename(varname, datestr):
savedir = '/net/eady/data1/j... | python |
#!/usr/bin/env python
# Copyright 2016 WebAssembly Community Group participants
#
# 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 ... | python |
'''
author: eleclike
date:
'''
| python |
# -*- coding: utf-8 -*-
# Part of the masterfile package: https://github.com/uwmadison-chm/masterfile
# Copyright (c) 2020 Board of Regents of the University of Wisconsin System
# Written by Nate Vack <njvack@wisc.edu> at the Center for Healthy Minds
# at the University of Wisconsin-Madison.
# Released under MIT licen... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.