content stringlengths 5 1.05M |
|---|
"""
Support for Harmony Hub devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/remote.harmony/
"""
import logging
from os import path
import urllib.parse
import voluptuous as vol
import homeassistant.components.remote as remote
import homeassistan... |
"""init
Revision ID: 2579e237c51a
Revises:
Create Date: 2019-11-11 15:20:33.685936
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2579e237c51a'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by A... |
import turtle
from draw_target import TARGET_LLEFT_X, TARGET_LLEFT_Y, TARGET_WIDTH
def check_print():
xcor = turtle.xcor()
ycor = turtle.ycor()
# Did it hit the target?
is_in_x = ((xcor >= TARGET_LLEFT_X) and
(xcor <= (TARGET_LLEFT_X + TARGET_WIDTH)))
is_in_y = ((ycor >= TARGET_LLEFT_Y) ... |
import sys
h, w = map(int, sys.stdin.readline().split())
canvas = (
["." * (w + 2)]
+ ["." + sys.stdin.readline().rstrip() + "." for _ in range(h)]
+ ["." * (w + 2)]
)
def main():
res = [[0] * (w + 1) for _ in range(h + 1)]
for i in range(1, h + 1):
for j in range(1, w + 1):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Dense, Activation, Bidirectional, LSTM, Reshape
from tensorflow.keras import backend as K
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, Lear... |
def setup_ntupler(process, cms, options):
print '=' * 60
print "Setting up NTupler"
print '=' * 60
######################################################################################################
################################## nTuple Configuration ##########################################... |
"""
Apply filters to data
SwA_{START}-{END}_proc1.nc -> SwA_{START}-{END}_proc2.nc
"""
import sys
import os
import numpy as np
import pandas as pd
import xarray as xr
from scipy.interpolate import interp1d
from dask.diagnostics import ProgressBar
from src.env import ICOS_FILE#, AEJ_FILES
from src.data.proc_env impo... |
from Dokra.utils import identity
from Dokra.wrapper import WrappedFunction, FunctionWrapper
class Dokra:
def __new__(cls, func=None, *args, **kwargs):
if not func:
return FunctionWrapper()
return Dokra.decorate(func)
@staticmethod
def decorate(func):
wrapped_annotatio... |
import numpy as np
import theano
from rllab.misc.ext import iterate_minibatches_generic
from rllab.misc import logger
from rllab.core.serializable import Serializable
from rllab.regressors.gaussian_conv_regressor import GaussianConvRegressor
from sandbox.ex2.parallel_trpo.conjugate_gradient_optimizer import ParallelCo... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli... |
import unittest
from descriptors.pattern_matching_descriptor import Cat
class TestPatternMatchingDescriptor(unittest.TestCase):
cat = Cat(4, "MEOW")
def test_cat_name(self):
self.assertEqual(self.cat.name, 4)
def test_cat_speak(self):
self.assertEqual(self.cat.speak, "MEOW")
if __name__ == '__main__':
unitt... |
'''
'''
# – -
# — -
# “ "
# ” "
# ‘ '
# ’ '
# – ; -
# — ; -
# “ ; "
# ” ; "
# ‘ ; '
# ’ ; '
# & &
import sys
import re
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus ... |
"""Shape detector utility file.
@description
Utility file for loading, processing, cleaning and manipulating
dataset. It also provides functional APIs for creating Sequence
generators.
@author
Victor I. Afolabi
Artificial Intelligence & Software Engineer.
Email: javafolabi@gmail.co... |
from apgl.graph.SparseGraph import SparseGraph
from apgl.graph.GeneralVertexList import GeneralVertexList
from apgl.graph.DenseGraph import DenseGraph
from apgl.graph.DictGraph import DictGraph
from apgl.graph.VertexList import VertexList
from apgl.graph.GraphUtils import GraphUtils
from apgl.graph.GraphStatistic... |
from player import Player
class Map:
def __init__(self, roads):
"""
:param roads: all the roads that connect two towers
:type roads: set
"""
self.roads = roads
def move(self, tower1, tower2):
"""
:param tower1: the source tower for the warr... |
import requests
from utils import loginFile, dataAnalysis
import os
import datetime
from dateutil.relativedelta import relativedelta
import json
from utils.logCls import Logger
dirpath = os.path.dirname(__file__)
cookieFile = f"{dirpath}/utils/cookies.txt"
dataFile = f"{dirpath}/datas"
class DevopsProject:
def... |
class Solution:
def findItinerary(self, tickets):
if not tickets:
return []
d = dict() #collections.defaultdict(list)
stack = []
def dfs(cur):
if cur not in d:
pass #print "cur->" + str(cur)
while cur in d and len(d[cur])>0:
... |
from dataclasses import dataclass
from datetime import datetime
from .base import MangadexBase
from .chapterlist import ChapterList
@dataclass(frozen=True)
class User(MangadexBase):
username: str = ''
levelId: int = None
joined: datetime = None
lastSeen: datetime = None
website: str = ''
biogr... |
"""
General device configuration.
"""
from .section import Config
class GeneralConfig(Config):
"""
Store information about the device that might not be relevant to a
particular application or might not be useful to the device itself.
"""
# pylint: disable=too-many-instance-attributes
__slots... |
import datetime
import gc
import json
import os
import shutil
import subprocess
import tempfile
import zipfile
from json.decoder import JSONDecodeError
from sys import exit as exit_ex
from tkinter.messagebox import (askyesno, askyesnocancel, showerror, showinfo,
showwarning)
from typing ... |
__all__ = ["join", "delete", "to_hans"]
def get_slot_val(para_item, slots, idx_slot_map):
if para_item.tp == "VAR":
return idx_slot_map[para_item.val]
return para_item.val
"""
join(seq, t1, t2, ...)
"""
def join(params, slots, idx_slot_map, context={}):
if len(params) <= 1: return
... |
#!/usr/bin/python
import json
import paho.mqtt.client as mqtt
from store_Sensor_Data_to_DB import sensor_Data_Handler
# MQTT Settings
MQTT_username = "mittsmarthjem"
MQTT_password = "mittsmarthjem"
MQTT_Broker = "10.0.0.1" #IP-address of Broker(Raspberry Pi)
MQTT_Port = 1883
Keep_Alive_Interval = 45
MQTT_Topic = "#"
... |
#
# This file is part of LUNA.
#
""" Simple utility constructs for LUNA. """
from nmigen import Module, Signal, Cat
from .cdc import synchronize
__all__ = [
'rising_edge_detected', 'falling_edge_detected', 'any_edge_detected',
'past_value_of', 'synchronize'
]
def _single_edge_detector(m, signal, *, domain, ... |
import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set... |
#This file creates the classifiers and makes predictions
# The difference between the createClassifiers and this file is:
# This uses pos-tagger of nltk to reduce the corpus of review and tips to
# contain only nouns and adjectives. This reduces the corpus size.
# Author: Pradeep Ravilla
from sklearn.feature_extractio... |
from svgwrite.extensions.shapes import rotate, scale, translate
import math
class TransformMixin:
"""
Apply transformations to self.points
"""
def rotate(self, delta):
"""
rotate this
"""
self.points = list(rotate(self.points, delta))
return
def scale(self,... |
import pygame
import Buttons
import Box
import Constants as CST
import Interface.ShipBuilder.Designer.Corvete as CorveteDesingner
import Interface.ShipBuilder.Designer.Destroyer as DestroyerDesingner
import Interface.ShipBuilder.Designer.Cruiser as CruiserDesingner
import Interface.ShipBuilder.Designer.Battleship as Ba... |
import re
import string
import nltk
nltk.data.path.append("./nltk_data/")
from nltk.stem import WordNetLemmatizer
from spellchecker import SpellChecker
from nltk.corpus import stopwords
PUNCT_TO_REMOVE = string.punctuation
PUNCT_TO_REMOVE += 'â’'
lemmatizer = WordNetLemmatizer()
spell = SpellChecker()
def remove_stop... |
# Generated by Django 3.0.5 on 2020-04-26 20:01
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("blog", "0005_auto_202003... |
from setuptools import setup, Extension
from pathlib import Path
this_directory = Path(__file__).parent
long_description = (this_directory / "README.md").read_text()
setup(
name='RAiSEHD',
version='0.0.10',
author = "Ross Turner",
author_email = "turner.rj@icloud.com",
description = ("RAiSE HD: La... |
import unittest
from BanditPAM import KMedoids
import pandas as pd
import numpy as np
def onFly(k, data, loss):
kmed_bpam = KMedoids(n_medoids=k, algorithm="BanditPAM")
kmed_naive = KMedoids(n_medoids=k, algorithm="naive")
kmed_bpam.fit(data, loss)
kmed_naive.fit(data, loss)
if (kmed_bpam.medoids... |
"""
Copyright 2017 Balwinder Sodhi
Licenced under MIT Licence as available here:
https://opensource.org/licenses/MIT
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.... |
from setuptools import setup
setup(name='sig2cli',
version='0.1.3',
description='Turn function signatures into Command Line Interfaces',
url='https://github.com/PaoloSarti/sig2cli',
author='Paolo Sarti',
author_email='paolo.sarti@gmail.com',
license='MIT',
packages=['sig2cli']... |
'''
Functions for drawing
'''
from . import charsets
from typing import List
from .params import PADDING
from .custom_types import Node, Offset
def draw_node(screen: list, text: str, left_bound: int, top_bound: int, box_width: int,
line_width: int, padding: int=PADDING, charset=charsets.Ascii):
'''
... |
#!/usr/bin/env python3
lookup = {
"ラジオトーク①": "Radio Talk 1",
"maiden voyage": "maiden voyage",
"木漏れ日": "Streaming Sunlight",
"帰還": "Return",
"黒い瞳": "Dark Eye",
"南へ": "To the South",
"風の碑": "Monument of Wind",
"zodiac": "zodiac",
"roll out": "roll out",
"煙突讃歌": "Chimney Hymn",
"いざ!": "Now!",
"さるをとる": "Catch the Monkey"... |
from functools import wraps
import numpy as np
import pythran_manual
code = """
def new_method(self, inp):
return pythran_func(self.freq, inp)
"""
def my_decor(func):
func_name = func.__name__
name_pythran_func = "__for_method__Transmitter__" + func_name
pythran_func = pythran_manual.__dict__[n... |
# coding: utf-8
from . import qywx
from . import ta
from . import io
from . import log
from . import echarts_plot
from . import fei_shu
from .echarts_plot import kline_pro, heat_map
from .log import create_logger
from .word_writer import WordWriter
from .corr import nmi_matrix
from .bar_generator import BarGenerator,... |
#!/usr/bin/env python3
#--------------------------------------------------------------------------
# SBXDec - Sequenced Box container Decoder
#
# Created: 03/03/2017
#
# Copyright (C) 2017 Marco Pontello - http://mark0.net/
#
# Licence:
# This program is free software: you can redistribute it and/or modify
# it under ... |
# ==============================================================================
# Copyright 2021 Technical University of Denmark
# Author: Nikolas Borrel-Jensen
#
# All Rights Reserved.
#
# Licensed under the MIT License.
# ==============================================================================
import os
impor... |
import setuptools
import versioneer
from setuptools.extension import Extension
from Cython.Build import cythonize
import numpy
with open("README.md", "r") as fh:
long_description = fh.read()
extensions = [
Extension("geoist.pfm._prism",
["geoist/pfm/_prism.pyx"],
include_dirs=[nump... |
# URL of your SONA system
sona_domain = 'https://ucla.sona-systems.com/'
# A file that includes your SONA username (on the 1st line) and password (on the 2nd line)
sona_credentials_file = 'sona_credentials.txt'
# Google calendar id (find it in your Calendar Settings -> Calendar ID)
# Make sure the keys in this dictio... |
"""
Description - Week 1 homework for 1mwtt program
Author - Cristina Tarantino
Date - July 2018
"""
from datetime import datetime
from random import randint
days_in_year = 365
# year leap. Source https://en.wikipedia.org/wiki/Year#Variation_in_the_length_of_the_year_and_the_day
days_in_year_leap = 365.2422
# 60 m... |
from reamber.sm.lists.SMBpmList import SMBpmList
from reamber.sm.lists.SMStopList import SMStopList
__all__ = ['SMBpmList', 'SMStopList']
|
class RemoveTransferEncodingHeaderMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
environ.pop("HTTP_TRANSFER_ENCODING", None)
return self.app(environ, start_response)
|
# coding=utf-8
"""
Filename: good_solution
Author: leicj
Date: 2020/4/1
Description: https://leetcode-cn.com/problems/remove-element/solution/python3-yi-chu-yuan-su-by-leicj/
"""
from typing import List
class Solution:
@staticmethod
def removeElement(nums: List[int], val: int) -> int:
"""
... |
from scipy.io import netcdf
import numpy as np
import numpy.matlib
tave = 900
basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/2nd_deriv/T1/'
basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/2nd_deriv/rho_scan2/r0.001/'
basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/fg_drive/r... |
#!/usr/bin/env python
from securitycenter import SecurityCenter5
from BeautifulSoup import BeautifulSoup
from csv import DictWriter
def builder(**kwargs):
report = kwargs['report'] # The CSV Report
sc = kwargs['sc'] # SecurityCenter
vulns = kwargs['resp'].json()['response']['results'] # The vuln data
... |
'''
Extracts info from the CLEAN logs in separate channels.
The path to the extract_from_log.py file should be changed.
The script expects the results are in individual channel folders, where each
contains ONLY 1 casa log file.
CALL:
python get_clean_results_template.py PATH_TO_CHANNELS CLEAN_results_file.csv
COMMON... |
from easyautoml.ftutils import get_train_data, get_test_data
from easyautoml.tpotutils import tpot_train, tpot_score
# GLOBAL CONFIG
TPOT_MAX_TIME_MINS = 1
TPOT_MAX_EVAL_TIME_MINS = 0.04
TPOT_POPULATION_SIZE = 40
N_JOBS=-1
def tpot_with_ft(
project,
train_file_name,
test_file_name,
submit_file,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Command line utility that accepts a word file and prints a dictionary of
anagrams for that file.
Module provides a function, find_anagrams(), which can be used to do the same
for an arbitrary list of strings.
"""
# Your name here, and any other people/sources who help... |
"""Checks for GitHub
Revision ID: cfe55041d49f
Revises: a760c9157e9e
Create Date: 2020-11-30 12:36:09.724628
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'cfe55041d49f'
down_revision = 'a760c9157e9e'
branch_labels = ... |
# Copyright (C) Yuki Takagi 2020
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# https://www.boost.org/LICENSE_1_0.txt)
from setuptools import setup
from setuptools import find_packages
from os import path
pkgdir = path.abspath(path.dirname(__file__))... |
"""color added
Revision ID: 3ac35a7fdc71
Revises: e96c9aa8081a
Create Date: 2019-04-25 17:06:18.233773
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3ac35a7fdc71'
down_revision = 'e96c9aa8081a'
branch_labels = None
depends_on = None
def upgrade():
# ##... |
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import debug
import design
from tech import spic... |
#!/usr/bin/env python
import unittest2 as unittest
import journalism
class TestColumns(unittest.TestCase):
def setUp(self):
self.rows = [
[1, 2, 'a'],
[2, 3, 'b'],
[None, 4, 'c']
]
self.column_names = ['one', 'two', 'three']
self.column_types = ... |
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
setup(
name='avanzapy',
# TODO Single source the version. Currently this has to be changed manually
# https://packaging.python.org/en/latest/single_source_version.html
version='0.0.2'... |
from PIL import Image
from argparse import ArgumentParser
import os
parser = ArgumentParser()
parser.add_argument("-d", "--dirctories", dest="source", nargs='+',
help="target file to save xml", metavar="INDIRS", required=True)
args = parser.parse_args()
for sourceid in range(len(args.source)):
i... |
class LockFilenameTimeout(Exception):
pass |
import sys
import math
from collections import defaultdict, deque
sys.setrecursionlimit(10 ** 6)
stdin = sys.stdin
INF = float('inf')
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().strip()
N = ni()
A = na()
ans = INF
for bit in range(1 << (N - 1)):
or_... |
import argparse
import csv
import os
import time
from core_data_modules.cleaners import Codes
from core_data_modules.traced_data import Metadata, TracedData
from core_data_modules.traced_data.io import TracedDataJsonIO, TracedDataCSVIO
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Joins... |
# author : Jelena Prokić <prokic@uni-marburg.de>
# created : 2013-11-02
# last update : 2013-12-15
"""
converts PAD original data format to qlc lingpy format
usage: pad2qlc.py ../sources/originaldata_corrected.csv ../doculects.csv
"""
import sys
import re
import unicodedata
from time import gmtime, localtime... |
#######################################################################
# Copyright (C) 2019-present, Blosc Development team <blosc@blosc.org>
# All rights reserved.
#
# This source code is licensed under a BSD-style license (found in the
# LICENSE file in the root directory of this source tree)
#######################... |
"""
"""
from MDSplus import *
import sys
s=int(sys.argv[1])
model_tree_num=-1
myTree=Tree("spectroscopy",model_tree_num)
myTree.createPulse(s)
myTree=Tree("spectroscopy",s,'Edit')
gpi_root="\SPECTROSCOPY::TOP.GPI_TCV"
myTree.addNode(gpi_root,"structure")
gpi_node=myTree.getNode(gpi_root)
gpi_node.addNode("APD_ARRAY",... |
import requests
import csv
import time
import boto3
import pandas as pd
import os
from datetime import datetime
from decimal import Decimal
# upload to DynamoDB
AWS_DB_REGION = 'us-west-2'
AWS_TABLE_NAME = 'yelp-restaurants'
AWS_PRIMARY_KEY = 'RestaurantID'
CSV_FILE = 'Yelp_Restaurants.csv'
CSV_HEAD = [AWS_PRIMARY_KEY... |
"""
This script demonstrates the implementation of the Sigmoid function.
The function takes a vector of K real numbers as input and then 1 / (1 + exp(-x)).
After through Sigmoid, the element of the vector mostly 0 between 1. or 1 between -1.
Script inspired from its corresponding Wikipedia article
https://en.w... |
# program to calculate the average from a list of numbers
# made by itsmeevil
def average(numList):
numList = numList.split(" ")
numList = list(map(float, numList))
return round(sum(numList) / len(numList), 2)
print("***Average Calculator***\n")
numList = input("Enter a list of numbers: ")
average = aver... |
import pytest, json
from src import encors
from http import HTTPStatus
@pytest.fixture
def client():
# setup testing client data
encors.app.config['TESTING'] = True
client = encors.app.test_client()
yield client
# clear testing client data before exit
# able to request at /
def test_smoketest(cl... |
import io
import requests
import json
import random
import time
import threading
from PIL import Image
from kollektiv5gui.util import config, logging
from json.decoder import JSONDecodeError
__lock = threading.Lock()
def __sendToApi(data):
"""
Classify an image using the API.
data needs to contain the by... |
"""<tt079.py
In the previous program, we looked at a technique involving lambda to pass
arguments to an event-handler function. In this program, we will look at a
different technique, called "currying".
ABOUT CURRY
In its very simplest sense, currying is a technique for using a function to
construct other function... |
## Check overlap with: from http://www.netinstructions.com/how-to-make-a-web-crawler-in-under-50-lines-of-python-code/ -->
## according to this : http://stackoverflow.com/questions/25127935/unicodeencodeerror-charmap-codec-cant-encode-character-problems
## you should type into console: chcp 65001
##
## redirects
#... |
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main():
...
def get_mode():
...
def get_key():
...
def translate_message():
...
if __name__ == "__main__":
main()
|
import os
import cv2
import tensorflow as tf
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# img = Image.open(os.path.join('images', '2007_000648' + '.jpg'))
img_raw = cv2.imread("1.jpg")
img_flt = img_raw.astype(np.float32) / 255
image = img_flt
# cv2.startWindowThread()
cv2.... |
"""
## NAME
buscar_autores.py
## VERSION
[1.0]
## AUTHOR
Jose Rodelmar Ocampo Luna <joserodelmar@gmail.com>
Daniela Goretti Castillo Leon <danigore22@gmail.com>
Zara Paulina Martinez Sanchez <zaram042001@gmail.com>
## DATE
03/12/2021
## DESCRIPTION
Mediante paso de argument... |
N = eval(input("Enter the start point N:\n"))
M = eval(input("Enter the end point M:\n"))
for i in range(N, M + 1):
n = str(i)
if n == n[::-1]:
prime = True
for j in range(2, i - 1):
if i % j == 0:
prime = False
if prime:
print(i) |
from urllib import quote_plus as quote
from django.utils import unittest
from django.test.client import Client
from board.models import Post
USERNAME = "paul"
PASSWORD = "paulpaul"
API_URL = "/api/1.0"
class APITest(unittest.TestCase):
def setUp(self):
self.client = Client()
self.client.login(u... |
from model.account import Account
from google.appengine.ext import ndb
from taskutils import task
import logging
def MakeAccountsExperiment():
def Go():
@task(includeheaders=True)
def MakeAccounts(numaccounts, headers):
logging.debug(headers)
logging.debug(numaccounts)
... |
# Time: O(h)
# Space: O(1)
# 270
# Given a non-empty binary search tree and a target value, find the value in the BST that is
# closest to the target.
#
# Note:
# - Given target value is a floating point.
# - You are guaranteed to have only one unique value in the BST that is closest to the target.
# Definition for ... |
# -*- coding: utf-8 -*-
import os
from django.db import models, migrations
import csv
def migration_open(fn):
p = os.path.join(
os.path.dirname(__file__),
fn)
return open(p, encoding="utf-8")
def dodaj_dane_typow_pbn(apps, schema_editor):
Charakter_PBN = apps.get_model("bpp", "Charakter_... |
# coding=utf-8
from babelfish import LanguageReverseConverter
from subliminal.exceptions import ConfigurationError
from subzero.language import Language
# alpha3 codes extracted from `https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes`
# Subscene language list extracted from it's upload form
from_subscene = {
... |
#####################################################
# Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2021.06 #
#####################################################
import random
class BatchSampler:
"""A batch sampler used for single machine training."""
def __init__(self, dataset, batch, steps):
self._... |
from simple_rl.mdp.MDPClass import MDP
from simple_rl.mdp.StateClass import State
from simple_rl.abstraction.action_abs.OptionClass import Option
from simple_rl.abstraction.action_abs.PredicateClass import Predicate
from simple_rl.planning.ValueIterationClass import ValueIteration
from planning.OptionsMDPValueIteratio... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'encoder-widget2.ui'
#
# Created by: PyQt5 UI code generator 5.12.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DeenEncoderWidget(object):
def setupUi(self, DeenEncoderWi... |
"""
Programming for linguists
Implementation of the Reverse Polish Notation Converter
"""
from algorithms.calculator.reverse_polish_notation import (Digit, Op, ReversePolishNotation)
from data_structures.queue_ import Queue_
from data_structures.stack import Stack
class ReversePolishNotationConverterState:
"""
... |
import time
import numpy as np
import pandas as pd
import networkx as nx
from tqdm import tqdm
from scipy import sparse
from helpers import sampling, simple_print
from sklearn.decomposition import NMF
class BoostedFactorization:
"""
LENS-NMF boosted matrix factorization model.
"""
def __init__(self, r... |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.progressbar import ProgressBar
from kivy.uix.dropdown import DropDown
from kivy.uix.textinput ... |
# coding: utf-8
from django.conf.urls.defaults import patterns
urlpatterns = patterns('xpsite.views',
)
|
''' Writing functions in Python '''
def say_hello() :
''' Function with no return '''
print("Hello!")
def add_ten(xparm) :
''' Function that returns a value '''
return xparm + 10
def add_twenty(xparm) :
''' Function that modifies a parameter '''
xparm = xparm + 20
def add_array(arr) :
''... |
#!/usr/bin/python
#coding=utf-8
'''自动爬取momentum每天的图片,并保存'''
import os
import json
import urllib2
import urllib
import time
def auto_down(url, filename):
try:
urllib.urlretrieve(url, filename)
except urllib.ContentTooShortError:
print 'Network conditions is not good.... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
import pytest
import swapper
from django.utils.encoding import force_text
@pytest.yield_fixture
def pages():
PAGES = (
'/this/is/a/test/',
'/this/is/a',
'/this/is/',
'/this/',
'/te... |
# Copyright 2021 Huawei Technologies Co., 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 applicable law or agreed to... |
"""
Tools for finding graph homomorphisms and cores.
Loads a Cython module for the actual search routines.
This module itself contains mostly auxiliary tools:
* Conversion Graph <-> raw CGraph
* Heuristics for branching order
* Finding and verifying homomorphism cores
"""
import logging
from random import shuffle
fr... |
import click
import dataset as dataset_lib
import requests
from datetime import datetime, timedelta
db = dataset_lib.connect("sqlite:///orchestrator.db")
EXCLUDED_PATTERNS = [
"resources/donnees-temps-reel-de-mesure-des-concentrations-de-polluants-atmospheriques-reglementes-1",
"files.data.gouv.fr/lcsqa/conc... |
#!/usr/bin/env python
from PIL import ImageGrab
import sys
import os.path
def main():
ofile = sys.argv[1]
im = ImageGrab.grabclipboard()
filename_ext = os.path.splitext(ofile)
dirpath = os.path.dirname(ofile)
if dirpath and not os.path.exists(dirpath):
os.makedirs(dirpath)
im.save(... |
import setuptools
from kkcoding import __version__
setuptools.setup(
name='kkcoding',
version=__version__,
author='汪心禾',
author_email='wangxinhe06@gmail.com',
description='Command-line Interface for KKCoding.net',
long_description=open('README.md').read(),
long_description_content_type='t... |
import string, copy
#import time
import os, os.path#, shutil
import sys
import numpy
#from PyQt4.QtCore import *
#from PyQt4.QtGui import *
import operator
import numpy as np
import re
os.chdir('K:\users\helge.stein\scripts-dev\JCAPDataProcess-master\AuxPrograms')
projectroot=os.path.split(os.getcwd())[0]
sys.path.appe... |
from __future__ import absolute_import, division, print_function, unicode_literals
from nose.tools import eq_
from smarkets.functools import always_return, memoized
def test_memoized():
@memoized
def my_sum(x, y):
counter[0] += 1
return x + y
counter = [0]
eq_(my_sum(1, 2), 3)
e... |
from flask import Flask
from contactista.models import db, alembic, security
from contactista.models import shell_context as shell_context_models
from contactista.models.auth import user_datastore
from contactista.serializers import shell_context as shell_context_serializers
from contactista.views.api import blueprint ... |
import torch
import kilonerf_cuda
from utils import PerfMonitor, ConfigManager
from run_nerf_helpers import get_rays, replace_transparency_by_background_color
class FastKiloNeRFRenderer():
def __init__(self, c2w, intrinsics, background_color, occupancy_grid, multi_network, domain_mins, domain_maxs,
white_... |
import configparser
import os
CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
ACCESS_TOKEN = "access_token"
REFRESH_TOKEN = "refresh_token"
EXPIRES_AT = "expires_at"
PATH = "settings.ini"
SECTION_SETTINGS = "Settings"
def create_config(path=PATH):
config = configparser.ConfigParser()
config.add_sec... |
import numpy as np
import random
def gen_rand_matrix(n, m, is_invertible=False, finite_field=521):
"""
Generates a random n x m matrix, with an optional flag for
invertible matrices (even though it's rare to randomnly generate
a singular matrix).
"""
if is_invertible:
return gen_nonsin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.