content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python # coding=utf8 import logging from logging import NullHandler logging.getLogger(__name__).addHandler(NullHandler())
python
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) dp = [0 for _ in range(n)] dp[-1] = cost[-1] dp[-2] = cost[-2] for i in range(n - 3, -1, -1): dp[i] = cost[i] + min(dp[i + 1], dp[i + 2]) return min(dp[0], dp[1])
python
from zipfile import ZipFile import zipfile import wget import os import subprocess import pycountry # define variables path = '/path/ipvanish/' url = 'https://www.ipvanish.com/software/configs/configs.zip' filename = path + '/' + os.path.basename(url) best_ping = 99999 # get user's choice def get_choice(): print(...
python
from django.contrib import admin from .models import ( Payment, PaymentChoice ) admin.site.register(Payment) admin.site.register(PaymentChoice)
python
from gym_connect_four.envs.connect_four_env import ConnectFourEnv, ResultType
python
import requests def coords_to_divisions(lat, lng): url = f"https://v3.openstates.org/divisions.geo?lat={lat}&lng={lng}" try: data = requests.get(url).json() return [d["id"] for d in data["divisions"]] except Exception: # be very resilient return []
python
# Generated by Django 2.0.7 on 2018-10-25 11:18 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hivs_cd', '0011_add_field_condomdistribution_purpose'), ] operations = [ migrations.AlterField( ...
python
#!/home/bryanfeeney/anaconda3/bin/python3.6 # # Simple script that uses the Microsoft Light Gradient-Boosted Machine-Learnign # toolkit to make predictions *separately* for each value. # from datetime import date, timedelta, datetime import pandas as pd import numpy as np from sklearn.metrics import mean_squared_err...
python
__source__ = 'https://leetcode.com/problems/intersection-of-two-linked-lists/' # https://github.com/kamyu104/LeetCode/blob/master/Python/intersection-of-two-linked-lists.py # Time: O(m + n) # Space: O(1) # LinkedList # # Description: Leetcode # 160. Intersection of Two Linked Lists # # Write a program to find the node...
python
# Generated by Django 2.2.10 on 2020-08-23 11:08 from django.db import migrations, models import django.db.models.deletion import event.enums class Migration(migrations.Migration): dependencies = [("event", "0016_attachment_type")] operations = [ migrations.CreateModel( name="Schedule",...
python
#!/usr/bin/env python #-*- coding:utf-8 -*- """ Created on Mar 1, 2020 @author: Chengning Zhang """ import warnings warnings.filterwarnings("ignore") def get_cv(cls,X,Y,M,n_splits=10,cv_type = "StratifiedKFold",verbose = True): """ Cross validation to get CLL and accuracy and training time and precision and recall...
python
#!/usr/bin/env python # # Public Domain 2014-2016 MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as ...
python
from time import sleep from progress.bar import Bar with Bar('Processing...') as bar: for i in range(100): sleep(0.02) bar.next()
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, with_statement, unicode_literals ) class DataObj: def __init__(self, str, *args, **kwargs): self.docs = None self.span = None str = self.preprocess(str) def prep...
python
import pygame import time class Clock: def __init__(self, profile: int, turbo: bool): self.cycle = 0 self.frame = 0 self.pyclock = pygame.time.Clock() self.start = time.time() self.profile = profile self.turbo = turbo def tick(self) -> bool: self.cycle ...
python
from cascade_at.core.log import get_loggers LOG = get_loggers(__name__) class InputDataError(Exception): """These are errors that result from faults in the input data.""" class SettingsError(InputDataError): def __init__(self, message, form_errors=None, form_data=None): super().__init__(message) ...
python
import logging from pipelines.plugin.base_plugin import BasePlugin from pipelines.plugin.exceptions import PluginError from pipelines.plugin.utils import class_name log = logging.getLogger('pipelines') class PluginManager(): def __init__(self): self.plugins = {} def get_plugin(self, name): ...
python
import json import os from typing import List, Optional from dkron_python.api import Dkron, DkronException import typer app = typer.Typer() get = typer.Typer(help="Fetch information about a resource") apply = typer.Typer(help="Apply a resource") delete = typer.Typer(help="Delete a resource") app.add_typer(get, name="g...
python
class ServiceProvider(): wsgi = True def __init__(self): self.app = None def boot(self): pass def register(self): self.app.bind('Request', object) def load_app(self, app): self.app = app return self
python
from dynabuffers.api.ISerializable import ISerializable, ByteBuffer from dynabuffers.ast.ClassType import ClassType from dynabuffers.ast.EnumType import EnumType from dynabuffers.ast.UnionType import UnionType from dynabuffers.ast.annotation.GreaterEquals import GreaterEquals from dynabuffers.ast.annotation.GreaterThan...
python
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\sims\suntan\suntan_ops.py # Compiled at: 2019-05-09 01:16:48 # Size of source mod 2**32: 1473 bytes ...
python
from avatar2 import QemuTarget from avatar2 import MemoryRange from avatar2 import Avatar from avatar2.archs import ARM from avatar2.targets import Target, TargetStates from avatar2.message import * import tempfile import os import time import intervaltree import logging from nose.tools import * QEMU_EXECUTABLE = ...
python
""" This module contains our unit and functional tests for the "think_aloud" application. """ # Create your tests here.
python
"""Database objects.""" import sqlalchemy from collections import Mapping from sqlalchemy.engine.url import make_url from sqlalchemy.event import listen from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session from sqlalchemy.orm.session import sessionmaker from .exceptions im...
python
def find_next_square(sq):
python
#!/usr/bin/python3.7 ######################################################################################## # pvt_collector/tedlar.py - Represents an tedlar layer within a PVT panel. # # Author: Ben Winchester # Copyright: Ben Winchester, 2021 ##########################################################################...
python
import time import random from const import * from util.logger import logger class Session(): def __init__(self): # requests.adapters.DEFAULT_RETRIES = 5 # 增加重試次數,避免連線失效 self.has_login = False self.session = requests.Session() self.session.headers = { 'User-Agent': make...
python
# Requests may need to be installed for this script to work import requests import re import config # Here we pass our client id and secret token auth = requests.auth.HTTPBasicAuth(config.client_id, config.secret_token) # Here we pass our login method (password), username, and password data = {'grant_type': 'password...
python
""" # ============================================================================= # Simulating the double pendulum using Runge–Kutta method (RK4) # ============================================================================= Created on Fri Jul 17 2020 @author: Ahmed Alkharusi """ import numpy as np import ...
python
from __future__ import annotations from datetime import date from typing import ( Literal, Optional, Sequence, ) from pydantic.fields import Field from pydantic.types import StrictBool from ..api import ( BodyParams, EndpointData, Methods, WrApiQueryParams, ) from ..types_.endpoint import...
python
import datetime as _datetime import os import random import string import inflect import six from . import mock_random inflectify = inflect.engine() def _slugify(string): """ This is not as good as a proper slugification function, but the input space is limited >>> _slugify("beets")...
python
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet import reactor from twisted.web import proxy, server site = server.Site(proxy.ReverseProxyResource('www.yahoo.com', 80, '')) reactor.listenTCP(8080, site) reactor.run()
python
from torch.optim.lr_scheduler import LambdaLR def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): """ Create a schedule with a learning rate that decreases linearly after linearly increasing during a warmup period. """ def lr_lambda(current_step): ...
python
# Copyright (c) 2019-2021, Jonas Eschle, Jim Pivarski, Eduardo Rodrigues, and Henry Schreiner. # # Distributed under the 3-clause BSD license, see accompanying file LICENSE # or https://github.com/scikit-hep/vector for details. import pytest import vector ak = pytest.importorskip("awkward") numba = pytest.importorsk...
python
import socket #for sockets import sys #for exit # create dgram udp socket try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error: print('Failed to create socket') sys.exit() HOST = '' # Symbolic name meaning all available interfaces PORT = 6000 # Arbitrary non-privileged por...
python
# Copyright (c) 2018 Sony Pictures Imageworks 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...
python
#!/usr/bin/env python3 # # Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center # Distributed under the terms of the 3-clause BSD License. import time import unittest from ipykernel.tests.utils import execute, wait_for_idle from sos_notebook.test_utils import flush_channels, sos_kernel, Noteboo...
python
"""Base method for all global interpretations. Is a subclass of base ModelInterpreter""" from ..model_interpreter import ModelInterpreter class BaseGlobalInterpretation(ModelInterpreter): """Base class for global model interpretations""" pass
python
import json import unittest from pyshared.server.ref import CallCommand from pyshared.server.ref import DelCommand from pyshared.server.ref import ListCommand from pyshared.server.ref import LocalSharedResourcesManager from pyshared.server.ref import SetCommand from pyshared.server.ref import default_command_mapper fr...
python
from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class RightBoard: def __init__(self, driver): self.driver = driver self.elements = RightBoardElements(self.driver) def click(self, elem): self.driver.execute_script( "arguments[0].c...
python
import threading import time import signal import sys from callbacks_event_listener import EventListener from wpwithin_python import WPWithin,\ PricePerUnit,\ Price,\ Service,\ CommonPSPKeys,\ ...
python
from django.urls import path, include urlpatterns = [ path('', include('accounts.urls.accounts')), path('', include('accounts.urls.employers')), path('', include('accounts.urls.professionals')), ]
python
from django.shortcuts import render from django.http import HttpResponse from notice.models import Notice, Qna from main.models import search_word from django.views.generic import ListView from django.db.models import Q from django.utils import timezone import datetime def main(request): # Main_Notice = Notice.ob...
python
import json from django import template register = template.Library() @register.filter def here(page, request): return request.path.startswith(page.get_absolute_url()) @register.simple_tag def node_module(path): return '/node_modules/{}'.format(path) @register.assignment_tag(takes_context=True) def navi...
python
from django.db import models from django.contrib.auth.models import User from pyuploadcare.dj.models import ImageField # Create your models here. class Neighborhood(models.Model): name = models.CharField(max_length=100) location = models.CharField(max_length=100) admin = models.ForeignKey("Profile", on_del...
python
## # Copyright © 2020, The Gust Framework Authors. All rights reserved. # # The Gust/Elide framework and tools, and all associated source or object computer code, except where otherwise noted, # are licensed under the Zero Prosperity license, which is enclosed in this repository, in the file LICENSE.txt. Use of # this ...
python
#!/usr/bin/env python3 import sys from os import path sys.path.insert(0, path.join(path.dirname(__file__))) from importers.monzo_debit import Importer as monzo_debit_importer from beancount.ingest import extract account_id = "acc_yourMonzoAccountId" account = "Assets:Monzo:Something" CONFIG = [ monzo_debit_impo...
python
import os import sys import tensorflow as tf from absl import app, logging from absl.flags import argparse_flags import _jsonnet def parse_args(args, parser): # Parse command line arguments parser = parser if parser else argparse_flags.ArgumentParser() parser.add_argument("input", type=str) # Name of T...
python
import logging from typing import Any, List, Optional from homeassistant.components.select import SelectEntity from gehomesdk import ErdCodeType from ...devices import ApplianceApi from .ge_erd_entity import GeErdEntity from .options_converter import OptionsConverter _LOGGER = logging.getLogger(__name__) class G...
python
import webbrowser def open_page(url: str, new: int = 0, autoraise: bool = True): webbrowser.open(url, new=new, autoraise=autoraise) actions = {'open webpage': open_page}
python
def util(node,visited,recstack): visited[node]=True recstack[node]=True for i in graph[node]: if visited[i]==False: if util(i,visited,recstack): return True elif recstack[i]==True: return True recstack[node]=False return False de...
python
#!/usr/bin/env python """ @package mi.dataset.parser.test @file marine-integrations/mi/dataset/parser/test/test_adcpt_m_log9.py @author Tapana Gupta @brief Test code for adcpt_m_log9 data parser Files used for testing: ADCPT_M_LOG9_simple.txt File contains 25 valid data records ADCPT_M_LOG9_large.txt File conta...
python
# Inspired by ABingo: www.bingocardcreator.com/abingo HANDY_Z_SCORE_CHEATSHEET = ( (1, float('-Inf')), (0.10, 1.29), (0.05, 1.65), (0.025, 1.96), (0.01, 2.33), (0.001, 3.08))[::-1] PERCENTAGES = {0.10: '90%', 0.05: '95%', 0.01: '99%', 0.001: '99.9%'} DESCRIPTION_IN_WORDS = {0.10: 'fairly conf...
python
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from past.utils import old_div import rlpy import numpy as np from hyperopt import hp param_space =...
python
import os from jobControl import jobControl from pyspark.sql import SparkSession from pyspark.sql import functions as f from pyspark.sql.types import IntegerType, StringType from utils import arg_utils, dataframe_utils job_args = arg_utils.get_job_args() job_name = os.path.basename(__file__).split(".")[0] num_partiti...
python
from fontbakery.checkrunner import Section from fontbakery.fonts_spec import spec_factory def check_filter(item_type, item_id, item): # Filter out external tool checks for testing purposes. if item_type == "check" and item_id in ( "com.google.fonts/check/035", # ftxvalidator "com.google.fonts/check/0...
python
# Generated by Django 3.2.5 on 2021-07-18 12:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('src', '0006_auto_20210718_1014'), ] operations = [ migrations.AddField( model_name='job', name='delivery_address', ...
python
"""fix Contact's name constraint Revision ID: 41414dd03c5e Revises: 508756c1b8b3 Create Date: 2021-11-26 20:42:31.599524 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '41414dd03c5e' down_revision = '508756c1b8b3' branch_labels = None depends_on = None def u...
python
#/usr/bin/env python import sys import logging logger = logging.getLogger('utility_to_osm.ssr2.git_diff') import utility_to_osm.file_util as file_util from osmapis_stedsnr import OSMstedsnr if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) # diff is called by git with 7 parameters: ...
python
# THIS FILE IS GENERATED FROM SIGPROFILEMATRIXGENERATOR SETUP.PY short_version = '1.1.0' version = '1.1.0'
python
from gym_minigrid.minigrid import * from gym_minigrid.register import register class WarehouseSortEnv(MiniGridEnv): """ Environment with a door and key, sparse reward """ def __init__(self, size=8): super().__init__( grid_size=size, max_steps=10*size*size ) ...
python
"""Plot road network """ import os import cartopy.crs as ccrs import geopandas import matplotlib.patches as mpatches import matplotlib.pyplot as plt from atra.utils import load_config, get_axes, plot_basemap, scale_bar, plot_basemap_labels, save_fig def main(config): """Read shapes, plot map """ data_p...
python
import torch import torch.nn as nn from utils.util import count_parameters class Embedding(nn.Module): """A conditional RNN decoder with attention.""" def __init__(self, input_size, emb_size, dropout=0.0, norm=False): super(Embedding, self).__init__() self.embedding = nn.Embedding(input_s...
python
class FileReader(object): def read(self, file): with open(file) as f: return f.read() def read_lines(self, file): lines = [] with open(file) as f: for line in f: lines.append(line) return lines
python
from locust import HttpUser, task from locust import User import tensorflow as tf from locust.contrib.fasthttp import FastHttpUser def read_image(file_name, resize=True): img = tf.io.read_file(filename=file_name) img = tf.io.decode_image(img) if resize: img = tf.image.resize(img, [224, 224]) r...
python
# coding=utf-8 import unittest import urllib2 import zipfile import random from tempfile import NamedTemporaryFile from StringIO import StringIO from . import EPUB try: import lxml.etree as ET except ImportError: import xml.etree.ElementTree as ET class EpubTests(unittest.TestCase): def setUp(self): ...
python
"""Collection of Object.""" import sqlite3 class Connection(sqlite3.Connection): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.execute('pragma foreign_keys=1') class CustomCommand: """Object for custom command.""" __slots__ = ( "id", "type...
python
import networkx as nx import numpy as np import sys from scipy.io import mmread from scipy.sparse import coo_matrix np.set_printoptions(threshold=sys.maxsize) if len(sys.argv) != 2: print("Usage: python3 ./hits.py <file.mtx>") exit() graph_coo = mmread(sys.argv[1]) print("Loading COO matrix") print(graph_coo....
python
import pickle from typing import Any, Union from datetime import datetime class DataStorage: _DataStorageObj = None def __new__(cls, *args, **kwargs): if cls._DataStorageObj is None: cls._DataStorageObj = super().__new__(cls) return cls._DataStorageObj def __init__(self): ...
python
class discord: Colour = None class datetime: datetime = None
python
import math import os def activator(data, train_x, sigma): #data = [p, q] #train_x = [3, 5] distance = 0 for i in range(len(data)): #0 -> 1 distance += math.pow(data[i] - train_x[i], 2) # 計算 D() 函式 return math.exp(- distance / (math.pow(sigma, 2))) # 最後返回 W() 函式 def grnn(data, train_x, train_y, ...
python
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,line-too-long from unittest import mock import os import pytest from eze.plugins.tools.checkmarx_kics import KicsTool from eze.utils.io import create_tempfile_path from tests.plugins.tools.tool_helper import ToolMetaTestBase ...
python
"""Simple templating engine. See `TemplateEngine` class.""" import os import re import inspect __all__ = ['TemplateEngine', 'TemplateSyntaxError', 'annotate_block'] class TemplateEngine: """Simple templating engine. WARNING: do NOT use this engine with templates from untrusted sources. Expressions in th...
python
from rdkit import Chem from rdkit.ML.Descriptors import MoleculeDescriptors from rdkit.Chem import Descriptors from padelpy import from_smiles import re import time nms=[x[0] for x in Descriptors._descList] print('\n') calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms) f=open('/scratch/woon/b3lyp_2017/datas...
python
from torch import randn from torch.nn import Linear from backpack import extend def data_linear(device="cpu"): N, D1, D2 = 100, 64, 256 X = randn(N, D1, requires_grad=True, device=device) linear = extend(Linear(D1, D2).to(device=device)) out = linear(X) vin = randn(N, D2, device=device) vou...
python
# -*- coding: utf-8 -*- import logging from pathlib import Path import yaml logger = logging.getLogger(__name__) def recursive_update(original_dict: dict, new_dict: dict) -> dict: """Recursively update original_dict with new_dict""" for new_key, new_value in new_dict.items(): if isinstance(new_valu...
python
# Generated by Django 3.2.6 on 2021-11-29 00:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kube', '0003_auto_20210917_0032'), ] operations = [ migrations.RemoveField( model_name='kubecluster', name='type', )...
python
import json from flask import make_response from marshmallow import fields, Schema, post_load, EXCLUDE from flask_apispec.utils import Ref from flask_apispec.views import MethodResource from flask_apispec import doc, use_kwargs, marshal_with # All the following schemas are set with unknown = EXCLUDE # because part ...
python
from abc import ABC, abstractmethod import itertools import numpy as np import matplotlib.pyplot as plt import tqdm from . import _heatmap from . import preprocessing class Regressor(ABC): ''' Mix-in class for Regression models. ''' @abstractmethod def get_output(self): ''' Retu...
python
from __future__ import absolute_import, print_function import pytest from steam_friends import app from steam_friends.views import api, auth, main def test_app(flask_app): assert flask_app.debug is False # todo: should this be True? assert flask_app.secret_key assert flask_app.testing is True asser...
python
# from classify.data.loaders.snli import SNLIDataLoader # __all__ = ["SNLIDataLoader"]
python
import numpy as np class InvertedPendulum: def __init__(self, length, mass, gravity=9.81): self.length = length self.mass = mass self.gravity = gravity # matrices of the linearized system self.A = np.array([[0, 1, 0, 0], [gravity/length, 0, 0, 0]...
python
class Base: @property def id(self): return self._id def __repr__(self): return '({} {})'.format(self.__class__.__name__, self.id) def __unicode__(self): return u'({} {})'.format(self.__class__.__name__, self.id) def __eq__(self, other): return self.id == other.id ...
python
# from DETR main.py with modifications. import argparse import datetime import json import random import time from pathlib import Path import math import sys from PIL import Image import requests import matplotlib.pyplot as plt import numpy as np from torch.utils.data import DataLoader, DistributedSampler import torc...
python
# Generated by Django 2.1.2 on 2018-12-05 14:28 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("barriers", "0020_auto_20181025_1545")] operations = [ migrations.RemoveField(model_name="barriercontributor", name="barr...
python
#special thanks to this solution from: #https://stackoverflow.com/questions/40237952/get-scrapy-crawler-output-results-in-script-file-function #https://stackoverflow.com/questions/41495052/scrapy-reactor-not-restartable from scrapy import signals from scrapy.signalmanager import dispatcher from twisted.internet import...
python
# -*- coding: utf-8 -*- """Helper module to work with files.""" import fnmatch import logging import os import re from stat import S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR # pylint: disable=redefined-builtin from ._exceptions import FileNotFoundError MAXLEN = 120 ILEGAL = r'<>:"/\|?*' LOGGER = logging.ge...
python
from numpy import dtype db_spec = True try: import sqlalchemy.types as sqlt except: db_spec = False return_keys = [ 'id', 'created_at', 'number', 'total_price', 'subtotal_price', 'total_weight', 'total_tax', 'total_discounts', 'total_line_items_price', 'name', 'tota...
python
from setuptools import find_packages, setup setup( name='serverlessworkflow_sdk', packages=find_packages(include=['serverlessworkflow_sdk']), version='0.1.0', description='Serverless Workflow Specification - Python SDK', author='Serverless Workflow Contributors', license='http://www.apache.org/l...
python
#!/usr/bin/env python3 # coding: utf-8 # PSMN: $Id: 02.py 1.3 $ # SPDX-License-Identifier: CECILL-B OR BSD-2-Clause """ https://github.com/OpenClassrooms-Student-Center/demarrez_votre_projet_avec_python/ Bonus 1, json """ import json import random def read_values_from_json(fichier, key): """ create an new em...
python
# encoding: utf8 from pygubu import BuilderObject, register_custom_property, register_widget from pygubu.widgets.pathchooserinput import PathChooserInput class PathChooserInputBuilder(BuilderObject): class_ = PathChooserInput OPTIONS_CUSTOM = ('type', 'path', 'image', 'textvariable', 'state', ...
python
""" Anserini: A toolkit for reproducible information retrieval research built on Lucene 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 a...
python
from picamera import PiCamera from time import sleep def record_video(sec): pi_cam = PiCamera() pi_cam.start_preview() pi_cam.start_recording('./video.mp4') sleep(sec) pi_cam.stop_recording() pi_cam.stop_preview() record_video(5)
python
import logging from hearthstone.enums import CardType, Zone, GameTag from hslog import LogParser, packets from hslog.export import EntityTreeExporter from entity.game_entity import GameEntity from entity.hero_entity import HeroEntity from entity.spell_entity import SpellEntity # import entity.cards as ecards logger =...
python
''' Train all cort models Usage: train_all.py [--num_processes=<n>] --type=<t> <consolidated_conll_dir> <out_dir> ''' import os from cort.core.corpora import Corpus import codecs import random import subprocess from cort_driver import train from joblib import Parallel, delayed import sys import itertools from doco...
python
""" Yoga style module """ from enum import Enum from typing import List class YogaStyle(Enum): """ Yoga style enum """ undefined = 0 hatha = 1 yin = 2 chair = 3 def get_all_yoga_styles() -> List[YogaStyle]: """ Returns a list of all yoga styles in the enum """ return [YogaStyle.hatha, Yo...
python
#!/usr/bin/python import os import sys import argparse from collections import defaultdict import re import fileUtils def isBegining(line): m = re.match(r'^[A-Za-z]+.*', line) return True if m else False def isEnd(line): return True if line.startswith('#end') else False def getItem(item): m = re...
python
import speech_recognition as sr import pyaudio #optional # get audio from the microphone while True: #this loop runs the below code infinite times until any inturrupt is generated r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) print...
python
from django.conf.urls import url from django.urls import path from . import views from . import dal_views from .models import * app_name = 'vocabs' urlpatterns = [ url( r'^altname-autocomplete/$', dal_views.AlternativeNameAC.as_view( model=AlternativeName,), name='altname-autocomplete'...
python
from dancerl.models.base import CreateCNN,CreateMLP import torch.nn as nn if __name__ == '__main__': mlp=CreateMLP(model_config=[[4,32,nn.ReLU()], [32,64,nn.ReLU()], [64,3,nn.Identity()]]) print(mlp) cnn=CreateCNN(model_config=[[4,32,3,2,1,n...
python