content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from .base import *
DEBUG = False
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'dist/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-prod.json'),
}
} | python |
from src.pybitbucket.bitbucket import Bitbucket
config = {
"secret-properties": "secretproperties.properties",
"properties": "properties.properties"}
bb = Bitbucket(settings=config)
# workspace = bb.workspace
prs_df = bb.df_prs
commits_df = bb.df_commits
prs_list = prs_df["pr_id"].unique().tolist().sort()
pr... | python |
#!/usr/bin/env python
'''
Tiger
'''
import json
import os
import subprocess
from collections import OrderedDict
from tasks.util import (LoadPostgresFromURL, classpath, TempTableTask, grouper,
shell, TableTask, ColumnsTask, TagsTask,
Carto2TempTableTask)
from tasks.meta ... | python |
from collections import OrderedDict
from algorithms.RNN import RNNModel
from algorithms.AR import AutoRegressive
from algorithms.LSTM import LSTMModel
from algorithms import LSTNet, Optim
import torch
p = 5
def get_models_optimizers(node_list, algs, cuda, lr, hidden_dim, layer_dim, nonlinearity, Data):
models, q... | python |
#!/usr/bin/env python3
import logging
import sys
from .ToolChainExplorer import ToolChainExplorer
class ToolChainExplorerDFS(ToolChainExplorer):
def __init__(
self,
simgr,
max_length,
exp_dir,
nameFileShort,
worker,
):
super(ToolChainExplorerDFS, self)._... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: signer.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from googl... | python |
import sym.models
import sym.trainer
import sym.datasets
import sym.config
| python |
#!/usr/bin/python
#
# Copyright (C) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# SPDX-License-Identifier: GPL-2.0+
#
import os
import struct
import sys
import tempfile
import command
import tools
def fdt32_to_cpu(val):
"""Convert a device tree cell to an integer
Args:
Value ... | python |
import inspect
import typing
try:
from contextlib import (
AsyncExitStack,
asynccontextmanager,
AbstractAsyncContextManager,
)
except ImportError: # pragma: no cover
AbstractAsyncContextManager = None # type: ignore
from async_generator import asynccontextmanager # type: igno... | python |
from oeis import phi
def test_phi():
assert [phi(x) for x in range (1, 10)] == [1, 1, 2, 2, 4, 2, 6, 4, 6] | python |
from datetime import datetime
import json
import glob
import os
from pathlib import Path
from multiprocessing.pool import ThreadPool
from typing import Dict
import numpy as np
import pandas as pd
from scipy.stats.mstats import gmean
import torch
from torch import nn
from torch.utils.data import DataLoader
ON_KAGGLE:... | python |
# Copyright (c) 2014-present PlatformIO <contact@platformio.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 appli... | python |
from ebonite.core.objects.requirements import InstallableRequirement, Requirements, resolve_requirements
def test_resolve_requirements_arg():
requirements = Requirements([InstallableRequirement('dumb', '0.4.1'), InstallableRequirement('art', '4.0')])
actual_reqs = resolve_requirements(requirements)
assert... | python |
"""
==================
Find ECG artifacts
==================
Locate QRS component of ECG.
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#
# License: BSD (3-clause)
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne import io
from mne.datasets import sample
print(_... | python |
# -*- coding: utf-8 -*-
import pytest
from unittest import mock
from pytube import YouTube
from pytube.exceptions import LiveStreamError
from pytube.exceptions import RecordingUnavailable
from pytube.exceptions import RegexMatchError
from pytube.exceptions import VideoUnavailable
from pytube.exceptions import VideoPri... | python |
import sys
import numpy as np
raw = sys.stdin.read()
locs = np.fromstring(raw, dtype=np.int64, sep=',')
average = np.average(locs)
def forLocation(locs, dest):
absolute = np.abs(locs - dest)
return ((absolute + 1) * absolute // 2).sum()
print('Result:', min(
forLocation(locs, int(np.ceil(average))),
... | python |
from pycantonese import stop_words
_DEFAULT_STOP_WORDS = stop_words()
def test_stop_words():
_stop_words = stop_words()
assert "唔" in _stop_words
def test_stop_words_add_one_word():
_stop_words = stop_words(add="foobar")
assert "foobar" in _stop_words
assert len(_stop_words) - len(_DEFAULT_STO... | python |
#!/usr/bin/env python
from __future__ import print_function
import roslib
import rospy
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import sys
# sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
import cv2 as cv
print(... | python |
import numpy as np
from whole_body_mpc_msgs.msg import StateFeedbackGain
import copy
class StateFeedbackGainInterface():
def __init__(self, nx, nu, frame_id="world"):
self._msg = StateFeedbackGain()
self._msg.header.frame_id = frame_id
self._msg.nx = nx
self._msg.nu = nu
se... | python |
""" This script runs every 10 seconds and assigns users to a new batch of tasks filtered by the specified column.
Notes:
1. Don't forget to enable Manual mode in Annotation settings
2. Be careful when adding email users: users who are not members of the project or workspace will break Data Manager
Install:
... | python |
import time
import requests
from requests.exceptions import HTTPError, Timeout
from bs4 import BeautifulSoup
from core.log_manager import logger
class Updates:
MAX_LENGTH = 25 # Maximum amount of numbers that a version can support
TIME_INTERVAL = 48 # In hours
def __init__(self, link, loca... | python |
import numpy
from typing import List
from skipi.function import Function
class AverageFunction(Function):
@classmethod
def from_functions(cls, functions: List[Function], domain=None):
r"""
Returns the average function based on the functions given as a list F = [f_1, ..., f_n]
::math.... | python |
import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup
from phyllo.phyllo_logger import logger
def getBooks(soup):
siteURL = 'http://www.thelatinlibrary.com'
textsURL = []
# get links to books in the collection
for a in soup.find_all('a', href=True):
... | python |
import scipy.integrate as scin
import numpy as np
import matplotlib.pyplot as pl
g=9.80665
Cd=0.2028
m=80
ics = ([0,0])
t = np.linspace(0,100,500) #creates an array t, integration range from 0 and inclusive of 100 since its linspace, increment of 500
def deriv(x,t):
F = np.zeros(2) #creates an array F, with length ... | python |
# -*- coding: utf-8 -*-
"""
wakatime.projects.projectmap
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use the ~/.wakatime.cfg file to set custom project names by
recursively matching folder paths.
Project maps go under the [projectmap] config section.
For example:
[projectmap]
/home/user/proj... | python |
__all__ = ['features','graph_layers'] | python |
# Author: Steven C. Dang
# Class for most common operations with TA2
import logging
import grpc
from os import path
from google.protobuf.json_format import MessageToJson
import pandas as pd
# D3M TA2 API imports
from .api_v3 import core_pb2, core_pb2_grpc
from .api_v3 import value_pb2
from .api_v3 import problem_pb... | python |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import MySQLdb
import requests
from lxml import etree,html
import re
from datetime import date,datetime
from time import sleep, time
import simplejson
import concurrent.futures
from concurrent.futures import ProcessPoolExecutor, as_completed
from tqdm import tqdm
from seleniu... | python |
import numpy as np
from math import radians
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
def wind_rose(df, wd, nbins=16, xticks=8, plot=111, wind=True, ylim=False, yaxis=False, yticks=False):
"""
Return a wind rose.
Parameters
----------
df : DataFrame
The pandas Dat... | python |
import pytest
import pystiche_papers.johnson_alahi_li_2016 as paper
@pytest.fixture(scope="package")
def styles():
return (
"composition_vii",
"feathers",
"la_muse",
"mosaic",
"starry_night",
"the_scream",
"udnie",
"the_wave",
)
@pytest.fixtur... | python |
a = "Paul Sinatra"
print(a.count("a"))
print(a.count("a",0,10))
print(a.endswith("tra"))
print(a.endswith("ul",1,8))
print(a.find("a"))
print(a.find("a",2,10))
print(len(a))
print(a.lower())
print(max(a))
print(min(a))
print(a.replace("a","b"))
print(a.split(" "))
print(a.strip())
print(a.upper()) | python |
"""Token constants."""
# Auto-generated by Tools/scripts/generate_token.py
__all__ = ['tok_name', 'ISTERMINAL', 'ISNONTERMINAL', 'ISEOF']
ENDMARKER = 0
NAME = 1
NUMBER = 2
STRING = 3
NEWLINE = 4
INDENT = 5
DEDENT = 6
LPAR = 7
RPAR = 8
LSQB = 9
RSQB = 10
COLON = 11
COMMA = 12
SEMI = 13
PLUS = 14
MINUS = 15
STAR = 16
S... | python |
from django.contrib.auth.models import User
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.renderers import DocumentationRen... | python |
from __future__ import print_function
import os
import sys
import curses
import txtsh.log as log
class Cursor(object):
def __init__(self):
self.y = 4
self.x = 0
self.up_limit = 4
self.down_limit = 4
def display(self):
curses.setsyx(self.y, self.x)
curses.do... | python |
#!/usr/bin/pypy
from sys import *
from random import *
T, n, p, K0 = map(int, argv[1:]);
print T
for i in xrange(T):
E = []
mark = []
for i in xrange(2, n * p / 100 + 1):
E.append((randint(1, i - 1), i))
mark.append(0)
for i in xrange(n * p / 100 + 1, n + 1):
j = randrange(0, ... | python |
"""
devl.py -- The more cross-platform makefile substitute with setup tools
Usage
=====
For first-time setup of this file, type 'python devl.py'
How to Add Functionality
========================
User Variables
--------------
To add a new user variable, you should
- Update the ``user_variables`` dict in this modul... | python |
# Copyright 2021 Ash Hellwig <ash@ashwigltd.com> (https://ash.ashwigltd.com)
#
# 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... | python |
"""Init module."""
from . import contypes, exceptions, models, repository, service
from .controller import controller
__all__ = [
"controller",
"contypes",
"exceptions",
"models",
"repository",
"service",
]
| python |
import argparse
def str2bool(v):
return v.lower() in ("yes", "y", "true", "t", "1")
parser = argparse.ArgumentParser(description="test global argument parser")
# script parameters
parser.add_argument('-g', '--GT_PATH', default='gt/gt.zip', help="Path of the Ground Truth file.")
parser.add_argument('-s',... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dagrun_operator import TriggerDagRunOperator
default_args = {'owner': 'afroot05', 'retries': 2, 'retry_delay': timedelta(minutes... | python |
from pointing.envs import SimplePointingTask
from pointing.users import CarefulPointer
from pointing.assistants import ConstantCDGain, BIGGain
from coopihc.bundle import PlayNone, PlayAssistant
import matplotlib.pyplot as plt
# ===================== First example =====================
# task = SimplePointingTask(gr... | python |
from os.path import join
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import argparse
from repro_lap_reg.load_param_seq_results import load_param_seq_results
from repro_lap_reg.viz_seq import plot_param_vs_metric_by_model
from repro_lap_reg.viz_utils import savefig
from repro_lap_reg.util... | python |
from collections import Counter
from dataclasses import dataclass
from itertools import zip_longest
@dataclass
class Point:
x: int
y: int
def __hash__(self):
return hash((self.x, self.y))
@dataclass
class Segment:
a: Point
b: Point
def orthogonal(self):
return self.a.x == self.b.x or self.a.y ==... | python |
# Config
# If you know what your doing, feel free to edit the code.
# Bot Token
# Token of the Bot which you want to use.
TOKEN = ""
# Log File
# Where all the logs of everything are stored.
# Default: "logs.txt"
LOG_FILE = "logs.txt"
# File where the codes are stored.
# Codes are given out by lines, so... | python |
import discord
from discord.ext import commands
class ListMyGames(commands.Cog):
def __init__(self, client):
self.client = client
self.db = self.client.firestoreDb
@commands.command(brief="Lists games you have already acquired")
async def listmygames(self, ctx):
await ctx.author.s... | python |
# Validating phone numbers
# Problem Link: https://www.hackerrank.com/challenges/validating-the-phone-number/problem
import re
for _ in range(int(input())):
print("YES" if re.match("^[789]\d{9}$", input()) else "NO")
| python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB
names=['AGE','TB','DB','TP','Albumin','A/G','sgpt','sgot','ALKPHOS','GENDER']
dataset=pd.read_csv("Indian Liver ... | python |
"""
taskcat python module
"""
from ._cfn.stack import Stack # noqa: F401
from ._cfn.template import Template # noqa: F401
from ._cli import main # noqa: F401
from ._config import Config # noqa: F401
__all__ = ["Stack", "Template", "Config", "main"]
| python |
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory
#
# 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 ... | python |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-emailuser',
version='0.0.1',
packages=['... | python |
"""Top-level package for explainy."""
__author__ = """Mauro Luzzatto"""
__email__ = "mauroluzzatto@hotmail.com"
__version__ = '0.1.14'
| python |
__version__ = "0.0.1"
__required_biorbd_min_version__ = "1.2.8"
| python |
# Import library
import sys
import rohub
import os
sys.path.insert(0, os.path.join(os.getcwd(), 'misc', 'rohub'))
import config
# Authenticate
rohub.login(username=config.username, password=config.password)
# metadata
metadata_contribution = {
'environment': 'agriculture',
'topic': 'exploration',
'filenam... | python |
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
"""Very simple inter-object notification s... | python |
import os
import pathlib
import shutil
from typing import List
from gaas.applications.image_coloring.config import \
ANIME_SKETCH_COLORIZATION_DATASET_DATASET_ID
from gaas.applications.image_coloring.dataset import \
AnimeSketchColorizationDatasetGenerator
from gaas.applications.image_coloring.utils.locations ... | python |
from . import extract | python |
from typing import Dict, Any
from typing import Tuple
class DataBuffer:
"""
Databuffer with rollover
"""
def __init__(self, cols, size):
self.size = size
self.entries = [None for i in range(size)]
self.counter = 0
self.cols = cols
self.col_to_idx = {c: idx for... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-18 18:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0025_auto_20190217_2026'),
]
operations = [
migrations.AddFiel... | python |
__all__ = ["battleground", "bridge", "forest", "mountains", "store"]
| python |
################################################################################
# Peach - Computational Intelligence for Python
# Jose Alexandre Nalon
#
# This file: fuzzy/control.py
# Fuzzy based controllers, or fuzzy inference systems
################################################################################
... | python |
import this # => display the Zen of Py
# 1. Any python file can be imported as module
# to load from another module:
import sys
sys.path += ["path_to_folder"] # and import MyModule
if __name__ == "__main__":
pass # this code will exec only if the script is ran. if loaded as module, it will not run
# PACKAGES
# ... | python |
import math
import itertools
import functools
import multiprocessing
import asyncio
import uuid
import numpy as np
import pymatgen as pmg
import lammps
from lammps.potential import (
write_table_pair_potential,
write_tersoff_potential,
write_stillinger_weber_potential,
write_gao_weber_potential,
w... | python |
# Generated by Django 2.0.5 on 2018-09-11 16:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("barriers", "0007_auto_20180905_1553")]
operations = [
migrations.RemoveField(model_name="barrierstatus", name="barrier"),
migrations.RemoveField(model_na... | python |
### extends 'class_empty.py'
### block ClassImports
# NOTICE: Do not edit anything here, it is generated code
from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
### endblock ClassImports
### block Header
# NOTICE: The code generator will not replace the code in this block
### end... | python |
from contextlib import nullcontext as expectation_of_no_exceptions_raised
import pytest
from _config.combo.cookie_banner import JYLLANDSPOSTEN_ACCEPT_COOKIES
from _config.combo.log_in import (AMAZON_LOGIN_CREDENTIALS, AMAZON_LOGIN_FORM, JYLLANDSPOSTEN_LOGIN_CREDENTIALS,
JYLLANDSPOSTEN... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import copy
import solutions.utils as utils
class CoProcessor:
def __init__(self, debug=True):
self._registers = {c: 0 for c in 'abcdefgh'}
self._pc = 0
self._mul_counter = 0
self._debug = debug
self._states = set()
... | python |
"""
Object Co-segmentation Datasets
author - Sayan Goswami
email - sayan.goswami.106@gmail.com
"""
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
from torchvision.datasets import ImageFolder, DatasetFolder
from torchvision.transforms import ToTensor
class DatasetABC(Dataset):
""... | python |
""" This simulation is adapted from main for Bayesian inference analysis """
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
import plotter
import network
import os
import pickle
import numpy as np
# %%markdown
#
# %%
# do not use spatial convolution (set kernels supe small)
no_spatial_conv = Tru... | python |
"""
Core functions.
"""
import numpy as np
import warnings
from scipy.optimize import brentq, fsolve
from scipy.stats import ttest_ind, ttest_1samp
from fractions import Fraction
from .utils import get_prng, potential_outcomes, permute
def corr(x, y, alternative='greater', reps=10**4, seed=None, plus1=True):
r... | python |
"""ETS Prediction View"""
__docformat__ = "numpy"
import datetime
import os
import warnings
from typing import Union
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd
from pandas.plotting import register_matplotlib_converters
from gamestonk_terminal import feat... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of pyunicorn.
# Copyright (C) 2008--2019 Jonathan F. Donges and pyunicorn authors
# URL: <http://www.pik-potsdam.de/members/donges/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results a... | python |
class AppriseNotificationFailure(Exception):
# Apprise returns false if something goes wrong
# they do not have Exception objects, so we're creating a catch all here
pass
| python |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2019 Lorenzo
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, ... | python |
# 文字列
import keyword
from importlib import import_module
import re
import string
'''
[文字列モジュール|string[|モジュール]]をインポートする
@prefix(sub;部分文字列)
@alt(先頭|最初|左[側|端])
@alt(末尾|最後|後ろ|右[側|端])
@alt(左側|左)
@alt(右側|右)
'''
string = import_module('string')
keyword = import_module('keyword')
s = 'ABC abc 123' # 文字列 s, s2, s3
s2 = 'a... | python |
""" Functions for running the PEPR model defined in the
--Univeral visitation law of human mobility-- paper
(https://www.nature.com/articles/s41586-021-03480-9).
"""
import random
import time
import itertools as it
import matplotlib.pyplot as plt
import numpy as np
def levy_flight(num_steps: int,... | python |
# -*- coding: utf-8 -*-
from authomatic import providers
class MozillaPersona(providers.AuthenticationProvider):
pass
| python |
import requests
from kong.api import API
class Connection:
def __init__(self, url='http://localhost:8001'):
self.url = url
def _get(self, path='', **request_args):
return requests.get(self.url + path, **request_args)
def _post(self, path='', **request_args):
return requests.pos... | python |
from discoPy.rest.base_request.base_request import BaseRequestAPI
class StageData(BaseRequestAPI):
'''Contains a collection of stage related methods.'''
def __init__(self, token: str, url: str=None):
super().__init__(token, url)
def create_stage_instance(self, channel_id, topic: str, privacy_leve... | python |
#!/usr/bin/env python3
# Python fizzbuzz implementation
for num in range(1, 25):
#check if number is divisible by both 3 and 5
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
#check if number divisible by 3
elif num % 3 == 0:
print("Fizz")
# check if number is divisible... | python |
import re
from dataclasses import dataclass
from typing import List, Tuple, Optional
import attr
from new.data_aggregation.utils import MethodSignature
@dataclass(frozen=True)
class Scope:
name: Optional[str] = None # attr.attrib()
bounds: Optional[Tuple[int, int]] = None # attr.attrib()
type: Optiona... | python |
# test function dot
def projCappedSimplex():
import numpy as np
from limetr.utils import projCappedSimplex
ok = True
# setup test problem
# -------------------------------------------------------------------------
w = np.ones(10)
sum_w = 9.0
tr_w = np.repeat(0.9, 10)
my_w = projC... | python |
# Author: Mikita Sazanovich
import argparse
import itertools
import os
import sys
import numpy as np
import tensorflow as tf
sys.path.append('../')
from deepq import StatePotentialRewardShaper, Estimator, StatePreprocessor, PrioritizedReplayBuffer
from deepq import get_last_episode
from dotaenv import DotaEnvironme... | python |
from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.util import Inches
class Present():
def test_pptx(self):
# create presentation with 1 slide ------
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_lay... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 25 13:08:47 2019
@author: Mario
"""
import subprocess, sys
if __name__ == "__main__":
#########################################
###### DISTRIBUTED COMPUTING SETUP ######
#########################################
rescanNetwork = True
if rescanNet... | python |
import argparse
import configparser
import json
import os
import sys
import time
import requests
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from util import logger
class ConversationScraper:
"""Scraper that retrieves, process and stores all messages belonging to a specific Facebook conversat... | python |
import sys
import timeit
import zmq
from kombu import Connection
from timer import Timer
TOTAL_MESSAGES = int(sys.argv[1])
amqp_timer = Timer()
zmq_timer = Timer()
def log(msg):
pass
# print(msg)
def main():
context = zmq.Context()
sockets = {}
with Connection("amqp://guest:guest@127.0.0.1:... | python |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
# import psycopg2
# import os
# import csv
# class PostgreSQL:
# def __init__(self, host, port, username, password, database):
# self.host = host
# self.port = port
# self.username = username
# self.password = password
# self.database = database
# se... | python |
from __future__ import print_function, absolute_import
import numpy as np
import torch
from torch.utils.data import Dataset
from functools import reduce
#####################################
# data loader with four output
#####################################
class PoseDataSet(Dataset):
def __init__(self, poses_... | python |
import os
import pandas as pd
from base import BaseFeature
from google.cloud import storage, bigquery
from google.cloud import bigquery_storage_v1beta1
from encoding_func import target_encoding
class TargetEncodingResponseTimeDiff(BaseFeature):
def import_columns(self):
return [
"1"
]
... | python |
import numpy as np
from math import pi
'''
Class to calculate the inverse kinematics for the stewart platform.
Needs pose and twist input to calculate leg length and velocity
All length-units is written in meters [m]
'''
class InverseKinematics(object):
def __init__(self):
# minimum po... | python |
import torch.nn as nn
from typing import Optional, Union, List
from .model_config import MODEL_CONFIG
from .decoder.deeplabv3plus import DeepLabV3PlusDecoder
from .get_encoder import build_encoder
from .base_model import SegmentationModel
from .lib import SynchronizedBatchNorm2d
BatchNorm2d = SynchronizedBatchNorm2d
... | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import argparse
def load():
"""
Description
Returns
Arguments object.
"""
parser = argparse.ArgumentParser(description="Program description",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
... | python |
from .model import Model
class Datacenters(Model):
pass
| python |
import threading
import typing as tp
from contextlib import contextmanager
from dataclasses import dataclass
from treex import types
@dataclass
class _Context(threading.local):
call_info: tp.Optional[tp.Dict["Module", tp.Tuple[types.Inputs, tp.Any]]] = None
def __enter__(self):
global _CONTEXT
... | python |
"""empty message
Revision ID: b1f6e283b530
Revises:
Create Date: 2021-06-15 12:34:40.497836
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b1f6e283b530'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | python |
from pymatgen.electronic_structure.core import Spin, Orbital
from pymatgen.io.vasp.outputs import BSVasprun, Eigenval
from pymatgen.io.vasp.inputs import Kpoints, Poscar, Incar
from pymatgen.symmetry.bandstructure import HighSymmKpath
from vaspvis.unfold import unfold, make_kpath, removeDuplicateKpoints
from pymatgen.c... | python |
#!/usr/bin/env python
# mainly taken from https://github.com/rochaporto/collectd-openstack
import collectd
import datetime
import traceback
class Base(object):
def __init__(self):
self.username = 'admin'
self.password = 'admin'
self.verbose = False
self.debug = False
self.... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
import tensorflow as tf
import cv2
from utils.misc import get_center
Rectangle = collections.namedtuple('Rectangle', ['x', 'y', 'width', 'height'])
def get_gauss_filter... | python |
import matplotlib.pyplot as plt
import numpy as np
import wave
import sys
import statistics
########################################
# INPUT PARAMETER #
########################################
bpm = 136
offsetms = 0 # offset for beat grid in ms. Moves the beat grid to the right and is used to al... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.