content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# flake8: noqa
from my_happy_pandas._libs import NaT, Period, Timedelta, Timestamp
from my_happy_pandas._libs.missing import NA
from my_happy_pandas.core.dtypes.dtypes import (
CategoricalDtype,
DatetimeTZDtype,
IntervalDtype,
PeriodDtype,
)
from my_happy_pandas.core.dtypes.missing import isna, isnull... | python |
import numpy as np
import scipy
import GPyOpt
import GPy
from multi_objective import MultiObjective
from multi_outputGP import multi_outputGP
from uKG_SGA import uKG_SGA
from uKG_cf import uKG_cf
from uEI_noiseless import uEI_noiseless
from parameter_distribution import ParameterDistribution
from utility import Utility... | python |
# NOQA
import asyncio
import requests
from xml.etree import ElementTree
from itertools import islice
from discord.ext import commands
class Language:
"""Dictionaries & other word things."""
def __init__(self, bot):
"""Cog constructor."""
self.bot = bot
@commands.command()
async def d... | python |
import pytest
import skbot.ignition as ign
import skbot.transform as tf
from typing import Tuple, List, Union
from pathlib import Path
joint_types = Union[tf.RotationalJoint, tf.PrismaticJoint]
sdf_folder = Path(__file__).parents[1] / "ignition" / "sdf"
ign.sdformat.generic_sdf.base.WARN_UNSUPPORTED = False
@pytest... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import spacetimeformer as stf
from .encoder import VariableDownsample
class SpacetimeformerEmbedding(nn.Module):
def __init__(
self,
d_y,
d_x,
d_model=256,
time_emb_dim=6,
method="spatio-temporal"... | python |
from subprocess import check_output, STDOUT, CalledProcessError
# ffmpeg command:
# ffmpeg -decryption_key 5df1b4e0d7ca82a62177e3518fe2f35a -i "./video_encripted.mp4" -pix_fmt bgr24 -vcodec copy "./video_decripted.mp4"
schema_encript = "cenc-aes-ctr"
key_encript = "5df1b4e0d7ca82a62177e3518fe2f35a"
kid_encript... | python |
/usr/lib64/python2.7/sre_parse.py | python |
import sys
sys.path.append("/home/shansixioing/tools")
from gen_utils import master_run
import random
import numpy as np
import glob
seed = 12342
random.seed(seed)
np.random.seed(seed)
import time
def main():
# gpu_ls = ['babygroot0', 'babygroot1', 'babygroot3', 'groot0', 'groot1', 'groot2', 'groot3', 'nebula0'... | python |
class BaseTask:
def run(self):
raise Exception("Method is not implemented")
def get_status(self):
raise Exception("Method is not implemented")
def wipe(self):
pass
| python |
# Copyright 2019 The IEVA-DGM Authors. All rights reserved.
# Use of this source code is governed by a MIT-style license that can be
# found in the LICENSE file.
# mpas dataset
from __future__ import absolute_import, division, print_function
import os
import pandas as pd
import numpy as np
from skimage import io, t... | python |
import os
from pkg_resources import resource_filename
import pandas as pd
def load_titanic(return_X_y: bool = False, as_frame: bool = False):
"""
Loads in a subset of the titanic dataset. You can find the full dataset [here](https://www.kaggle.com/c/titanic/data).
Arguments:
return_X_y: return a... | python |
# Contents of test_cart_1d.py
#===============================================================================
# TEST CartDecomposition and CartDataExchanger in 1D
#===============================================================================
def run_cart_1d( verbose=False ):
import numpy as np
from mpi4py ... | python |
from django.shortcuts import get_object_or_404
from django import template
from mailing.models import CustomerLoyaltyElement
from accounts.models import CorporateProfile, CompanyName
from travelling.models import Trip, Rating
register = template.Library()
@register.inclusion_tag('mailing/get-loyalty-element.html', ... | python |
# coding=utf-8
"""
Emulate a gmetric client for usage with
[Ganglia Monitoring System](http://ganglia.sourceforge.net/)
"""
from . Handler import Handler
import logging
try:
import gmetric
except ImportError:
gmetric = None
class GmetricHandler(Handler):
"""
Implements the abstract Handler class, se... | python |
from datetime import datetime
from pathlib import Path
from textwrap import dedent
import os
import pwd
import subprocess
import sys
import textwrap
import click
import jinja2
STATUS_CLASSIFIERS = {
"planning": "Development Status :: 1 - Planning",
"prealpha": "Development Status :: 2 - Pre-Alpha",
"alpha... | python |
__version__ = "0.0.9"
from .core import *
| python |
import sys
__version__ = "0.1"
from .dicodon_optimization import (
optimize_dicodon_usage,
dicodon_count_from_sequences,
codon_count_from_sequences,
dicodon_score_dict_from_sequences,
score,
translate_to_aa,
)
from .fasta import parse_fasta_to_dict
| python |
import pywhatkit
import speech_recognition as sr
import pyttsx3
r = sr.Recognizer()
def SpeakText(command):
engine = pyttsx3.init()
engine.say(command)
engine.runAndWait()
try:
with sr.Microphone() as source2:
r.adjust_for_ambient_noise(source2, duration=0.2)
... | python |
#!/usr/bin/env python3
import sys
import getopt
import os
import json
from typing import Dict
from typing import List
def showhow():
print("configfilter.py -t tpldir -o outdir [-p <pattern>] [-v] <key-value.json>")
print(" -t: 設定ファイルのテンプレートが格納されたディレクトリ")
print(" -o: 処理された設定ファイルの出力先ディレクトリ")
print(" ... | python |
from splinter import Browser
from bs4 import BeautifulSoup
from webdriver_manager.chrome import ChromeDriverManager
import requests
import pandas as pd
import pymongo
import time
client = pymongo.MongoClient('mongodb://localhost:27017')
db = client.mars_db
collection = db.mars
def init_browser():
executable... | python |
class AnnotationModel:
def __init__(self, text: str, comment: str, last_update: str):
self.text = text
self.comment = comment
self.last_update = last_update
| python |
""" Assignment 7
Write a short script that will get a name from the user.
Find the length of the name.
If the length is lower than 5 print "Under".
If the length is more than 5 print "Over".
If the length is exactly 5 print "Five".
Try to use 'if', 'else' and 'elif' exactly once each.
Also, try not to evaluate the le... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : leeyoshinari
import pymysql
import zhihu_spider.settings as cfg
class MySQL(object):
def __init__(self):
self.db = None
self.cursor = None
self.connect()
def connect(self):
self.db = pymysql.connect(host... | python |
import numpy as np
# ra54 = np.random.random((5,4))
ra54 = np.arange(20).reshape(5,4)
print(ra54)
print(ra54[2,3])
print(ra54[(2,3),(3,3)])
it = np.nditer(ra54, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
idx = it.multi_index
print(idx, '=>', ra54[idx])
it.iternext()
| python |
import asyncio
async def make_americano():
print("Americano Start")
await asyncio.sleep(3)
print("Americano End")
return "Americano"
async def make_latte():
print("Latte Start")
await asyncio.sleep(5)
print("Latte End")
return "Latte"
async def main():
coro1 = make_americano()
... | python |
# -*- coding: utf-8 -*-
"""Special tools for working with mapping types."""
from types import SimpleNamespace
from typing import Mapping, Iterator, Iterable, TypeVar, Union, Any
T = TypeVar("T")
T_Sentinel = type("T_Sentinel", (), {})
R_SENTINEL = T_Sentinel()
T_Bool = Union[T_Sentinel, bool]
def lowerify_mapping(... | python |
# Manipulating Python Lists
#
import math
import os
# Create a Python List
#
cars=["Toyota","Chevrolet","Ford","Honda","Brabus"]
print(cars)
# Basic Operations on Python List
#
# Arithmetic Operations on a Python List
#
# print(math.pi)
| python |
"""
???+ note "Intermediate classes based on the functionality."
"""
import numpy as np
from bokeh.models import CDSView, IndexFilter
from bokeh.palettes import Category20
from bokeh.layouts import row
from hover import module_config
from hover.utils.misc import current_time
from hover.utils.bokeh_helper import bokeh_h... | python |
##########################################################################
#
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | python |
import concurrent.futures
class Epochs:
def __init__(self, sfcContract, database):
self.__sfcContract = sfcContract
self.__database = database
self.__data = []
def __getEpochValidator(self, epochId, validatorId):
data = self.__sfcContract.getEpochValidator(epochId, validatorId... | python |
import matplotlib.pyplot as plt
import umap
import umap.plot
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import numpy as np
def plot_umap(features, labels, save_path = None, annotation = False):
'''
:param features:
:param labels:
:param save_path:
:param annotation: dictionary, wi... | python |
from sys import stderr
from queue import LifoQueue as stack
from queue import PriorityQueue as p_queue
from queue import SimpleQueue as queue
import networkx as nx
import pylab as plt
from IPython.core.display import HTML, display, Image
# import pygraphviz
# from networkx.drawing.nx_agraph import graphviz_layout
# ... | python |
from collections import OrderedDict
import copy
import json
import io
import yaml
import os
import progressbar
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
warnings.filterwarnings("ignore", message="Polyfit m... | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 19 11:23:32 2015
@author: Wasit
"""
mytuple=(1,2,3,'my tuple')
print mytuple[-1] | python |
from typing import List
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort(reverse = True)
return max(nums[0] * nums[1] * nums[2], nums[0] * nums[-1] * nums[-2]) | python |
def addition(firstNumber, secondNumber):
answer = firstNumber + secondNumber
return answer
def subtraction(firstNumber, secondNumber):
answer = firstNumber - secondNumber
return answer
def multiplication(firstNumber, secondNumber):
answer = firstNumber * secondNumber
return answer
def divisio... | python |
import socket
import struct
# thrift does not support unsigned integers
def hex_to_i16(h):
x = int(h)
if (x > 0x7FFF): x-= 0x10000
return x
def i16_to_hex(h):
x = int(h)
if (x & 0x8000): x+= 0x10000
return x
def hex_to_i32(h):
x = int(h)
if (x > 0x7FFFFFFF): x-= 0x100000000
return x... | python |
# the main optimization function
def main(districts_orig, blocks_dict_orig):
import numpy as np
import statistics as st
import random
from classes import Block, SchoolDistr
from copy import deepcopy
current_best_cumul_zvalue = None
current_best_distr_division = None
... | python |
__version__ = '0.15.2rc0'
| python |
# Copyright (c) 2019 Erwin de Haan. 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 applic... | python |
#!/usr/bin/env python3
"""
Send reports artifacts by email
"""
import logging
import os
import tempfile
import zipfile
from json.decoder import JSONDecodeError
import requests
from megalinter import Reporter, config
class FileIoReporter(Reporter):
name = "FILEIO"
scope = "mega-linter"
def __init__(self,... | python |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from enum import Enum
from typing import Iterable
from pants.base import deprecated
from pants.engine.rules import Rule, collect_rules, rule
from pants... | python |
import cc_dat_utils
#Part 1
input_dat_file = "data/pfgd_test.dat"
#Use cc_dat_utils.make_cc_data_from_dat() to load the file specified by input_dat_file
#print the resulting data
if __name__ == '__main__':
# Reading from input dat file
dat_file = "data/pfgd_test.dat"
result = cc_dat_utils.make_cc_data_... | python |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | python |
"""
471. Top K Frequent Words
https://www.lintcode.com/problem/top-k-frequent-words/description?_from=ladder&&fromId=37
hash map: o(n) time o(n) extra space
idea:
only record the maximum kth occurance of words in the heap, keep the minmum occurance
if incoming words occurance > min occurance for the current kth mos... | python |
from models.model_factory import RegisterModel
import torchvision.models as models
import torch.nn as nn
import torch
@RegisterModel('resnet18')
class Resnet18(nn.Module):
def __init__(self, args):
super(Resnet18, self).__init__()
self._model = models.resnet18(pretrained= args.trained_on_imagenet)
... | python |
#
# Copyright (c) 2019 UAVCAN Development Team
# This software is distributed under the terms of the MIT License.
# Author: Pavel Kirienko <pavel.kirienko@zubax.com>
#
"""
This module contains implementations of various CRC algorithms used by the transports.
`32-Bit Cyclic Redundancy Codes for Internet Applications (... | python |
from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from .models import Lost
# Create your views here.
def home(request):
stuffs = Lost.objects.all()
return render(request, 'lost.html', {'stuffs' : stuffs})
def new(request):
if request.method == 'POST':
... | python |
import numpy as np
import torch
from torchvision import datasets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from skimage.measure import compare_psnr, compare_ssim
from skimage.transform import resize
from skimage.restoration import denoise_nl_means, estimate_sigma
import PIL
import skim... | python |
from MergeIndependent import *
| python |
import numpy as np
from netCDF4 import Dataset
from scipy.interpolate import griddata
from collections import defaultdict
lon_high = 101.866
lon_low = 64.115
lat_high= 33.
lat_low=-6.79
numpy_cube=np.load('/nfs/a90/eepdw/Data/Observations/Satellite/GSMAP_Aug_Sep_2011/GSMAP_EMBRACE.npz')
# Load land sea mask. T... | python |
import json, re, os, platform, subprocess, sys
from pathlib import Path
from flask import Flask, request, redirect, url_for, Response, send_file, render_template
# from pegpy.main import macaron
# from datetime import datetime
import transpiler
app = Flask(__name__)
# horizontalBar = r"---"
# reHorizontalBar = re.c... | python |
# Copyright 2022 MTS (Mobile Telesystems)
#
# 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 agr... | python |
import cv2
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestNeighbors
from scipy import interpolate
import math
NN_RATIO = 0.7
NUM_IAC_ITER = 200
ransac_thr = 10
ransac_iter = 1000
RANDOM_SEED = 42
# Matches SIFT features in template to nearest neighbours... | python |
import numpy as np
import cudarray as ca
from .. import expr as ex
if ca.float_ == np.float32:
eps = 1e-04
else:
eps = 1e-06
def allclose(a, b, rtol=None, atol=None):
if ca.float_ == np.float32:
rtol = 1e-03 if rtol is None else rtol
atol = 1e-04 if atol is None else atol
else:
... | python |
"""
Check the tutorial for comments on the code.
"""
import sys
from direct.showbase.ShowBase import ShowBase
class Application(ShowBase):
def __init__(self):
sys.path.insert(0, "render_pipeline")
from rpcore import RenderPipeline
self.render_pipeline = RenderPipeline()
self.re... | python |
# Parts of the code in this file have been borrowed from:
# https://github.com/facebookresearch/habitat-api
import os
import numpy as np
import torch
from habitat.config.default import get_config as cfg_env
from habitat.datasets.pointnav.pointnav_dataset import PointNavDatasetV1
from habitat import Config, Env, RLEn... | python |
from util.Docker import Docker
from util.Api import Api
import os
import unittest
class Dredd:
image = 'sls-microservices/openapi'
container_name = ''
def test_against_endpoint(self, service, api_endpoint, links=[], env=[]):
self.container_name = Docker().random_container_name('openapi')
co... | python |
"""
This file can generate all the figures used in the paper.
You can run it with -h for some help.
Note that:
- you need to have produced the data to be able to plot anything.
"""
import numpy as np
import pandas as pd
from scipy.stats import permutation_test
# ===================================================... | python |
# get data from txt file with calibration
import numpy as np
from scipy import interpolate
calib_data = np.genfromtxt('Turb_calib.txt', dtype='float', skip_header= 1) # get txt file (ignores 1st row)
x = calib_data[:, 0]
y = calib_data[:, 1]
turb_interpolate = interpolate.interp1d(x, y, kind= 'linear', bounds_erro... | python |
# Uses python3
n = int(input())
a = [int(x) for x in input().split()]
assert(len(a) == n)
i, j = 0, 1
for k in range(n):
if a[i] < a[k]:
i, j = k, i
print(a[i]*a[j])
| python |
import urllib
import urllib2
import urlparse
import json
import logging
class APIClient:
def __init__(self, api_root, debug=False):
self.api_root = api_root
self.debug = debug
def __call__(self, path, params, body=None, headers={}):
full_url = urlparse.urljoin(self.api_root, path)
... | python |
import numpy as np
from sympy.solvers import solve
from sympy import Symbol
from scipy.interpolate import interp1d
from scipy.integrate import trapz
def steel_specific_heat_carbon_steel(temperature):
"""
DESCRIPTION:
[BS EN 1993-1-2:2005, 3.4.1.2]
Calculate steel specific heat acco... | python |
# Copyright 2015 Janos Czentye <czentye@tmit.bme.hu>
#
# 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 a... | python |
import numpy as np
import math
from domains.environment import Environment
import copy
class SimpleEnv(Environment):
def __init__(self, branch, solution_path, printp=False):
self._branch = branch # branching factor
self._solution_path = solution_path # path to unique solution
self._path ... | python |
import alphanum
def test_no_string_length():
foo = alphanum.generate()
assert len(foo) == 1
def test_with_string_length():
foo = alphanum.generate(10)
assert len(foo) == 10
def test_subsequent_strings_differ():
foo = alphanum.generate(10)
bar = alphanum.generate(10)
assert foo != bar
| python |
from tkinter import*
janela = Tk()
janela.title('contagem')
janela['bg']='Black'
segundos = None
#dimisões da janela
largura = 230
altura = 250
#resolução do sistema
largura_screen = janela.winfo_screenwidth()
altura_screen = janela.winfo_screenheight()
#posição da janela
posX = largura_screen/2 - largura/2
posY... | python |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXX XXXX XXXXX XXXXXX XXXX XXXX X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXX XXXXXXXX XXXXXX XXXXX XXXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXX XXXX XXXX
XXXXX XXXXX X XXXXXX XXXXXXXX XXXXXXXXXXXX XXX XXXXX XXX XXX X XXXXXXXXXX XXX
XX XXXXXX
XXXXX XXXX XXX XXXX XXXXXXXXX XX XXX XXXX... | python |
from discord import Game, Member, TextChannel, CategoryChannel, PermissionOverwrite, Message, Status, ActivityType
from random import randint
from ..bunkbot import BunkBot
from ..channel.channel_service import ChannelService
from ..core.bunk_user import BunkUser
from ..core.daemon import DaemonHelper
from ..cor... | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import logging
import torch
import torch.nn as nn
from ..interface import BaseOperator
'''
This file contains the torch implementation of operators
'''
#---------------------- convolution layer ----------------------#
class Conv(BaseOperator):... | python |
from django.db.models import Sum, Q
from drf_writable_nested import WritableNestedModelSerializer
from rest_framework import serializers
from api.serializers.submissions import SubmissionLeaderBoardSerializer
from competitions.models import Submission, Phase
from leaderboards.models import Leaderboard, Column
from .f... | python |
from ravendb.infrastructure.entities import User
from ravendb.tests.test_base import TestBase
class LoadTest(TestBase):
def setUp(self):
super(LoadTest, self).setUp()
def test_load_document_and_expect_null_user(self):
with self.store.open_session() as session:
null_id = None
... | python |
import subprocess
import sys
import time
if len(sys.argv) < 5:
raise "Must input u_size, v_size, dataset, models to train"
#subprocess.run("source ~/env/bin/activate", shell=True)
u_size = int(sys.argv[3])
v_size = int(sys.argv[4])
dataset = sys.argv[2]
model = sys.argv[5]
n_encoding_layers = sys.argv[-2]
proble... | python |
#!/usr/bin/env python
from concurrent.futures import ThreadPoolExecutor
from optparse import OptionParser
from collections import OrderedDict
import os
import sys
import json
import urllib3
import urllib3.contrib.pyopenssl
import xmltodict
import traceback
import certifi
prog = os.path.basename(__file__)
base_dir = o... | python |
#!/usr/bin/env python
################################ Import modules ################################
import argparse
import msprime
import allel
import numpy as np
import pandas as pd
############################### Define functions ###############################
def read_args():
'''
This function parses ... | python |
# Location of the self-harm annotation file.
LABEL_FILE = "gold-transcripts/self-harm-annotations.txt"
# Location of gold TXT with the hash filename.
TXT_DIR = "gold-transcripts/gold-final_2019-04-08_anno"
# Location of the word-level GT.json and pred.json files.
JASA_DIR = "jasa_format/v7s"
# Output directory to st... | python |
from setuptools import setup
setup(
name="PyStructPro",
version="1.0",
description="A small project used to generate directory skeleton for personal projects",
url="https://github.com/roberttk01/pystructpro.git",
author="Thomas Kyle Robertson",
author_email="roberttk01@gmail.com",
license="... | python |
#!/usr/bin/env python
import unittest
from spdown.spotify import Spotify
class TestSpotifyExtraction(unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main()
| python |
# import functools
import bcrypt
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from pymongo import MongoClient
# print = functools.partial(print, flush=True)
app = Flask(__name__)
api = Api(app)
client = MongoClient("mongodb://my_db:27017")
db = client.projectDB
users = db["Users"... | python |
class bidict(dict):
"""
Implementation of bidirectional dictionary.
This kind of dictionary stores {key: key} pair.
The main idea is to access each key using sibling key.
Current implementation stores 1 pair of key-value in self dictionary,
like a regular dict, but it is possible to obtain key ... | python |
# coding=utf-8
"""
In the card game poker, a hand consists of five cards and are ranked, from
lowest to highest, in the following way:
High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are consecutiv... | python |
from django.apps import AppConfig
class ForumEngineConfig(AppConfig):
name = 'forum_engine'
| python |
if True:
s = "<selection>foo</selection>"
| python |
import gym, argparse
import numpy as np
import itertools
import tensorflow as tf
from tf_rl.common.utils import AnnealingSchedule, eager_setup
from tf_rl.common.filters import Particle_Filter
from tf_rl.common.wrappers import MyWrapper_revertable
eager_setup()
class Model(tf.keras.Model):
def __init__(self, num_... | python |
from runner.run_description import RunDescription, Experiment, ParamGrid
_params = ParamGrid([])
_experiments = [
Experiment(
'battle_fs4_pbt',
'python -m algorithms.appo.train_appo --env=doom_battle --train_for_env_steps=300000000000 --algo=APPO --env_frameskip=4 --use_rnn=True --ppo_epochs=1 --r... | python |
## ---------------------------------------------------------------------------
## Abstract syntax tree YAML tools.
## ---------------------------------------------------------------------------
import string, re, sys, yaml, tools
from tools import warning, error
def decl (type, name):
"Return the concatenation of ... | python |
"""
Compares spectrogram computations with TensorFlow and Vesper.
As of 2018-11-09, Vesper is a little more than three times faster than
TensorFlow at computing spectrograms with a DFT size of 128.
"""
import functools
import time
import numpy as np
import tensorflow as tf
import vesper.util.data_windows as data_w... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
import sys
import time
import urllib
import os.path
from struct import pack
from sklearn import preprocessing
import numpy as np
import pandas as pd
import fact.io
import progressbar
N = 200000
factLevel2URL = "https://factdata.app.tu-dortmund.de... | python |
def treemap(
df,
fig_filepath,
scale=1.5,
columns=None,
treemap=None,
layout=None,
update_layout=None,
**kwargs,
):
# textinfo = "label+value+percent parent+percent root"
# import plotly.express as px
import plotly.graph_objects as go
labels = list(df[columns.label].to_l... | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | python |
# -*- coding: utf-8 -*-
#
# This file is part of reana.
# Copyright (C) 2019 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Reana workflow factory helper functions."""
import json
import logging
import os
import s... | python |
import sys
sys.path.append("../../")
from appJar import gui
def fDeleteRow(dRow): app.deleteTableRow("entryTable", dRow)
def fAddRow(): app.addTableRow("entryTable", app.getTableEntries('entryTable'))
with gui() as app:
app.addTable("entryTable", [["Item", "Description"]], action=fDeleteRow, addRow=fAddRow, acti... | python |
import requests
import time
import json
import threading
import queue
import yaml
from sqlalchemy import create_engine
from sqlalchemy.types import BigInteger, Integer
import pandas as pd
def split_list(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def worker_get_owned_games(lst_user_id, api_key,... | python |
from dataclasses import dataclass
from infrastructure.cqrs.ICommand import ICommand
@dataclass
class DeleteJobRequest(ICommand):
Id: int = None
| python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2019-07-25 19:52
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('commands', '0001_add-js-commands'),
]
operations = [
migrations.RunSQL([
... | python |
# -*- coding: utf-8 -*-
"""Top-level package for Pull Webhook."""
__author__ = """Dario Iacampo"""
__email__ = 'dario@jntstudio.net'
__version__ = '0.1.7'
from .pull_webhook import Puller
from .pull_webhook import main
__all__ = [Puller, main]
| python |
from tests import base
from tests import factories as f
outbox_len = 0
password = '123123'
def test_workshop_create(base_url, browser, outbox):
"""
"""
f.create_usertype(slug='tutor', display_name='tutor')
poc_type = f.create_usertype(slug='poc', display_name='poc')
state = f.create_state()
u... | python |
from pydantic import BaseModel
class ThingWithId(BaseModel):
id: str
@property
def isNone(self):
return self.id == "none"
@classmethod
def create_none(cls):
return cls(id="none")
| python |
from IPython.display import display, HTML
import numpy as np
import seaborn as sns
def display_html(html: str):
display(HTML(html))
def get_color_palette(prepend_neutral_color:bool=False):
colors = sns.color_palette('Set1')
if prepend_neutral_color:
colors = colors[-1:] + colors[:-1]
return ... | python |
# Copyright 2009-2015 MongoDB, 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 writin... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.