content stringlengths 5 1.05M |
|---|
import json
import os
import numpy as np
import tensorflow as tf
from flask import Flask, request
with open("dictionary-test.json", "r") as fopen:
dic = json.load(fopen)
cluster = tf.train.ClusterSpec({"worker": ["192.168.0.101:2222", "192.168.0.104:2223"]})
class Model:
def __init__(
self, size_la... |
from os.path import realpath, exists, join
from larch import Group
from larch.fitting import param_group, Parameter
from larch.io import read_xdi
from larch.xafs import feffit_dataset, feffit_transform, feffit, feffit_report, feffpath
from larch.wxlib import _newplot, _plot
def do_fit(self, which):
if which == ... |
#!/usr/bin/env python
"""
update_dreqs_0243.py
Determine which MPI coupled variables need the external_variables global
attribute setting.
"""
import argparse
import json
import logging.config
import os
import pprint
import sys
import django
django.setup()
from pdata_app.models import DataRequest, VariableRequest
__... |
"""
Main module which defines ApplicationWindow,
the main window of PythonTurtle.
"""
import multiprocessing
import os
try:
import wx
import wx.adv
import wx.aui
import wx.lib.buttons
import wx.lib.scrolledpanel
except ModuleNotFoundError:
print("wxPython doesn't seem to be installed. You need ... |
from torch import nn
class CNN_CIFAR(nn.Module):
def __init__(self):
super(CNN_CIFAR, self).__init__()
self.conv2d_1 = nn.Conv2d(3, 32, kernel_size=5, padding=2)
self.max_pooling = nn.MaxPool2d(2, stride=2)
self.conv2d_2 = nn.Conv2d(32, 64, kernel_size=5, padding=2)
self.fl... |
import numpy as np
def check_loss(result_name,train_loss,val_loss):
'''
Returns explanations for loss plot if the model overfits
'''
f = open("./Results/" + result_name+"_sugg.txt","a+")
g = open("./Results/" + result_name+"_explain.txt","a+")
tloss = np.load(train_loss)
vloss = np.l... |
#coding:utf-8
import re
import pandas as pd
import jieba
import jieba.posseg as pseg # 词性标注
#from jieba.analyse import ChineseAnalyzer
import numpy as np
import json
from jieba.analyse import extract_tags
class extractkey:
def __init__(self):
#分词加载,预处理字典
jieba.load_userdict("./dict/expendword.txt")... |
# Generated by Django 3.2.7 on 2021-10-01 19:51
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('medico', '0001_initial'),
]
operations = [
migrat... |
import copy
from typing import Tuple, Union
import control as _ctrl
import numpy as _np
from numpy import inf
from .linalg import block, eye, matrix, norm, zeros, eig_max
from .quantizer import DynamicQuantizer as _DynamicQuantizer
from .quantizer import StaticQuantizer as _StaticQuantizer
from .quantizer import _Con... |
import argparse
import csv
from os.path import abspath, dirname
from unicodedata import normalize
from urllib.parse import urlparse
from jinja2 import Environment, FileSystemLoader
def load_template(spider_data):
env = Environment(loader=FileSystemLoader("."))
template = env.get_template("spider_t... |
# @Author: George Onoufriou <georgeraven>
# @Date: 2018-11-04
# @Filename: argz.py
# @Last modified by: georgeraven
# @Last modified time: 2018-11-04
# @License: Please see LICENSE in project root.
# @Copyright: George Onoufriou
import os, sys, argparse, configparser
def argz(argv=None, description=None):
... |
__all__ = (
"Result",
"AlwaysSuccess",
"AlwaysFailure",
"ResultType",
"NoResultType",
"unsafe",
"success",
"failure",
"unwrap_success",
"unwrap_failure",
"NoResult",
)
# Annotations
from .result import (
Result,
AlwaysSuccess,
AlwaysFailure,
)
# Types
from .re... |
from markdown import Extension
from markdown.preprocessors import Preprocessor
from prosecode.chunk import Chunk
import re
class CodeChunkExtension(Extension):
def __init__(self, execute = False, executepath = ''):
super().__init__()
self.execute = execute
self.executepath = executepath
... |
from setuptools import find_packages, setup
#The packages gets all the relevant python packages, for non python files, you need to add
# them into the manifest.in
VERSION = "0.2.0"
setup(
name='YTReviewsAPI',
version=VERSION,
author="Porter Hunley",
author_email="porterhunley@gatech.edu",
license="... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import paramiko
import Mobigen.Common.Log as Log; Log.Init()
class SftpClient :
def __init__(self, host, port, user, passwd) :
self.host = host
self.port = port
self.user = user
self.passwd = passwd
self._connect()
def _connect(self) :
try... |
import unittest
import ciw
class TimeDependentBatches(ciw.dists.Distribution):
def sample(self, t, ind=None):
if t < 11.0:
return 5
return 1
class TestArrivalNode(unittest.TestCase):
def test_init_method(self):
ciw.seed(5)
Q = ciw.Simulation(ciw.create_network_from_... |
#!/usr/bin/env python3
"""\
Stream g-code to grbl controller
This script differs from the simple_stream.py script by
tracking the number of characters in grbl's serial read
buffer. This allows grbl to fetch the next line directly
from the serial buffer and does not have to wait for a
response from the computer. This ... |
import random
ans = []
def generate_binomial_pricing_of_stock(S0,u,d,n):
if n == 0:
return
curr = []
for val in ans[-1]:
curr.append(val*u)
curr.append(val*d)
ans.append(curr)
generate_binomial_pricing_of_stock(S0,u,d,n-1)
def call_option_pricing(rate, strike_price, answer... |
# Exact copy of global values in extensions.tg_filters
SPA = "spa"
WEBAPP = "webapp"
ALPINE = "alpine"
DEBIAN = "debian"
YES = 'yes'
NO = 'no'
S3 = 'S3'
GCS = 'GCS'
|
limit = {
'temperature': {'min': 0, 'max': 45},
'soc': {'min': 20, 'max': 80},
'charge_rate': {'min': 0, 'max': 0.8}
}
threshold = {
'temperature': 4,
'soc': 4,
'charge_rate': 0.04
}
warning_message = {
'EN':{
'temperature': {'min': 'Warning: Approaching less temperature', 'max': 'Warning: Approach... |
print("Hello World")
x = input("your name?" )
print("Hello ", x)
|
# 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 json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Ocean(... |
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
import numpy as np
### Create our BC Model ###
class HumanData(Dataset):
def __init__(self, data):
self.data = data
def __len__(self):
return len(... |
'''
Configuration File:
-------------------
config_name: The name of the config file to look at for the sim parameters to use
See the template directory for predefined config files. Run ::
$ peptidesim --config <configuration file name>
to generate a config file in the current directory based on the config template... |
from django.shortcuts import render, redirect
from .models import Message
from .forms import MessageForm
def board(request):
messages = Message.objects.order_by('-date')
if request.method == "POST":
form = MessageForm(request.POST)
if form.is_valid():
form.save()
return ... |
from .auth import Auth, new_oauth_client
from .blueprint import AuthBlueprint
from .config import AuthConfig
from .decorator import requires_auth, requires_role
__all__ = [
"Auth",
"AuthConfig",
"requires_auth",
"requires_role",
"AuthBlueprint",
"new_oauth_client",
]
|
import json
from pyjetbrainsdevecosystem.data_import_utils import unpack_csv_data
questions_dict = {}
with open('survey_data/2020/DevEcosystem 2020 questions_outside.csv',
encoding='utf8') as questions_text:
questions_reader = unpack_csv_data(questions_text)
questions_fieldnames = questions_reader.f... |
# This an autogenerated file
#
# Generated with ThrusterControl
from __future__ import annotations
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.thrustercontrol import ThrusterControlBlueprint
from typing import Dict
from sima.sima.moao import ... |
#
# Some utility functions for the pipelines
# Author: cdeck3r
#
import os
import collections
# src: https://stackoverflow.com/a/2158532
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
... |
# coding=utf-8
from __future__ import unicode_literals
from collections import OrderedDict
from .. import Provider as ColorProvider
localized = True
# Reference
# https://th.wikipedia.org/wiki/รายชื่อสี
# on 2019-10-20
class Provider(ColorProvider):
all_colors = OrderedDict((
('สีดำ', '#000000'),
... |
import yaml
import json
import Core
import markdown
import re
__yaml_frontmatter__ = r'(---)(.*?)\1'
class YamlParser(Core.Parser):
accepts = ["yaml", "yml"]
def interpret(self, file_contents):
return yaml.load(file_contents)
class JsonParser(Core.Parser):
accepts = ["json", "js"]
def int... |
"""
*Integer*
An integer of music.
Implemented with int.
"""
from abc import ABCMeta
from music.__model._number import Number
__all__ = ["Integer"]
class Integer(
int,
Number,
):
__metaclass__ = ABCMeta
def __init__(
self,
n: int,
):
super(Integer, self).__n... |
"""
@file
@brief Actions definition.
"""
from .api_extension import AutoAction
from .gactions import MLAction, MLActionFunction
class MLModel(MLActionFunction):
"""
Base class for every machine learned model
"""
def __init__(self, input, output_names=None, name=None):
"""
@param name... |
# 2021Jan23 Brockman Neopixel Demo
from adafruit_circuitplayground import cp
import time
Rdefault = 0
Gdefault = 0
Bdefault = 0
R = Rdefault
G = Gdefault
B = Bdefault
cp.pixels.brightness = 0.03
pressed_count = 0
pressed_prior = False
pressed = False
pressed_time = 0
while True:
# ether button pressed?
i... |
# layerindex-web - Branch-based URL definitions
#
# Copyright (C) 2013-2016 Intel Corporation
#
# Licensed under the MIT license, see COPYING.MIT for details
#
# SPDX-License-Identifier: MIT
from django.conf.urls import *
from django.views.defaults import page_not_found
from django.urls import reverse_lazy
from layeri... |
#!/usr/bin/env python3
"""
A unival tree (which stands for "universal value") is a tree where all
nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
"""
c... |
from jikanpy import Jikan
from jikanpy.exceptions import APIException
import pickle
from collections import Counter, defaultdict
from time import sleep
from assoc import AssocMap
# VERBOSITY GLOBALS: changing these has no influence on performance, only the human-readable
# output of the program
NRESULTS_SEARCH = 10
N... |
import sys
from random import randint
import commands
def printSpaces(i) :
for ii in range(i) :
sys.stdout.write(' ')
class naryNode3 :
def __init__(self, data):
self.data = data
self.parent = None
self.firstChild = None #this node has pointers to only th... |
"""
common functions that almost all route needs
"""
from functools import wraps
from flask import jsonify
from .. import db
def jsonify_wrapper(func):
"""
a decorator, jsonify every api return dict value.
example:
.. code-block:: python
@main.route('/api/search')
@jsonify_wrapper
... |
import os
import yaml
import time
import shutil
import torch
import random
import argparse
import numpy as np
import datetime
from torch.utils import data
import pickle
from loader.airsim_fsl_dataset import airsim_fsl_dataset
from loader.samplers import CategoriesSampler
from tools.utils import load_model
from trainer... |
# -*- coding: utf-8 -*-
# python manage.py make migrations your_app_label
# python manage.py migrate --fake-initial your_app_label
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
from datetime import date, datetime
from django.conf import settings
class OweMode... |
"""Plot the surface pressure coefficient at final time step."""
from matplotlib import pyplot
import numpy
import pathlib
import petibmpy
import rodney
def get_pressure(simudir, timestep):
name = 'p' # name of the field variable to load
datadir = simudir / 'output'
# Load the gridlines from file.
... |
import os
import random
import numpy as np
from pysc2.env import sc2_env
from pysc2.lib import actions
from gym.spaces.discrete import Discrete
from sc2env.pysc2_util import register_map
from sc2env.representation import expand_pysc2_to_neural_input
MAP_NAME = 'SimpleTacticalEnvironment'
MAP_SIZE = 64
RGB_SCREEN_SIZE... |
"""The SyncWorker is a single thread of execution that is responsible for
executing sync-OLD! commands.
The SyncWorker performs these steps in a loop:
1. Using DTServer, pop the next sync-OLD! command off of the queue.
2. Determine whether the OLD already exists and create it if it does not.
3. Fetch the last modifie... |
"""remove feels table
Revision ID: c2d2f403fb8c
Revises: 4923fb2ba581
Create Date: 2020-02-14 20:23:25.494070
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "c2d2f403fb8c"
down_revision = "4923fb2ba581"
branch_labels = None
depends_on = None
def upgrade():
... |
from django.conf.urls import patterns, url
from package import apiv2 as package_api
from grid import views as grid_views
from searchv2 import views as search_views
urlpatterns = patterns("",
# {% url "apiv2:category" %}
url(
regex=r"categories/$",
view=package_api.CategoryListAPIView.as_view()... |
from datetime import date, timedelta
from sqlalchemy.sql import and_, func
from controllers.c_panel import CPanel
from exceptions.abort_exception import AbortException
from models import try_commit, try_flush, Cells, Certificate, Mark, Place, Incoterm, PanelType, User
from models.company import Company
from models.pa... |
### This is an example
i = 20
# @@DNA
# Description: prints 'hello world' to stdout
# Input: None
# Output: None
# Status: Done
# @@END
def main(){
print('Hello world')
return
}
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import json
import time
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
from numpy import newaxis
from keras.layers import Dense, Activation, Dropout, LSTM
from keras.models import Sequential, load_model
from kera... |
#
# Copyright 2016 Quantopian, 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 wr... |
""" flask hello test app """
import sys
import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
"""
print(sys.version)
print("============================")
print(sys.version_info)
print("============================"... |
#!/usr/bin/env python
# coding: utf-8
# ## Постановка задачи
# Загрузим данные и подготовим все данные для анализа: проведем нормализацию и преобразование категорий. Оптимизируем потребление памяти.
#
# Разделим выборку на обучающую/проверочную в соотношении 80/20.
#
# Применим наивный Байес для классификации скорин... |
"""Pipeline for image augmentation.
This module contains the image augmentation pipeline.
Todo:
- Add license boilerplate.
- Cleanup
"""
from multiprocessing import Pipe
from ImageBot.Config import *
from collections.abc import Iterable
import uuid
from functools import partial
from queue import Queue
from m... |
from torchvision import transforms
from PIL import Image
def base_transform(img_size, mode):
assert mode in ['train', 'test']
if mode == 'train':
transform = transforms.Compose([
transforms.Resize((img_size,img_size), interpolation=Image.BICUBIC),
transforms.RandomHorizontalFlip... |
# -*- coding: utf-8 -*-
#
# BitcoinLib - Python Cryptocurrency Library
# Chain.so client
# © 2017-2019 July - 1200 Web Development <http://1200wd.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published ... |
"""p2 core constants"""
ATTR_BLOB_STAT_MTIME = 'blob.p2.io/stat/mtime'
ATTR_BLOB_STAT_CTIME = 'blob.p2.io/stat/ctime'
ATTR_BLOB_HASH_MD5 = 'blob.p2.io/hash/md5'
ATTR_BLOB_HASH_SHA1 = 'blob.p2.io/hash/sha1'
ATTR_BLOB_HASH_SHA256 = 'blob.p2.io/hash/sha256'
ATTR_BLOB_HASH_SHA384 = 'blob.p2.io/hash/sha384'
ATTR_BLOB_HASH... |
# -*- coding: utf-8 -*-
"""
Kitconc examples
@author: jlopes@usp.br
"""
from kitconc.kit_corpus import Corpus
corpus = Corpus('kitconc-examples/workspace','ads','english')
collocates = corpus.collocates('experience',left_span=2,right_span=2,coll_pos='IN NN JJ VBN VBD',show_progress=True)
print(collocates.df.he... |
#!/usr/bin/env python3
try:
import sys, os, time, threading as t;
import re, datetime as dt, pickle;
import tkinter as tk;
from tkinter import ttk
from PIL import Image; from PIL import ImageTk;
from tkinter import messagebox;
from tkinter import filedialog;
except:
pass;
try:
import sys;
import re, dateti... |
import pygame
import os
import random
width = 1000
height = 800
centre_x = width/2
centre_y = height/2
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# pour ecrire sur l ecran
font_name = pygame.font.match_font('arial')
def draw_text(surf, text, si... |
import os
import re
import json
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation impor... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 19:09:31 2018
@author: joshu
"""
def add_numbers(num1, num2):
return num1+num2
def assign_name():
name = 'Doug'
gbl_name = 'Sally'
def change_name():
global gbl_name
gbl_name = 'Sammy'
change_name()
print(gbl_name)
def get_sum(num1, num2... |
import os
from dotenv import load_dotenv
from fabric import Connection
from invoke.exceptions import UnexpectedExit
load_dotenv("infra.env")
HOST = os.environ.get('HOST')
REMOTE_USER = os.environ.get('REMOTE_USER')
KEYFILE = os.environ.get('KEYFILE')
VERSION = os.environ.get('UBUNTU_VER')
PACKAGES = os.environ.get('PA... |
import re
import random
from src.utilities import *
from src import users, channels, debuglog, errlog, plog
from src.functions import get_players, get_all_players
from src.decorators import cmd, event_listener
from src.containers import UserList, UserSet, UserDict, DefaultUserDict
from src.messages import messages
fro... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import torch
import random
def parse_cfg(cfg_file):
'''
读取并解析配置文件
输入: 配置文件目录
输出: 解析后的结果,list 中的每一个元素为 dict 形式
'''
lines = []
with open(cfg_file, 'r') as f:
for line in f.readlines():
if len(line) >... |
# -*- coding: UTF-8 -*-
from collections import OrderedDict
import cv2
import numpy as np
import dlib
FACIAL_LANDMARKS_68_IDXS = OrderedDict([
("mouth", (48, 68)),
("inner_mouth", (60, 68)),
("right_eyebrow", (17, 22)),
("left_eyebrow", (22, 27)),
("right_eye", (36, 42)),
("left_eye", (42, 48... |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_citadel
# Purpose: SpiderFoot plug-in to search Leak-Lookup using their API,
# for potential data breaches.
#
# Author: sn <citadel.pw@protonmail.com>
#
# Created: 15/08... |
from enum import unique
from flask import Flask, render_template, request, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import redirect
from flask_login import LoginManager, UserMixin, login_manager, login_user, logout_user, login_required, current_user
from werkzeug.security import check_password_... |
from day15_1 import find_path
def extend(rows, times=5):
"""Extend rows. Return the result."""
extended = rows
length = len(rows)
for row in extended: # Lengthen rows.
for i in range((times - 1) * length):
row.append(row[i] % 9 + 1)
for i in range((times - 1) * length): # Add... |
# Code from Chapter 10 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with n... |
import string
from collections import defaultdict
'''
This function constructs folds that have a balanced category distribution.
Folds are stacked up together to give the order of docs in the main data.
idx_order defines the order of documents in the data. Each sequence of (docs_per_fold) documents in... |
"""Added the on delete and on update settings
Revision ID: 500de4365b5d
Revises: 1dbcb98d3ab8
Create Date: 2017-09-22 22:31:34.147336
"""
# revision identifiers, used by Alembic.
revision = '500de4365b5d'
down_revision = '1dbcb98d3ab8'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy ... |
import datetime
from typing import Any, Dict, Tuple
from ee.clickhouse.client import sync_execute
from ee.clickhouse.models.action import format_action_filter
from ee.clickhouse.models.property import parse_prop_clauses
from ee.clickhouse.sql.retention.retention import REFERENCE_EVENT_SQL, REFERENCE_EVENT_UNIQUE_SQL, ... |
from django.contrib import admin
from infs3202.events.models import Event, Ticket
admin.site.register(Event)
admin.site.register(Ticket)
|
import geopandas as gpd
import numpy as np
import shapely.geometry as sg
from pandamesh import triangle_geometry as tg
outer_coords = np.array([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])
inner_coords = np.array([(3.0, 3.0), (7.0, 3.0), (7.0, 7.0), (3.0, 7.0)])
line_coords = np.array([(2.0, 8.0), (8.0, 2.0)]... |
import click
from .commands import archive, archive_category
@click.group()
@click.pass_context
def channel(context):
"""Manage series operations"""
pass
channel.add_command(archive)
channel.add_command(archive_category)
__all__ = [
'channel'
]
|
# DomirScire
from collections import Counter
import operator
WORDS = ['this', 'is', 'an', 'elementary', 'test', 'example']
def most_repeating_letters_count(word):
return Counter(word).most_common(1)[0][1]
def most_repeating_word(words):
return max(words, key=most_repeating_letters_count)
if __name__ == "__... |
from injector import inject
from logging import getLogger
from typing import List
from typing import Optional
from gumo.core import EntityKey
from gumo.pullqueue import PullTask
from gumo.pullqueue.worker.domain.configuration import PullQueueWorkerConfiguration
logger = getLogger(__name__)
class PullTaskRemoteRepo... |
import docx
def docx_to_text(file_path):
doc = docx.Document(file_path)
result = []
for p in doc.paragraphs:
txt = p.text
result.append(txt)
return result
|
from ..utils.loader import Custom
from ..utils.helper import get_full_name, make_output
from .base_resource import BaseResource
from .role import Role
class ApiGatewayResource(BaseResource):
TEMPLATE = \
'''
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref null
'''
def _dump_properties(self, prop... |
import numpy as np
a=[1,2,3,4]
def add_ab(a=1,b=2):
return a+b
b=[1,2,3,4]
print(type(a),a+b)
|
import sys
try:
import unittest2 as unittest
except ImportError:
import unittest
from rope.base import exceptions
from rope.base import libutils
from rope.base.pycore import _TextChangeDetector
from rope.base.pyobjects import get_base_type, AbstractFunction
from ropetest import testutils
class PyCoreTest(uni... |
from unittest import TestCase
from kdrl.agents.static import *
from kdrl.trainer import *
import numpy as np
class TestStaticAgent(TestCase):
def test_random_agent(self):
agent = RandomAgent(action_space=2)
def random_test(f):
first_action = f()
for i in range(100):
... |
class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
seen = defaultdict(int)
is_fast_forwarded = False
while N > 0:
if not is_fast_forwarded:
state_key = tuple(cells)
last_seen_index = seen[state_key]
... |
from win32com.client import (
GetObject,
Dispatch,
)
from pythoncom import (
com_error,
)
import datetime
import re
from textwrap import fill
# --------- #
__test__ = {}
# --------- #
# 12/30/1899, the zero-Date for ADO = 693594
_ADO_zeroHour = datetime.date(1899, 12, 30).toordinal()
_time_... |
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Quantum Fourier Transform examples.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the ... |
from icemac.addressbook.browser.search.result.handler.export.base import (
BaseExport)
import icemac.addressbook.export.xls.simple
class DefaultsExport(BaseExport):
"""Exporter for default data and addresses."""
exporter_class = icemac.addressbook.export.xls.simple.DefaultsExport
class CompleteExport(B... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.3.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # Error bars in plots:
# %% [markd... |
"""Tests for ``iter_dataframes`` generator property."""
import numpy as np
from waves import Sound
def test_iter_dataframes_mono_from_file(mono_sound):
data = mono_sound.dataframes
for i, frame in enumerate(mono_sound.iter_dataframes):
assert frame == data[i]
def test_iter_dataframes_stereo_from_... |
import re
import sys
VERSION = '0.7.1'
VERSION_STRING = "WebIOPi/%s/Python%d.%d" % (VERSION, sys.version_info.major, sys.version_info.minor)
PYTHON_MAJOR = sys.version_info.major
BOARD_REVISION = 0
_MAPPING = [[], [], []]
_MAPPING[1] = ["V33", "V50", 0, "V50", 1, "GND", 4, 14, "GND", 15, 17, 18, 21, "GND... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-04-28 14:39
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('website', '0044_remove_promotion_referred'),
]
ope... |
"""Test all utils."""
from django.test import TestCase
from oauth2client.client import OAuth2WebServerFlow
from geokey.contributions.utils import (
my_flow_from_clientsecrets,
get_args,
get_authenticated_service,
initialize_upload
)
class GetArgsTest(TestCase):
"""Test for method 'get_args'."""... |
class BaseError(Exception):
def __init__(self, status, title, body=''):
self._status = status
self._title = title
self._body = body
@property
def title(self):
return self._title
@property
def body(self):
return self._body
@property
def status(self):... |
import time
from pyrunner import Worker
class SayHello(Worker):
def run(self):
self.logger.info('Hello World!')
return
class FailMe(Worker):
def run(self):
return 1 |
#!/usr/bin/env python3
""" Compute greatest common factor of two integers provided by the user """
from get_integer_from_user import get_integer
def gcd_recursive(num1, num2):
""" (int, int) -> int
Uses Euclid's method to compute the greatest common factor
(greatest common divisor) of two integer... |
from arcgis.gis import GIS
from arcgis.features.feature import Feature
import os
from .. import util
from ..util import ThreadPool, lprofile
'''
from dotenv import load_dotenv
load_dotenv()
'''
from requests.exceptions import ConnectionError
'''
ARCGIS_USER = os.getenv("ARCGIS_USER")
ARCGIS_PASS = os.getenv("ARCGIS_PAS... |
# Import packages
import numpy as np
import cv2
import imutils
print "All packages imported properly!"
# Displaying & resizing images
image = cv2.imread("testudo.jpg")
cv2.imshow("Old School Testudo Logo", image)
cv2.waitKey(0)
image = imutils.resize(image, width=400)
cv2.imshow("Old School Testudo Logo: Resized",... |
"""
Example DAG where rekcurd_airflow plugins are used
"""
import airflow
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from rekcurd_airflow.operators import ModelSwitchOperator
from datetime import timedelta
default_args = {
'owner': 'rekcurd-airflow',
'depends_on_past'... |
class Array(object):
def sum(self, size, array_string):
return 0
|
import webapp2
from views import MainPage, SubscriberPage
application = webapp2.WSGIApplication([
('/', MainPage),
('/subscriber', SubscriberPage),
], debug=True)
|
#!/usr/bin/env python3
from llvmlite import ir
i1 = ir.IntType(1)
i8 = ir.IntType(8)
i16 = ir.IntType(16)
i32 = ir.IntType(32)
i64 = ir.IntType(64)
void = ir.VoidType()
m = ir.Module()
fty = ir.FunctionType(void, [i32, i32, i32])
f = ir.Function(m, fty, "cmov_test")
entry = f.append_basic_block("entry")
bld = ir.IR... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.