text stringlengths 3.07k 12.6k |
|---|
# move in circle
# check for lobby screen
# check after game
# pytess
# ocv
# keyboard
# mouse
import win32_connectors.KeyboardConnectors as kc
import time
import imageFunctions.imagecomparison as ic
from enum import Enum
from win32_connectors.KeyBoardLogger import keyIsUp
class State(Enum):
VOTING = 1
MENU ... |
"""
<NAME>
<EMAIL>
Albert-Ludwigs-Universität Freiburg
Computational Physics: Material Science
Exercise Sheet 01 - Planetary Evolution
The following are the referenced equations in the code:
Eq (1) : Euler algorithm for r(t+dt) and v(t+dt)
Eq (2) : Verlet algorithm for r(t+dt) and v(t)
Eq (3) : Velocity-Verlet algori... |
# Python script for extracting a subset of Live Ocean results
# ---------------------------------------------------------------------------
# Usage
#
# From command line:
# python UBC_subdomain.py filename1 filename2 filename3 ...
#
# Inside python:
# import UBC_subdomain
# UBC_subdomain.get_UBC_subdomain([fil... |
"""
datazen - A class for adding manifest-loading to environments.
"""
# built-in
import logging
import os
from io import StringIO
from typing import List, Tuple
# third-party
from cerberus import Validator
# internal
from datazen.environment.config import ConfigEnvironment
from datazen.classes.target_resolver impor... |
'''
It transmits to you a buffer (your puzzle input) listing each particle in order
(starting with particle 0, then particle 1, particle 2, and so on). For each
particle, it provides the X, Y, and Z coordinates for the particle's position
(p), velocity (v), and acceleration (a), each in the format <X,Y,Z>.
E... |
# -*- encoding: utf-8
import csv
import datetime as dt
import io
import os
import os.path
import traceback
import urllib.parse
import zipfile
import boto3
import archivematica
from archivematica import choose_processing_config
from big_s3 import S3File
from log_handler import Logger
from verify_transfer_packages imp... |
from helpers import send_and_assert, send_request
def test_get_list(sample_filled_app, api_url):
app, db, rbac, dmg = sample_filled_app
roles = send_request(app, api_url + '/roles').get_json()
assert len(roles) == 5
for role in roles:
assert 'name' in role
assert 'id' in role
... |
import re
from math import sqrt
from anytree import Node, RenderTree, DoubleStyle
from anytree.exporter import DotExporter
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def preprocessExpression(string):
"""Convert a expression string to a list of operand and operator"""
# Remove space... |
class wundiaedge(object):
''''
@brief 加权无向边
'''
def __init__(self, v, w, weight):
super(wundiaedge, self).__init__()
self.v = v
self.w = w
self.weight = weight
def either(self):
return self.v
def other(self, v):
return self.w if v ==... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Shaper (CMDB tool)
Lib for manipulating files: read/write
Support <EMAIL>
Minsk 2018
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software F... |
import glob
import os
import time
import numpy as np
import soundfile as sf
from constants import *
import common
# source1: https://bit.ly/2GSsEgw
# source2: https://bit.ly/2sWxHIc
def generate_fb_and_mfcc(signal, sample_rate):
# Pre-Emphasis
pre_emphasis = 0.97
emphasized_signal = np.append(
... |
import csv
def create_countries_csv():
''' creates noc.csv by adding a NOC_ID field '''
with open('noc_regions.csv') as csvfile:
reader = csv.reader(csvfile)
next(reader)
NOC_dict = {}
NOC_ID = 1
with open('countries.csv', 'w', newline='') as csvfile:
... |
#!/usr/bin/env python
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2019. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS... |
import json
from django.conf import settings
from aliyunsdkcore.client import AcsClient
from aliyunsdkjaq.request.v20161123 import (
OtherPreventionRequest,
LoginPreventionRequest,
AfsCheckRequest
)
from ._compat import (
build_opener, ProxyHandler, urlopen
)
DEFAULT_JAQ_REGION = 'cn-hangzhou'
DEFAU... |
"""System process utilities module."""
import time
import psutil
import warnings
import subprocess
import platform
import threading
import functools
from .timing import get_sleeper, exponential_interval
from testplan.common.utils.logger import TESTPLAN_LOGGER
def _log_proc(msg, warn=False, output=None):
if out... |
from flask import render_template, url_for, redirect, request, flash
from unolocum.amzn_form import UrlForm
from unolocum import app
from bs4 import BeautifulSoup
import requests
from unolocum.sql import cur, conn
from mysql.connector.errors import DataError
from datetime import datetime
# global variables
... |
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import gridspec
from sklearn.metrics import euclidean_distances
from matplotlib.ticker import MultipleLocator
from matplotlib.colors import Normalize
rc = {"legend.fontsize": 11,
"axes.titlesize": 11,
"axes.labelsize": 11,
"xtick... |
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module with utilities for archiving functionality."""
import os
from chromite.cbuildbot import cbuildbot_config
from chromite.cbuildbot import co... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from __future__ import division, print_function
import argparse
import collections
import os.path
import re
import sys
t... |
import turtle
import random
# assighining colors to the snake:
turtle.hideturtle()
turtle.penup()
snake = turtle.clone()
snake.shape("square")
# snake and background color:
bg_color = input("choose a background color, or die ")
turtle.bgcolor(bg_color)
snake_color = input("choose a snake color, or don't, i don't car... |
import os
import re
from ..api import NuvlaError
from .base import ResourceBase
APP_TYPE_K8S = 'application_kubernetes'
APP_TYPE_DOCKER = 'application'
class Module(ResourceBase):
resource = 'module'
TYPE_PROJECT = 'project'
TYPE_COMPONENT = 'component'
TYPE_APPLICATION = 'application'
def f... |
import torch
import torch.nn as nn
from FusionTransformer.models.transformers import SpatialTransformer, ScaleUpModule, image_2d_distilled_transformer
import timm
from typing import Dict
from collections import OrderedDict
class BilinearModule(nn.Module):
def __init__(self, in_features, out_features, interpolation... |
import math
import statistics
import warnings
import numpy as np
from hmmlearn.hmm import GaussianHMM
from sklearn.model_selection import KFold
from asl_utils import combine_sequences
class ModelSelector(object):
'''
Base class for model selection (strategy design pattern)
'''
def __init__(self, all... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2020 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publishe... |
import faulthandler
import random
import pytest
from rdkit.Chem import MolFromSmiles
import selfies as sf
faulthandler.enable()
@pytest.fixture()
def max_selfies_len():
return 1000
@pytest.fixture()
def large_alphabet():
alphabet = sf.get_semantic_robust_alphabet()
alphabet.update([
"[#Br]", ... |
import os
import time
import numpy as np
import tensorflow as tf
from tbase import utils
from tbase.data_loader import LoaderV2, FeederV2, Batch
from tbase.normalizers import Normalizer
from tbase.skeleton import SkeletonSequence
from tbase.visualizer import Visualizer
import flags_parser
from models import VanillaA... |
'''ShuffleNet in PyTorch.
See the paper "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn... |
#!/usr/bin/env python
# coding: utf-8
# 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 b... |
"""Generator of TTML/stpp mp4 media segments with fixed duration according to a template."""
# The copyright in this software is being made available under the BSD License,
# included below. This software may be subject to other third party and contributor
# rights, including patent rights, and no such rights are gran... |
import dlib
import cv2
import numpy as np
import models
import NonLinearLeastSquares
import ImageProcessing
import settings_storage
import FaceRendering
import utils
from drawing import *
import os
import time
def imageswap(cameraImg,detector, predictor, maxImageSizeForDetection, projectionModel,
me... |
#!/usr/bin/env python
# Copyright 2015 <NAME> <<EMAIL>>
#
# 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 la... |
import datetime
import re
from functools import total_ordering
from typing import Any # noqa: F401
from typing import Dict # noqa: F401
from typing import Iterable # noqa: F401
from typing import List # noqa: F401
from typing import Optional # noqa: F401
from typing import Text # noqa: F401
impo... |
import os
import torch
import yaml
from utils import data_utils, model_utils, criterion_utils
# Load configurations
with open("analysis/analysis_conf.yaml", "rb") as stream:
conf = yaml.safe_load(stream)
# Load audio-caption and audio-phrase pairs
caption_datasets, vocabulary = data_utils.load_data(conf["audio_... |
import curses
from .utils import ceil
# Draw a rectangle at X , Y with WITH AND HEIGHT
# ... ncurses as it but i can stend invert x,y and having lower right pos instead of width and height
def rect(win, _px, _py, _w, _h):
win.vline(_py+1, _px, curses.ACS_VLINE, _h - 1)
win.hline(_py, _px+1, curses.ACS_HLINE, _w - ... |
import os
from cffi import FFI
from . import evt_exception
class LibEVT:
ffi = FFI()
lib = None
abi = None
def check_lib_init():
if LibEVT.lib is None:
evt_exception.evt_exception_raiser(
evt_exception.EVTErrCode.EVT_NOT_INIT)
return LibEVT
def init_evt_lib():
assert ... |
import os, sys
sys.path.append("./")
import hydra
import omegaconf
import random
import numpy as np
import yaml
import math
from tqdm import tqdm
from sklearn.svm import OneClassSVM
import torch
from torch.utils.data import DataLoader
from pointnet_autoencoder.utils.setting import (
PytorchTools, is_absolute, ma... |
import subprocess
from datetime import datetime
import pytest
from pdm.pep517.metadata import Metadata
from tests import FIXTURES
def test_parse_module():
metadata = Metadata(FIXTURES / "projects/demo-module/pyproject.toml")
assert metadata.name == "demo-module"
assert metadata.version == "0.1.0"
as... |
# author: gorquan <<EMAIL>>
# date: 2019.8.16
import requests
import json
import time
from headers import headers
from urllib.parse import urlparse
import random
from bs4 import BeautifulSoup
import re
from hyper.contrib import HTTP20Adapter
from slimit.parser import Parser
from slimit.visitors import nodevisitor
from... |
from scripts.utils import get_account, FORKED_LOCAL_ENV
from scripts.get_weth import get_weth
from brownie import config, network, interface
from web3 import Web3
AMOUNT = Web3.toWei(0.1, "ether")
def aave_deposit():
account = get_account()
erc20_address = config["networks"][network.show_active()]["weth_to... |
import pygame
import math
import random
from pygame import mixer
mixer.init()
import time
strike_cnt = 0
score = 0
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("<NAME> | Update 1.0")
file = pygame.image.load('ShipBattleshipHull.png')
miss = pygame.image.load('spr_missile.png')
othe... |
import os
import threading
import inspect
from contextlib import contextmanager
from django.apps import AppConfig
from django.core.checks import Error, register
from django.conf import settings
from django.db.models import QuerySet
from django.forms import Form
from django.template import Context
from django.template.... |
import os
import pandas as pd
from abc import ABC, abstractmethod
import torch
from sdv.tabular.ctgan import CTGAN
import logger
import config
class ISaveLoad(ABC):
""" The ISaveLoad Interface defines the 'save' and 'load' methods
needed by a Checkpoint. The checkpoint uses these to load and save
models ... |
import argparse
import atexit
from pathlib import Path
import readline
import shlex
from typing import Callable, Dict, Iterable, List, Optional, Sequence
from . import input_streams
from .command import Command
from .exceptions import CommandError, RiposteException, StopRiposteException
from .printer.mixins import Pri... |
""" Imagekit Image "ImageProcessors"
A processor defines a set of class variables (optional) and a
class method named "process" which processes the supplied image using
the class properties as settings. The process method can be overridden as well allowing user to define their
own effects/processes entirely.
"""
from... |
# <NAME>
# Sarupria Research Group
# Clemson University
# 2019 Jun 11
import sys
import os
import math
import numpy as np
import argparse
import MDAnalysis as mda
# For Cython nlist
# PROVIDE AN ABSOLUTE PATH TO MAKE THIS IMPORT WORK
# FROM WHEREVER YOU ARE EXECUTING THIS CODE
sys.path.append('/home/rdefeve/repos/str... |
import discord
from discord.ext import commands
import logging
import utils.jdoodle as jdoodle
from utils.embed import EmbedUtils
logger = logging.getLogger(__name__)
BASH_EMOTE = "<:bash:481893449633890304>"
BRAINFUCK_EMOTE = "<:brainfuck:477434846738907137>"
C_LANG_EMOTE = "<:clang:481893204111654... |
import pytest
from django.contrib.contenttypes.models import ContentType
from nose.tools import assert_raises
from addons.osfstorage.models import NodeSettings
from addons.osfstorage import settings as osfstorage_settings
from osf.models import BaseFileNode, Folder, File, FileVersion
from osf_tests.factories import (... |
import logging
import time
import numpy as np
from timeserio.externals import keras
logger = logging.getLogger(__name__)
def _now():
"""Return the current time, helper for mocking."""
return time.time()
def _get_log_metrics(history, exclude=('epoch', 'batches')):
metrics = [k for k in history.keys() ... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
#!/usr/bin/env python
# dimselect.py
# Copyright (c) 2017. All rights reserved.
from rpy2 import robjects
from typing import Sequence, TypeVar, Union, Dict
import os
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
from d3m.primitive_interfaces.transformer import TransformerPrimitiveBase
import numpy ... |
def _parse_sources_impl(sources, out_files):
for src in sources:
file = src.files.to_list()[0]
out_files.append(file)
def _parse_sources(attr):
"""Split source files into public and private ones"""
public_files = []
private_files = []
if hasattr(attr, "srcs"):
_parse_source... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple On Memory File System Creator
"""
import sys
import argparse
from pathlib import Path
# table format: file:[next, pos, size, name] dir:[next, num, 0, name]
def out_header(out, table, name):
out.write('/* This file is generated by the MEMFS Converter */\... |
import logging
from typing import List, Tuple
import backoff
import sqlalchemy.exc
from climsoft_api.api.instrument import schema as instrument_schema
from climsoft_api.utils.query import get_count
from fastapi.exceptions import HTTPException
from opencdms.models.climsoft import v4_1_1_core as models
from sqlalchemy.or... |
from __future__ import annotations
from typing import Any, Optional, TYPE_CHECKING
import asyncio
import sys
from pathlib import Path
import aiohttp
import backoff
from aiopath import AsyncPath
from async_property import async_property
if TYPE_CHECKING:
from loguru import Logger
from json_parser import JSONObj... |
#!/usr/bin/env python
import json, os, yaml, subprocess, http.client, urllib, requests, random
from datetime import date
from re import escape
#from pathlib import Path
#import http.client, urllib, sys, random, time, requests
CONFIG_FILE = 'config.yaml'
with open(CONFIG_FILE, 'r') as config_file:
config = yaml.s... |
#!/usr/bin/env python2
# Python libs
import math
# Ros libs
import rospy
# Ros messages
from std_msgs.msg import Float64
from std_msgs.msg import Float32MultiArray
from sensor_msgs.msg import Imu
from geometry_msgs.msg import Twist
#Gravity
G = 9.81
FILTER_SIZE = 20
if rospy.has_param('/use_simulation'):
SIMULATIO... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2022 MBition GmbH
from typing import List, Union
from .utils import read_description_from_odx
from .structures import BasicStructure
from .dataobjectproperty import DopBase
from .decodestate import DecodeState
from .encodestate import EncodeState
class EndOfPduField(Dop... |
import os
import time
import tfplot
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
class Hook(object):
"""
Parent class of all hooks
Hooks are used in network.train() to monitor training progress
"""
def __init__(self):
self.step = -1
def run(self, sess, wr... |
# License: Apache 2.0
import warnings
import types
import numpy as np
from scipy import sparse as sp
from scipy.sparse import SparseEfficiencyWarning
from sklearn.base import BaseEstimator, TransformerMixin
from joblib import Parallel, delayed
from sklearn.utils.validation import check_array, check_is_fitted
from ..u... |
import os
import xarray as xr
import tensorflow as tf
import tempfile
import cfgrib
from datetime import datetime, timedelta
import numpy as np
import argparse
import logging
import shutil
import subprocess
import apache_beam as beam
import random
import sys
LEVEL_TYPE = 'atmosphere' # unknown?
def _array_feature(v... |
import matplotlib.pyplot as plt
from pyqchem.plots import plot_configuration
from pyqchem.structure import Structure
from urllib.request import urlopen
import requests as req
import numpy as np
import json
import warnings
from requests.exceptions import ConnectionError
def print_excited_states(parsed_data, include_co... |
import torch
import numpy as np
import time
class Integrator(torch.nn.Module):
def __init__(self, config):
super(Integrator, self).__init__()
self.config = config
self.device = config.SETTINGS.device
self.implementation = config.SETTINGS.implementation
def forward(self, upda... |
import time
from typing import Optional, TypedDict
import requests
from rest_framework.exceptions import ValidationError
from django.conf import settings
from django.contrib.auth.models import User
from officehours_api.backends.backend_dict import BackendDict
class BluejeansUserExtraFields(TypedDict):
username:... |
from pathlib import Path
import unittest
from cryptol.cryptoltypes import to_cryptol
from saw_client import *
from saw_client.llvm import Contract, void, SetupVal, FreshVar, cryptol, i8, i32, LLVMType, LLVMArrayType
def ptr_to_fresh(c : Contract, ty : LLVMType, name : Optional[str] = None) -> Tuple[FreshVar, SetupVal... |
import os
import json
import collections
import six
from openpype import resources
from .color_defs import parse_color
current_dir = os.path.dirname(os.path.abspath(__file__))
class _Cache:
stylesheet = None
font_ids = None
tools_icon_color = None
default_entity_icon_color = None
disabled_enti... |
""" Utils for sub commands """
import re
import os
import sys
from datetime import datetime, time as time_obj, timezone
from typing import List, NamedTuple, Optional, Tuple, Union
import pytz
import click
import pycountry
from tabulate import tabulate
from rich.console import Console
from tzlocal import get_localzone
... |
import csv
import networkx as nx
import pandas as pd
import logging
import os
from template_generation_utils import get_root_nodes, read_taxonomy_config, read_dendrogram_tree
CLUSTER = "cluster"
EXPRESSIONS = "expressions"
ALLEN_ID_PREFIX = "AllenDend:"
EXPRESSION_SEPARATOR = "|"
log = logging.getLogger(__name__)
... |
import tensorflow as tf
NUM_CLASSES = 1000
def fire_module(x, inp, sp, e11p, e33p):
with tf.variable_scope("fire"):
with tf.variable_scope("squeeze"):
W = tf.get_variable("weights", shape=[1, 1, inp, sp])
b = tf.get_variable("bias", shape=[sp])
s = tf.nn.conv2d(x, W, [... |
# mypy: ignore-errors
import json
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.db import models
from accounts.models import Account, LMS
from django.utils.translation import gettext_lazy as _
from pylti1p3.registration import Registration
class LtiToo... |
import numpy
import scipy
import scipy.signal
import librosa
import typing
import peakutils
import matplotlib.pyplot as plt
from ..multipitch import Multipitch
from ..chromagram import Chromagram
from ..dsp.wfir import wfir
from ..dsp.frame import frame_cutter
from collections import OrderedDict
class MultipitchESACF... |
import enum
class bank_side(enum.Enum):
Right = 1
Left = 2
class State:
def __init__(
self,
boat_location,
parent=None,
missionaries_right=3,
cannibals_right=3,
path_cost=0,
depth=None,
):
self.parent = parent
self.boat_location... |
from dataclasses import dataclass
from typing import Optional
from .combiner import apply_position, get_matcher, match_to_feature_sets
from .data import get_data
from .data_types import Symbol
from .definitions import BracketStrategy
from .features import FeatureSet
from .ipa_config import IPAConfig
from .matcher impo... |
from django.shortcuts import get_object_or_404
from django.conf import settings
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from apps.accounts.serializer import ProfileSerializer, \
LimitedProfileSerializer
from apps.challenge.models import Tournament
from .except... |
"""
HDMI MQTT Service
"""
# Warning: I am not proud of this code.
from hdmimatrix import switch
from hdmimatrix import actions as hdmi_actions
INITIAL_STATE = {
"connections": [],
"connections_error": None,
"selected_input": -1,
"selected_input_error": None,
"audio_mode": -1,
"audio_mode_... |
#!/usr/bin/python
import sys
if sys.version_info[0] == 2:
# get rid of 2.x range that produced list instead of iterator
range = xrange
from math import sqrt, ceil
from collections import deque
from unitTests import testAssert
def isPythagorean(a, b, c):
# return True if a^2 + b^2 == c^2, False otherwise
ret... |
"""
Sparks are pieces of information with IoC, URLs and other associated assets.
We can search using the API and by term, tag or other parameters.
"""
import typing
from .configuration import ( # pylint: disable=E0401
BASE_SPARKS_URL, BASE_SPARKS_TIMELINE_URL, BASE_SPARKS_DISCOVER_URL
)
from .core import BASEMo... |
import numpy as np
def relu(X):
return np.maximum(0, X)
def softmax(X):
X = X - np.max(X, axis=1, keepdims=True)
return np.exp(X) / np.sum(np.exp(X), axis=1, keepdims=True)
def relu_backward(Z, delta):
delta[Z <= 0] = 0
def cross_entropy_error(y, t):
batch_size = y.shape[0]
return -np.sum(t ... |
"""
Not using Python Enum
The value/name proposition can make things unnecessarily confusing for an SDK.
KISS applies here.
"""
class CheckoutSdkEnum:
@classmethod
def has_value(cls, value):
return value is not None and \
any(str(value).lower() == str(item).lower()
for item... |
# Copyright © 2015-2017 <NAME> <<EMAIL>>
# SPDX-License-Identifier: MIT
'the “ls” command'
import functools
import os
import re
from lib import colorterm
from lib import deblogic
from lib import debsoap
from lib import utils
def add_argument_parser(subparsers):
ap = subparsers.add_parser('ls')
ap.add_argume... |
# Copyright 2020 Alibaba Group Holding Limited. 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 ... |
"""
Definition of views.
"""
from datetime import timedelta
import json
from django.shortcuts import render, redirect, render_to_response
from django.http import HttpRequest, Http404, HttpResponseBadRequest
from django.template import RequestContext
from django.conf import settings
from django.utils import timezone
fr... |
from utils import *
row_units = [cross(r, cols) for r in rows]
column_units = [cross(rows, c) for c in cols]
square_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]
unitlist = row_units + column_units + square_units
# TODO: Update the unit list to add the new diagonal units
diagno... |
import re
import os
import sys
import socket
from threading import Thread, Event
import subprocess
import time
from shutil import copyfile
try:
import IDF
except ImportError:
# this is a test case write with tiny-test-fw.
# to run test cases outside tiny-test-fw,
# we need to set environment variable `... |
from src.basics import lexical_analyzer as lex
from src.strand import strand_graph as sg, bond_graph as bg
from src.species import species as sp
from src.species import species_explore as se
from src.util import cexception as ex
from bidict import bidict
def get_additional_info(fp, line):
"""
get additional i... |
# get value of dice
def diceValue():
dice = []
for randomValue in range(5):
dice.insert(randomValue, random.randint(1,6))
return sorted(dice)
# Count the value of dice
def CountDice(dices):
diceLength = len(dices) - 1
count = 0
diceValueCount = {}
while(count < diceLength):
curre... |
#!/usr/env/bin python3
import argparse
import os
import os.path
import shutil
import subprocess
import json
import time
root_dir = os.path.dirname(os.path.abspath(__file__))
def parse_args():
p = argparse.ArgumentParser(description="Script to automate a training and guess runs with specified config files" )
p.... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from nets.Xception import Xception
from keras.models import Model
from keras import layers
from keras.layers import Input
from keras.layers import Lambda
from keras.layers import Activat... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 18 23:48:52 2021
@author: James
"""
# import packages
import requests
from bs4 import BeautifulSoup
import time
import re
import pandas as pd
import json
# 非函數測試
'''
url = 'https://www.ptt.cc/bbs/Steam/index.html'
keyword = '心得'
previousPage = 5
# def 1
# 爬網頁
r = req... |
#!/usr/bin/env python
"""
Loader to build an events database from micro architecture specifications (json)
This module provides factories to parse and build event objects
Each record is classified into one of following types
1. generic core - events programmable in general purpose pmu registers
2. fixed core - e... |
import os
from typing import cast, List, Optional
from logging import Logger, Formatter, Handler, StreamHandler, DEBUG, \
INFO, WARN, ERROR, CRITICAL
from enum import Enum
__all__ = ['enableVerbose', 'disableVerbose']
loggers = {}
"""
The LogLevel enum class defines the log levels for the ArkoudaLogger, the
pur... |
from typing import List, Dict, Tuple, Union
import itertools
import time
import numpy as np
from utils import calculate_times
from utils.dependency_graph import DependencyNode, DependencyGraph, CircularDependencyException, DisconnectedDependencyGraphException, SolveOrder, calculate_order
from . import Solver
from dat... |
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from .models import User, auction_listing, bids, comment
from .forms import c... |
import importlib
import inspect
import pkgutil
from pathlib import Path
import manimlib
from flask import Flask, render_template, abort, url_for, send_from_directory
from flask_assets import Environment, Bundle
from pygments import highlight
from pygments.lexers.python import Python3Lexer
from pygments.formatters.html... |
# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
import numpy as np
from capfore.forecast import Forecast
from capfore.models import Task,Cell
from celery.utils.log import get_task_logger
import json
from capfore.dbgets import *
logger = get_task_logge... |
""" In this example, we're going to use NEvoPy's implementation of a classic
fixed-topology neuroevolution algorithm to learn how to play Flappy Bird!
We're going to use the "FlappyBird-v0" gym environment (available here:
https://github.com/Talendar/flappy-bird-gym) to simulate the game.
Note:
When I ran this ex... |
"""
Copyright (2010-2014) INCUBAID BVBA
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, so... |
# all imports
import os
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
from pybtex.database import parse_string
app = Flask(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
ALLOWED_EXTENSIONS = set(['bib'])
#... |
import asyncio
import aiofiles
import aiohttp
import async_timeout
import os
import random
import requests
from collections import namedtuple
import pyppeteer
import tkinter
try:
from ujson import loads as json_loads
except:
from json import loads as json_loads
url_httpbin_get = 'http://httpbin.org/get'
d... |
from datetime import datetime, timedelta
from django import forms
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_protect
from django... |
"""Tools for helping manage xontributions."""
import importlib
import importlib.util
import json
import pkgutil
import sys
import typing as tp
from enum import IntEnum
from pathlib import Path
from xonsh.built_ins import XSH
from xonsh.cli_utils import ArgParserAlias, Arg, Annotated
from xonsh.completers.tools import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.