content stringlengths 5 1.05M |
|---|
from gclang.gen.GuardedParser import GuardedParser
from gclang.gen.GuardedVisitor import GuardedVisitor
from dataclasses import InitVar, dataclass
@dataclass
class MacroOperator:
name: str
parameters: tuple[str]
body: GuardedParser.OperatorListContext
@dataclass
class MacroExpression:
name: str
pa... |
import re
from thefuck.utils import for_app
@for_app('heroku')
def match(command):
return 'Run heroku _ to run' in command.stderr
def get_new_command(command):
return re.findall('Run heroku _ to run ([^.]*)', command.stderr)[0]
|
import json
import torch
from base.base_dataset import BaseADDataset
from networks.main import build_network
from optim import ClassifierTrainer
class Classifier(object):
"""A class for an anomaly detection classifier model.
Attributes:
objective: Hypersphere ('hsc'), binary cross-entropy ('bce'), o... |
#
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import unittest
from check_seventeen import check_seventeen_
class TestCheckSeventeen(unittest.TestCase):
def test_obvious(self):
y = 0
while y < 25000:
#if there is no remainder after division
if y % 17 == 0:
#it is divisible by ___ and should be rejected
... |
"""A histoprogramming utility to go from some input lines to something plottable.
Licensed under the 3-clause BSD License:
Copyright (c) 2011-2014, Neeraj Kumar (neerajkumar.org)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the foll... |
# -*- coding: utf-8 -*-
'''
Created by 15 cm on 11/22/15 6:33 PM
Copyright © 2015 15cm. All rights reserved.
'''
__author__ = '15cm'
from data.data_handler import DataHandler
from feature.superpixel import SuperPixel
from mynp import np
import os
CURPATH = os.path.split(os.path.realpath(__file__))[0]
class Bow:
... |
"""Script for running Pokemon Simulation."""
from threading import Thread
from queue import Queue
from time import time
from agent.basic_pokemon_agent import PokemonAgent
from agent.basic_planning_pokemon_agent import BasicPlanningPokemonAgent
from battle_engine.pokemon_engine import PokemonEngine
from file_manager.l... |
from .category import Category
class Insect(Category):
_name = "insect"
_values = [
"ant",
"bee",
"beetle",
"butterfly",
"cicada",
"cockroach",
"cricket",
"dragonfly",
"earwig",
"firefly",
"fly",
"grasshopper",
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .config_source import ConfigResult, ConfigSource, ObjectType
from .errors import ConfigLoadError
__all__ = [
"ConfigSource",
"ConfigLoadError",
"ObjectType",
"ConfigResult",
]
|
#!/usr/bin/env python3
# Copyright 2020 Red Hat
#
# 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 ... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 tianyou pan <sherry0429 at SOAPython>
"""
import falcon
class BaseFalcon(object):
OK = falcon.HTTP_200
ERROR = falcon.HTTP_404
|
import socket
from .task import Task
from . import helpers
from .app_settings import TASKS_HOST,TASKS_PORT
def push_task_to_queue(a_callable,*args,**kwargs):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_task = Task(a_callable,*args,**kwargs)
new_task = helpers.save_task_to_db(new_... |
# Copyright 2018 Novo Nordisk Foundation Center for Biosustainability, DTU.
#
# 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 requir... |
# -*- coding: utf-8 -*-
from flask_restx._http import HTTPStatus as flaskplus_HTTPStatus
HTTPStatus = flaskplus_HTTPStatus
|
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import torch.nn as nn
def plot_filters_single_channel_big(t, place_to_store):
# setting the rows and columns
nrows = t.shape[0] * t.shape[2]
ncols = t.shape[1] * t.shape[3]
npimg = np.array(t.numpy(), np.float32)
npimg = npi... |
# -*- coding: utf-8 -*-
import json
import os
import sys
import time
from datetime import datetime, timedelta
from config import checkin_map, get_checkin_info, get_notice_info, env2config
from motto import Motto
from utils.message import push_message
def main_handler(event, context):
start_time = time.time()
... |
__author__ = 'HaoBin'
class Logger(object):
def __init__(self, filename="output.txt"):
self.terminal = sys.stdout
filename = "permute_output_" + str(time.time()) + ".txt"
self.log = open(filename, "w")
def write(self, message):
self.terminal.write(message)
self.log.writ... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
"""
Contains Canvas DAO implementations.
"""
from restclients_core.dao import DAO, LiveDAO
from commonconf import settings
from urllib3 import PoolManager
from urllib3.util.retry import Retry
from os.path import abspath, dirname
imp... |
# coding: utf-8
from findaconf import manager
manager.run()
|
from PiControl.models import Pin, Schedule
import rollbar
import sys
import RPi.GPIO as RPIO
class PinController(object):
def __init__(self):
RPIO.setmode(RPIO.BCM)
self.my_pins = None
self.set_all_pins()
def get_thermometers(self):
return self.my_pins.filter(is_thermometer=Tr... |
import json
def normalization(artwork):
if artwork:
artwork['artist'] = artwork['artist'].replace("Attributed to Goya (Francisco de Goya y Lucientes)", "Francisco Goya")
artwork['artist'] = artwork['artist'].replace("Goya (Francisco de Goya y Lucientes)", "Francisco Goya")
artwork['artist'] ... |
class Solution:
def solve(self, s):
num = ''
ans = 0
import string
letters = string.ascii_letters
for i in s:
if i not in letters:
num += i
else:
print(num)
if num:
ans += int(num)... |
# 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 ... |
def min2Broja(a, b):
if a < b:
return a
else:
return b
def min3Broja(a, b, c):
return min2Broja(min2Broja(a, b), c)
prviBroj = float(input("Unesite 1. broj: "))
drugiBroj = float(input("Unesite 2. broj: "))
treciBroj = float(input("Unesite 3. broj: "))
# manjiOdPrvaDva = min2Broja(prviBro... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Autocommit pg database wrapper
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# -----------------------------------------------... |
# Copyright (c) 2020, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from baskerville.features.updateable_features import UpdaterRate
from pyspark.sql import functions as F
from baskerville.fea... |
import data
import matplotlib.pyplot as plt
import numpy as np
import datetime
def time_graph():
df, emails, timestamp = data.get_data()
df = timestamp.to_numpy()
s = np.arange(0, len(df))
df = np.column_stack((df, s))
for i in range(378):
temp = df[i, 0]
temp1, temp2 = temp.spl... |
from orphics.theory.cosmology import Cosmology
import orphics.tools.stats as stats
import numpy as np
import orphics.tools.io as io
from enlib import enmap
# let's define the bin edges for this test
ellmin = 2
ellmax = 4000
bin_width = 200
bin_edges = np.arange(ellmin,ellmax,bin_width)
# a typical map might be 400sq.... |
from setuptools import setup
setup(name='worin',
version='0.1.0',
description='A Korean POS Tagger using Neural Network',
author='YU Jaemyoung',
author_email='yu@mindscale.kr',
url='https://github.com/mindscale/worin',
packages=['worin'],
package_data={
'': ['*.txt',... |
#!/usr/bin/env python
# Copyright 2017 Informatics Matters 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 applicab... |
import pytest
from api_test_utils.api_test_session_config import APITestSessionConfig
from api_test_utils import poll_until, PollTimeoutError
from api_test_utils.api_session_client import APISessionClient
@pytest.fixture
def api_test_config() -> APITestSessionConfig:
yield APITestSessionConfig(base_uri="https:... |
from model import Test
from repo import TestSetsRepo
|
from server.app.tests import registration, login, shared, combined_utils, user_requ
from graphene_django.utils.testing import GraphQLTestCase
from graphql_jwt.testcases import JSONWebTokenTestCase
from django.contrib.auth import get_user_model
from copy import deepcopy
class UserRegistrationTest(GraphQLTestCase, reg... |
from django.db.models import Count, Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404, redirect
from.models import Post
from marketing.models import Signup
from.forms import CommentForm
def search(request):
queryset = Post.objects.al... |
import os
import re
from setuptools import setup
HERE = os.path.dirname(__file__)
with open(os.path.join(HERE, "src", "JupyterLibrary", "_version.py")) as fp:
version = re.findall(r"""__version__ = "([^"]+)""", fp.read())[0]
setup(version=version)
|
"""Get the code for the Travis Badge."""
from write_me.list_files import get_yml_files
from write_me.project_data import get_project_url
YAMALS = get_yml_files()
BADGE = "[](https://travis-ci.org/{0}/{1})"
COVERALLS = "[
def archive_urls():
date_start = datetime.datetime(2006, 1, 5)
date_end = datetime.dat... |
import torch
class ResidualBlock(torch.nn.Module):
"""
A single Residual Block
"""
def __init__(self, num_filts):
"""
Parameters
----------
num_filts : int
number of input and output channels/filters
"""
super().__init__()
self.bloc... |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# Create Class to create data and create batches
class TimeSeriesData():
def __init__(self, num_points, xmin, xmax): # Creating data, a sinus function
self.xmin = xmin
self.xmax = xmax
self.num_points = num_point... |
"""
Google, medium
Given k sorted singly linked lists, write a function to merge all the lists
into one sorted singly linked list.
"""
import heapq
from typing import List, Tuple
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def merge_k_lists(lists:... |
import numpy as np
import os
import csv
from collections import OrderedDict
class Hazard(object):
def __init__(self, hazard_scenario_name, scenario_hazard_data,
hazard_input_method):
self.hazard_scenario_name = hazard_scenario_name
self.scenario_hazard_data = scenario_hazard_data
... |
# https://leetcode.com/problems/longest-repeating-character-replacement/
# You are given a string s and an integer k. You can choose any character of the
# string and change it to any other uppercase English character. You can perform
# this operation at most k times.
# Return the length of the longest substring cont... |
from utils import prime_numbers
def sum_of_primes(stop: int) -> int:
return sum(prime_numbers(stop))
assert sum_of_primes(10) == 17
assert sum_of_primes(2_000_000) == 142_913_828_922
|
# coding=utf-8
__author__ = 'Anatoli Kalysch'
import pip
import sys
from os import getcwd, system, remove
from shutil import copyfile
def do(action, dependency):
return pip.main([action, dependency])
def usage():
print "Usage: python setup.py <install | uninstall>"
dependencies = ["distorm3", 'idacute']
... |
from threading import Thread,currentThread, Lock, RLock, Semaphore
import requests
import os
semaphore = Semaphore(0)
hasilperhitungan=0
class rollySemaphoreDeleteFile (Thread):
def __init__(self,name,thread_number,namafile):
Thread.__init__(self)
self.threadLock = Lock()
self.name = name
... |
# Fonte: https://leetcode.com/problems/pascals-triangle/
# Autor: Bruno Harlis
# Data: 23/08/2021
"""
PROBLEMA PROPOSTO:
Dado um inteiro numRows, retorna o primeiro numRows do triângulo de Pascal.
No triângulo de Pascal , cada número é a soma dos dois números diretamente
acima dele, conforme mostrado:
1
1 1
... |
# coding: utf-8
# ----------------------------------------------------------------------------
# <copyright company="Aspose" file="MapiContactNamePropertySetDto.py">
# Copyright (c) 2018-2020 Aspose Pty Ltd. All rights reserved.
# </copyright>
# <summary>
# Permission is hereby granted, free of charge, to an... |
from redis_dec.CacheDecorator import Cache
__title__ = 'redis_decorator'
__author__ = 'Louis Lou'
__license__ = 'Apache License 2.0'
__copyright__ = 'Copyright 2018 Qijia (Louis) Lou and Contributors'
|
#! /usr/bin/env python3
import pygame
from itertools import repeat
from math import floor, acos, pi, cos, sin, sqrt, pow
from orientation import NORTH, SOUTH, EAST, WEST
from geometry import inscribe_polygon, graphics_affines, scale_points, inscribe_angles, rotate_angles, angles_to_polygon
from random_util import rand... |
from .users import UsersViewSet |
import time
from dataclasses import dataclass
from PIL import Image, ImageDraw, ImageFont
from threading import Thread
from .screen import BaseTopNavScreen, ButtonListScreen
from ..components import GUIConstants, Fonts, TextArea, calc_text_centering
from seedsigner.hardware.buttons import HardwareButtonsConstants
fr... |
"""
PROVINCES
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
labels = ['Punjab','Gilgit Baltistan','Balochistan', 'KPK', 'Sindh', 'Federal Territory']
sizes = [154,1,1,6,2,2]
explode = (0.25,0.5,0,0.9,0.1,0.5)
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, a... |
from reification import *
from caty.jsontools import tag, untagged, tagged
class ReifyType(SafeReifier):
def setup(self, opts, arg):
SafeReifier.setup(self, opts, arg)
def _execute(self):
system = self.current_app._system
app_name, module_name, name = split_colon_dot_path(self._cdpath)... |
import pandas as pd
from data_aug.tezro_data import TezroDataset
from torchvision.transforms import transforms
from data_aug.gaussian_blur import GaussianBlur
from data_aug.view_generator import ContrastiveLearningViewGenerator
def get_simclr_pipeline_transform(size, s=1):
"""Return a set of data augmentation tran... |
# Hangman game
import random, string
def loadWords():
print("Loading word list from file...")
inFile = open(WORDLIST_FILENAME, 'r')
line = inFile.readline()
wordlist = line.split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def chooseWord(wordlist):
... |
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("connected OK")
else:
print("Bad connection Returned code=", rc)
def on_disconnect(client, userdata, flags, rc=0):
print(str(rc))
def on_subscribe(client, userdata, mid, granted_qos):
print(... |
# coding=utf-8
import numpy as np
from scipy.integrate import quad, cumtrapz
profiles = {"linear": lambda x: x,
"quadratic": lambda x: x ** 2,
"exponential": lambda x: np.exp(10 * (x - 1))}
def FDENS(x, moat_left, ramp_length, plasma_length, N, func='linear'):
func = profiles[func]
re... |
import os
import sys
import logging
import argparse
import json
import get_data
import settings
import utils
import data_manager
import visualizer
def init(stock_code, num_epoches, num_steps ):
#--stock_code MSFT --rl_method dqn --net lstm --num_steps 5 --learning --num_epoches 10 --lr 0.001 --start_epsilon 1 -... |
#!/usr/bin/env python
import argparse
import subprocess
import tempfile
import smtplib
import email.mime.multipart
from email.MIMEText import MIMEText
import logging
def set_log():
logger = logging.getLogger()
logger.setLevel(LOG_LEVEL)
fm = logging.Formatter('%(filename)s [LINE:%(lineno)d]# %(levelname)... |
from __future__ import unicode_literals
from django.conf.urls import include, patterns, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$',
'base.views.index',
name='index'),
url(r'^i18n/',
... |
'''
在反向传播时对梯度缩放
'''
from paddle.autograd import PyLayer
class GradMultiply(PyLayer):
@staticmethod #必须静态方法,(不初始化就可调用)
def forward(ctx, x,scale):
# ctx is a context object that store some objects for backward.
ctx.scale = scale # 注册变量,back中可以用
return x
@staticmethod
# forward h... |
#!/usr/bin/python
from __future__ import print_function
"""Recursive version if Fibonacci."""
def unused():
"""A function that shouldn't be compiled."""
return 42
def fib(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
print(fib(9))
# TODO: Do this later.
if 0... |
from datetime import datetime
from typing import Hashable, Any, Optional, Dict, TypeVar, List
from copy import deepcopy
from mongoengine import connect
from core.state_schema import User, Human, Bot, HumanUtterance, BotUtterance, Dialog, HUMAN_UTTERANCE_SCHEMA,\
BOT_UTTERANCE_SCHEMA
from core.transform_config imp... |
# -*- coding: utf-8 -*-
# File: test_tracker_adapter.py
""" tracker adapter test module. """
__author__ = 'Otto Hockel <hockel.otto@gmail.com>'
__docformat__ = 'plaintext'
import pytest
import urllib.request
from .conftest import mock_urlopen, _get_url, _put_url, _delete_url
from pymite.adapters import Tracker
def ... |
'''
Author: Nick Cao
Date: 2021-06-06 12:04:39
LastEditTime: 2021-06-06 12:12:18
LastEditors: Nick Cao
Description:
FilePath: \LeetCodeLog\src\121. Best Time to Buy and Sell Stock\121.py
'''
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = 10**5
profit = 0
for x i... |
# Generated by Django 2.2 on 2019-07-21 14:02
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0005_auto_20190721_1515'),
]
operations = [
migrations.AlterModelOptions(
name='address',
options={'verbose_name_plura... |
import os.path
import re
import datetime
from unittest.mock import MagicMock
from dicttoxml import dicttoxml
from data_collection.news_spider import NewsSpider
from data_collection.parser_zoo import PARSER_ZOO
from test.util import fake_response_from_file
def test_news_spider_find_news_ref():
response = fake_res... |
from norsourceparser.core.models import PosTreeContainer
def test_pos_tree_resolve():
tree = 'pos("S" ( "S" ( "N" ("N" ("Epic"))))) ("V" ("V" ("V" ("Running")))))'
resolved = PosTreeContainer.resolve_pos_tree(tree)
assert len(resolved) == 2
assert len(resolved[0]) == 2
assert resolved[0][0] == 'N... |
default_app_config = "wagtailblock.blocks.apps.BlocksConfig"
|
"""Add movie table and movie_genre
Revision ID: d11d5359e4ca
Revises:
Create Date: 2020-09-27 23:20:58.300881
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd11d5359e4ca'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### ... |
import sys
import multiprocessing
import datetime
import re
import os
import zlib
from datetime import datetime
import tempfile
import subprocess
from array import array
from struct import unpack
from urllib.request import pathname2url
import math
import bisect
import numpy as np
from collections import ... |
from django.db import models
# Create your models here.
class signup(models.Model):
name = models.CharField(max_length=100)
ph = models.CharField(max_length=100)
about = models.CharField(max_length=100, default='null')
email = models.EmailField(primary_key=True, max_length=100, default='null')
de... |
class PositionModel:
def __init__(self, id: int, position: str):
self.id = id
self.position = position
|
from __future__ import print_function
__author__ = ["Tomas Mendez Echenagucia"]
__copyright__ = "Copyright 2020, Design Machine Group - University of Washington"
__license__ = "MIT License"
__email__ = "tmendeze@uw.edu"
__version__ = "0.1.0"
import os
import json
from compas.datastructures import Mesh
# TODO: Make c... |
# enable users to import directly, without importing pretty_json.pretty_json
from pretty_json.pretty_json import *
|
from django.contrib.auth.base_user import BaseUserManager
from django.db import models
from django.core.validators import MinLengthValidator
from django.core.validators import MaxLengthValidator
from django.core.validators import RegexValidator
from django.contrib.auth.models import AbstractUser
class UserManager(Bas... |
"""
Profile CRUD, import/export, storage, and buildings
"""
import json
from celery.result import AsyncResult
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
fro... |
import numpy as np
from numpy import sin, cos, log
from _routines import ffi, lib
from threading import Thread, Lock
import quaternion
def basic_eval(q, a, b, c, max_iter, shape=None):
if shape is None:
for z in (q, a, b, c):
if hasattr(z, 'shape'):
if shape is None:
... |
"""
License
-------
Copyright (C) 2021 - David Fernández Castellanos
This file is part of the ADMiniSter package. You can use it, redistribute
it, and/or modify it under the terms of the Creative Commons Attribution
4.0 International Public License.
Summary
-------
... |
from datetime import timedelta
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from django.utils.timezone import now
from help_desk.models import ActiveRange
from help_desk.utils import create_help_desk_groups
from help_... |
# -*- coding: UTF-8 -*-
# Sandbox class
# https://github.com/hiromu/arrow-judge/blob/master/src/sandbox.py
import os
import re
import pwd
import json
import stat
import time
import shutil
import signal
import subprocess
import uuid
import configparser
AVAILABLE_DEVICES = ['full', 'null', 'random', 'stderr', 'stdin', ... |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/python3
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import re
import sqlite3
import time
import random
import logging
import copy
import threading
import concurrent.futures
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
#import thread
database ... |
import torch
from src.utils import preprocess
from time import gmtime, strftime
def save_model(model, optimizer, src_vocabulary, tgt_vocabulary, epoch, loss, time_elapsed, with_att=False, is_jit=False):
"""
Save trained model, along with source and target languages vocabularies.
:param model: The trained... |
from .experiment import Experiment
from .experiment_set import ExperimentSet |
#!/usr/bin/env python
import os
import urllib
import time
import threading
import sys
sys.path.insert(0, os.path.abspath('./plugins/butia'))
from gettext import gettext as _
from plugins.plugin import Plugin
from TurtleArt.talogo import logoerror
from TurtleArt.tapalette import make_palette
from TurtleArt.tapalette i... |
from math import pow
mod=1000000007
t=int(input())
while(t):
t-=1
k,a,b=map(int,input().split())
ans=0
j=1
while(j<=b):
ans+=((b-max(j,a)+1)*j)
j*=(k)
j+=1
print(ans%mod) |
#!/usr/bin/env python3
#
# $ env PYTHONPATH=.. python3 hello_world.py
# Tree: ['Hello', ',', 'World', '!']
#
import textparser
from textparser import Sequence
class Parser(textparser.Parser):
def token_specs(self):
return [
('SKIP', r'[ \r\n\t]+'),
('WORD', r'\w... |
from .utils import latest_version, validate
from .utils import SchemaNotFoundError, InvalidSchemaError, ValidationError
from .version import __version__
|
"""This module is a collection of classes and
operations for the arithmetic expressions that
will come as input from the end user.
"""
import pycalco
from pycalco.shell import PyCalcoShell
class PyCalco(object):
def __init__(self):
self.version = pycalco.version
self.shell = PyCalcoShell()
... |
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import scipy.stats
import matplotlib.gridspec as gridspec
# mpl.use('TkAgg')
# create base data
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000,200000,3650),
np.random.normal(43000,1000... |
import time
from datetime import timedelta
from typing import Union
def usec() -> int:
"""Returns the current time in microseconds since the Unix epoch."""
return int(time.time() * 1000000)
def msec() -> int:
"""Returns the current time in milliseconds since the Unix epoch."""
return int(usec() / ... |
import numpy as np
import re
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from sqlalchemy.sql import exists
from flask import Flask, jsonify
# Database Setup
engine = create_engine("sqlite://... |
# coding: utf-8
from __future__ import unicode_literals
from .ard import ARDMediathekBaseIE
from ..utils import (
ExtractorError,
get_element_by_attribute,
)
class SRMediathekIE(ARDMediathekBaseIE):
IE_NAME = "sr:mediathek"
IE_DESC = "Saarländischer Rundfunk"
_VALID_URL = (
r"https?://sr-... |
# Particles und Confetti
# Nach dem Processing (Java) Sketch von Daniel Shiffmann
# aus: The Nature of Code, o.O., 2012, Seite 166ff
# Dieses Mal mit externer Bibliothek
size(500, 500)
speed(30)
colormode(RGB)
from pvector import PVector
pt = ximport ("particle")
particles = []
confetti = []
def setu... |
import m1
m1.getdata(10)
|
"""Joint MAP state-path and parameter estimator."""
import itertools
import numpy as np
from ceacoest import optim, rk, utils
class Problem(optim.Problem):
"""Joint MAP state-path and parameter estimation problem."""
def __init__(self, model, t, y, u):
self.model = model
"""Underlying ... |
import os
from domainbed.lib import misc
import numpy as np
import torch
import torch.nn.functional as F
import json
def argmax(iterable):
return max(enumerate(iterable), key=lambda x: x[1])[0]
def argmin(iterable):
return min(enumerate(iterable), key=lambda x: x[1])[0]
def percent(number):
number = roun... |
# Generated by Django 3.2.6 on 2021-11-30 20:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('offers', '0008_auto_20211130_1718'),
]
operations = [
migrations.AlterField(
model_name='fiiedit',
name='data_base',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.