content stringlengths 5 1.05M |
|---|
import threading
import inspect
import secs
class SecsCommunicatorError(Exception):
def __init__(self, msg):
super(SecsCommunicatorError, self).__init__(msg)
def __str__(self):
return repr(self)
class SecsWithReferenceMessageError(SecsCommunicatorError):
def __init__(self, msg, ref_ms... |
# -*- coding: utf-8 -*-
"""
create on 2019-03-20 04:16
author @lilia
"""
from sklearn.ensemble import RandomForestClassifier
from analysis_llt.ml.cv.base import BaseCV
class RandomForestClassifierCV(BaseCV):
def __init__(self, n_estimators='warn', criterion='gini', max_depth=None, min_samples_split=1.0, cv=None... |
from harmony_tools.cli.abc.category import BaseCategory
from harmony_tools.cli.categories.notes import (
random,
)
class Category(BaseCategory):
name = 'notes'
help = 'note tools'
def get_commands(self):
return [
random.Command(self),
]
|
from django.conf.urls import url
from web.views import index,cart,orders,vip
urlpatterns = [
# 前台首页
url(r'^$', index.index, name="index"), #商城首页
url(r'^list$', index.lists, name="list"),# 商品列表
url(r'^list/(?P<pIndex>[0-9]+)$',index.lists,name="list"), #分页商品列表展示
url(r'^detail/(?P<gid>[0-9]+)$', ind... |
from collections import defaultdict
class Santa():
def __init__(self, houses):
self.x = 0
self.y = 0
self.houses = houses
self.houses[(self.x, self.y)] += 1
def move(self, char):
if char == "<":
self.x -= 1
elif char == "^":
self.y -= 1
elif char == ">":
self.x += 1
elif char == "v":
s... |
MAP_SIZE = 15
def print_func(str_p):
str1=''
str2=''
str3=''
str4=''
if len(str_p)>10:
str1=str_p[:10] + '| '
if len(str_p)>20:
str2=str_p[10:20] + '| '
if len(str_p)>30:
str3=str_p[20:30] + '| '
if len(str_p)>40:
... |
import collections
Instruction = collections.namedtuple('Instruction', 'name argument')
file = open('./input.txt', 'r')
string = file.read()
lines = string.split('\n')
# acc increase accumulator
# jmp jumps to relative instruction
# nop No Operation
# acc -99
# nop +0
# jmp +4
def parse_lines(line):
i = line.spl... |
import os
import sys
def process(input_file, output_file):
output_text = ""
if input_file.endswith("abstract.summary.txt") or input_file.endswith("community.summary.txt") or input_file.endswith("combined.summary.txt") or input_file.endswith("human.summary.txt"):
input_text = []
with open(input_... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import ListView, FormView
from pythons_core.view_mixins import GroupRequiredMixin
from .forms import PythonCreateForm, FilterForm
from .models im... |
# TREC Question classifier
# Dataset : https://cogcomp.seas.upenn.edu/Data/QA/QC/
# Report : https://nlp.stanford.edu/courses/cs224n/2010/reports/olalerew.pdf
# Method: Used SVM to classify the questions
# Code: https://github.com/amankedia/Question-Classification/blob/master/Question%20Classifier.ipynb
import pandas... |
"""
Networks have various basic characteristics beyond the number of nodes and
edges that are useful for analyzing a graph. For example, the degree of a node
is the number of edges that start (or end) at that node. A higher degree
indicates that the node is better connected to the rest of the network.
This module illu... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 11 12:09:52 2018
@author: shivap
"""
import numpy as np
from tqdm import tqdm
import GPy
import pandas as pd
from MAB.MultiPlayMAB import MultiPlayMAB
class RandomArm_MAB(MultiPlayMAB):
def __init__(self, objfn, initN, bounds, acq_type, C, r... |
# coding: utf-8
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import httplib
from uuid import uuid4
from flask import url_for
import pytest
@pytest.mark.usefixtures('live_server', 'customer_with_library_permissions')
class TestTheArchiveEndpoint(object):
... |
import sys
from PIL import Image
sys.path.append('./')
from models.mtcnn import MTCNN # noqa
from models.inception_resnet_v1 import InceptionResnetV1 # noqa
if __name__ == "__main__":
mtcnn = MTCNN()
print('mtcnn:{}'.format(mtcnn))
img_path = './data/test_images/angelina_jolie/1.jpg'
... |
import os
import shutil
import errno
from jsub.util import safe_mkdir
class FileSystem(object):
def __init__(self, param):
self.__param = param
self.__content_dir = os.path.expanduser(param.get('taskDir', '~/jsub'))
def __abs_path(self, task_id, path):
return os.path.join(self.__conte... |
#-----------------------------------------------------------------------------
# Copyright (c) 2013-2022, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License (version 2
# or later) with exception for distributing the bootloader.
#
# The full license is in the file COPYING.txt... |
#Converter de DICTIONARY para JSON
import json
carros={
"Marca":"Honda",
"Modelo":"HRV",
"Cor":"Prata"
}
carrosJson=json.dumps(carros)
print(carrosJson)
|
from PIL import Image
import time
import math
def midpoint_line(img,x0,y0,x1,y1,color):
#用中点算法画一条直线
if x0>x1 or (x0==x1 and y0>y1):
t=x0
x0=x1
x1=t
t=y0
y0=y1
y1=t
steep=abs(y1-y0)>abs(x1-x0)
if steep == True:
t=x0
x0=y0
... |
import dotenv
from gamecord import Game
import os
game = Game('game', screen_size=(10, 10), controls=['⬅', '⬆', '⬇', '➡', '🇽'], title='Test Game 1', tick=0.0)
ball = [1, 1]
@game.set_update()
async def update():
global ball
if game.input:
if game.input[0] == '⬅':
ball[0] -= 1
el... |
"""The module provides functions to compute quantities relevant to financial
portfolios, e.g. a weighted average, which is the expected value/return, a
weighted standard deviation (volatility), and the Sharpe ratio.
"""
import numpy as np
import pandas as pd
def weighted_mean(means, weights):
"""Computes the we... |
from regression_tests import *
class TestSignedMod1IdiomARM(Test):
settings = TestSettings(
input='arm-elf-09923a6e40662aab0ad2a1096f802f08'
)
def test_check_for_detected_function_and_signedMod1_idiom(self):
assert self.out_c.has_func( 'LzmaProps_Decode' )
# check presence of '% 9'... |
from pathlib import Path
import os
import pandas as pd
import numpy as np
import torch
import json
import gc
from wilds.common.metrics.all_metrics import Accuracy
from wilds.datasets.wilds_dataset import WILDSDataset
from transformers import GPT2Tokenizer
class Py150Dataset(WILDSDataset):
"""
... |
from enum import Enum
import arachne.nouns as a
nouns = (
a.Container,
a.Item,
a.Door,
a.Room,
a.Key,
a.Door
)
class Verb(Enum):
# basic player actions
LOOK = 'im rotating it in my mind'
TAKE = 'the act of picking things up'
DROP = 'the act of putting things down'
PUT = '... |
tab1 = ["Caros colegas", "Por outro lado", "Assim mesmo", "Não poderemos esquecer que", "Do mesmo modo",
"A prática mostra que", "Nunca é demais insistir, uma vez que", "A experiência mostra que",
"É fundamental ressaltar que", "O incentivo ao avançar tecnológico, assim como"]
tab2 = ["a execução des... |
"""\
PyMzn supports asynchronous solving through Python coroutines. The package
``pymzn.aio`` contains the coroutine version of the standard ``pymzn.minizinc``
function. This coroutine allows to execute the minizinc as an asynchronous
process and to obtain intermediate solutions while the solver is still in
execution. ... |
import _portaudio as pa
class DeviceInfo:
def __init__(self, default: bool, index: int, name: str, max_input_channels: int,
default_sample_rate: float):
# pylint: disable=too-many-arguments
self._default = default
self._index = index
self._name = name
self.... |
#!/usr/bin/env python3
""" Script for creating one hot encode DNA sequences from FASTA"""
from typing import Tuple, BinaryIO, Dict
import argparse
import gzip
import hashlib
import sys
import numpy as np
_ENCODEDICT: Dict[str, int] = {
'A': 0,
'C': 1,
'G': 2,
'T': 3,
'N': 4,
}
def fastaparser(fil... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class SaleOrder(models.Model):
_inherit = 'sale.order'
mrp_production_count = fields.Integer(
"Count of MO generated",
compute='_compute_mrp_production_c... |
"""
Testing Module for class object DetectedObject
"""
import unittest
import numpy as np
from tracker.objects.detectedobject import DetectedObject
class TestDetectedObject(unittest.TestCase):
"""
Test functions of DetectedObject
"""
def setUp(self):
self.img = np.zeros([1000, 1000, 3], dtyp... |
# Copyright 2020 The Flax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import os
import pandas as pd
from joblib import Parallel, delayed
def readParallel(directory, processor, files = None, read_function = pd.read_csv, **args):
"""
Reads files located in the given directory in parallel
Arguments:
directory {str} -- Path where to read the data
... |
with open('file2.txt', 'a') as fileptr:
fileptr.write('python has an easy syntax and user-friendly interaction') |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '6/30/2020 3:44 PM'
def dfs(graph, visited, init_node):
if init_node not in visited:
visited.append(init_node)
for connected_node in graph[init_node]:
dfs(graph, visited, connected_node)
if __name__ == '__main__':
... |
import pygame
import client.UIConstants as UIC
class ClickableImage:
"""This class draws an image which can be used as a button to initiate actions.
Edited code for class button found on-line at
https://www.youtube.com/watch?v=4_9twnEduFA
to create this.
"""
def __init__(self, image, x, y, wi... |
import re
from setuptools import setup, find_packages
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read(... |
#All Django Imports
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
#All local imports (libs, contribs, models)
from .contrib import quest... |
import argparse
import json
import os
from glob import glob
from core_data_modules.logging import Logger
from storage.google_cloud import google_cloud_utils
from storage.google_drive import drive_client_wrapper
from src.lib import PipelineConfiguration
log = Logger(__name__)
if __name__ == "__main__":
parser = ... |
# 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, software
# distributed under t... |
mats = [
Mat(**m)
for m in [
{
"name": "Bronze",
"smithing": 1,
"forging": 15,
"forging_levels": [1],
"forging_burial": False,
},
{
"name": "Iron",
"smithing": 2,
"forging": 40,
"f... |
# [h] apply actions
import hTools2.dialogs.folder.actions
reload(hTools2.dialogs.folder.actions)
hTools2.dialogs.folder.actions.actionsFolderDialog()
|
from urllib.request import urlopen
from json import loads
from datetime import datetime
from itertools import groupby
url = 'https://ru.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&rvlimit=500&titles=%D0%91%D0%B5%D0%BB%D1%8C%D0%BC%D0%BE%D0%BD%D0%B4%D0%BE,_%D0%96%D0%B0%D0%BD-%D0%9F%D0%BE%D0%BB%D1%8C'... |
from __future__ import print_function
import numpy
import scipy
import scipy.linalg
from scipy.sparse.linalg import lsqr
def ridge_svd(X, y, alpha, cutoff = 1e-10):
N1, N2 = X.shape
U, s, Vt = scipy.linalg.svd(X, full_matrices=False)
Nm = s.size
idx = s > cutoff * s[0]
s_nnz = s[idx][:, numpy.newa... |
# coding: UTF-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from .game_div import GameDiv
from .chess_element import ChessElement
from .game_text_element import GameTextElement
from .image_element import ImageElement
from .pieces_element import PiecesEle... |
"""BAP View Plugin to read latest BAP execution trace."""
from __future__ import print_function
from bap.utils.run import BapIda
import re
import idaapi # pylint: disable=import-error
class BapViews(idaapi.Choose2):
# pylint: disable=invalid-name,missing-docstring,no-self-use
def __init__(self, views):
... |
#!/usr/bin/env python3
# Copyright 2019 Mycroft AI 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... |
from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from blog.models.post import Post
from blog.models.followers import Follower
from django.http import HttpResponse
@csrf_exempt
def follow(requ... |
from geom import *
import utils
# class CameraIntrinsics:
# def __init__(self,
# fx: float, fy: float,
# px: float, py: float, skew: float,
# pitch: float, nrows: int, ncols: int
# ):
# self.fx = fx
# self.fy = fy
# self.px = px
# self.py = py
# ... |
{
"id": "db41b3",
"title": "Contiguous memory and finding segfaults in Cython",
"date": "2020-07-27",
"tags": ['cython', 'python', 'C', 'GSoC'],
}
|
import geoip2.database
import geoip2.errors
city_reader = None
country_reader = None
try:
city_reader = geoip2.database.Reader("/usr/share/GeoLite2-City.mmdb")
except FileNotFoundError:
try:
country_reader = geoip2.database.Reader("/usr/share/GeoLite2-Country.mmdb")
except FileNotFoundError:
... |
# -*- coding: utf-8 -*-
""" Daemon / Service for the Codex CMDB """
import click
import logging
from flask.helpers import get_debug_flag
from codex.cmdb import init_cmdb
from codex.webapp import create_app
from codex.mcast import McastThread
from codex.settings import DevConfig, ProdConfig
from codex.config import l... |
import os
import json
import datetime
from shutil import copy
import numpy as np
import tqdm
import multiprocessing
from multiprocessing import Pool
from runner_tool.json_api import get_file_name_from_path, copy_config_files
from runner_tool.law_wind_generator import AreaWind
from runner_tool.runner_solver import cop... |
#!/usr/bin/python3
# make menuconfig -> Device Drivers -> USB support ->
# USB Gadget Support -> USB functions configurable through configfs / Function filesystem (FunctionFS)
# modprobe libcomposite usb_f_fs
import os, stat
import os, subprocess, logging, argparse
import mtp
logger = logging.getLogger(__name__)... |
import os
from flask import Flask
from flask_appconfig import HerokuConfig
from .frontend import frontend
def create_app(configfile=None):
app = Flask(__name__)
HerokuConfig(app, configfile)
app.register_blueprint(frontend)
env_variables = ['SECRET_KEY', 'TWITTER_USERNAME', 'TWITTER_CONSUMER_KEY... |
# Author: Gael Varoquaux
# Copyright (c) 2005, Enthought, Inc.
# License: BSD Style.
|
"""This module contains the general information for ComputeServerFeatMask ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class ComputeServerFeatMaskConsts():
pass
class ComputeServerFeatMask(ManagedObject... |
# Crie um programa que leia o nome de uma pessoa e diga se ela tem "Silva" no nome.
nome = str(input('Digite o nome completo: ')).strip()
print('Exite SILVA no seu nome: {}'.format('SILVA' in nome.upper()))
|
"""
homeassistant.components.thermostat.honeywell
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Adds support for Honeywell Round Connected and Honeywell Evohome thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/thermostat.honeywell/
"""
import ... |
"""
Copyright 2017 Parag K. Mital
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, software... |
import yaml
import os
config = None
localdir = os.path.split(__file__)[0]
with open(os.path.join(localdir,"station_config.yaml"), 'r') as stream:
config = yaml.load(stream,Loader=yaml.FullLoader)
def configuration():
config_ret = config.copy()
config_ret["config_file_location"] = __file__
ret... |
class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print(("tried to handle unknown method " + name))
if args:
print(("it had arguments: " + str(args)))
... |
class DebugClass:
print_debug = False
print_error = True
remove_timeout = False # WIP
debug = DebugClass()
codebase = {}
|
from .www import build_webhook
app = build_webhook()
|
import sys
# up, down, left, right, up-left, up-right, down-left, down-right
mv_x = [0, 0, -1, 1, -1, 1, -1, 1]
mv_y = [1, -1, 0, 0, 1, 1, -1, -1]
grid = {}
def pos(x, y):
return str(x)+", "+str(y)
def look_around_neighbors(x, y):
sum_of_neighbors = 0
for i in range(8):
look_x, look_y = x+mv_x[i], y+mv_y[i]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import torch
from torch import nn, autograd
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
# from sklearn import metrics
from torch.autograd import Variable
from collections import deque, Counter
import torch.optim a... |
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from scipy.ndimage import distance_transform_edt as distance
from skimage import segmentation as skimage_seg
def generalized_distance_transform(inputs):
in_shape = inputs.shape
i = torch.arange(in_shape[1]).float(... |
__author__ = "Yannick ARMENTI"
__version__ = "0.1.1"
"""
Helpers to use voila-vuetify template
of the Jupyter voila-dashboard project.
"""
from .application import ApplicationVoilaVuetify
from .menu import MenuController
from .core import CoreController
from .abstract import AbstrController
from .dialog import Dialog... |
"""Plotting module."""
import logging
import os
import time
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.colors import LightSource
from numpy import asarray, ndarray
from pandas.plotting._matplotlib.tools import create_subplots, flatten_axes
logger = logging.getLogger(__name__)
log ... |
import numpy as np
import argparse
import os
def read_camera(sequence,ind):
file = "%s/cams/%08d_cam.txt"%(sequence,ind)
f = open(file)
f.readline().strip()
row1 = f.readline().strip().split()
row2 = f.readline().strip().split()
row3 = f.readline().strip().split()
M = np.... |
import re
import urllib
import os
from bs4 import BeautifulSoup
from dotenv import load_dotenv
from utils.utils import get_content
""" Functions and Classes used to communicate with the genius.com API"""
load_dotenv()
TOKEN = os.environ.get("GENIUS_ACCESS_TOKEN")
BASE_URL = "https://api.genius.com/"
HEADERS = {"Auth... |
from nasws.cnn.policy.cnn_general_search_policies import CNNSearchPolicy
from nasws.cnn.search_space.darts.utils import change_model_spec
# this is also a merge between these two
class DARTSBenchWeightSharingPolicy(CNNSearchPolicy):
"""
Darts Search Space supporter.
"""
def __init__(self, args):
... |
from gui import window
from src.bet_probability_calculator import bet_probability_calculation
if __name__ == '__main__':
window.mainloop()
|
from time import time
from redis import Redis
from app.config import REDIS_URL
if __name__ == "__main__":
start = time()
redis = Redis.from_url(REDIS_URL)
for key in [key.decode() for key in redis.keys("*")]:
print(f"Delete : {key}")
redis.delete(key)
print(f"Completed. : {time() - ... |
# https://github.com/IntelRealSense/librealsense/blob/master/wrappers/python/examples/python-tutorial-1-depth.py
import cv2
import pyrealsense2 as rs
import numpy as np
def draw_rectangle(event, x, y, flags, param):
global pt1, pt2, topLeft_clicked, botRight_clicked
if event == cv2.EVENT_LBUTTONDOWN:
... |
# -------------------------------------------------------------------------------
#
# Copyright (c) 2019 Waysys LLC
#
# -------------------------------------------------------------------------------
# -------------------------------------------------------------------------------
__author__ = 'Bill Shaffer'
__versio... |
# Author: Steven Zhao
# Coding: utf-8
# Simple Particle Swarm Algorithm
###################################################################
import random
import numpy as np
from collections import defaultdict
class Particle:
"""
Class to represent individual particle in the algorithm.
"""
def __init_... |
# Generated by Django 3.2.6 on 2021-08-10 06:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login_register', '0003_auto_20210810_0247'),
]
operations = [
migrations.AddField(
model_name='usuario',
name='contr... |
''' Given an arithmetic expression as a string. To compute it's value '''
def solve(indexn,number,e):
if d[e]==1:
number[indexn-1]+=number.pop()
elif d[e]==2:
number[indexn-1]-=number.pop()
elif d[e]==3:
number[indexn-1]*=number.pop()
elif d[e]==4:
number[indexn-1]/=number... |
#!/usr/bin/env python
# This file is part of the clacks framework.
#
# http://clacks-project.org
#
# Copyright:
# (C) 2010-2012 GONICUS GmbH, Germany, http://www.gonicus.de
#
# License:
# GPL-2: http://www.gnu.org/licenses/gpl-2.0.html
#
# See the LICENSE file in the project's top-level directory for details.
impor... |
from config import Package
class libm(Package):
def gen_locations(self):
yield ('/usr/local', ['/usr/local'], ['/usr/local'])
def gen_envs(self, loc):
for env in Package.gen_envs(self, loc):
self.headers = ['math.h']
if self.find_libraries(loc[2], 'm'):
... |
from .apps import IamheadlessPublisherAdminDocumentsConfig as AppConfig
class Settings:
APP_NAME = AppConfig.name
ITEM_TYPE = 'document'
URLNAME_CREATE_ITEM = f'admin-create-{ITEM_TYPE}'
URLNAME_DELETE_ITEM = f'admin-delete-{ITEM_TYPE}'
URLNAME_RETRIEVE_UPDATE_ITEM = f'admin-edit-{ITEM_TYPE}'
... |
import re
BRIGHT_REGEX = re.compile('.*bright.*')
def task_256_to_urwid_256():
manual_map = {
'red': 'dark red',
'green': 'dark green',
'blue': 'dark blue',
'cyan': 'dark cyan',
'magenta': 'dark magenta',
'gray': 'light gray',
'yellow': 'brown',
'colo... |
import csv
from pathlib import Path
from typing import Generator, Tuple, Union
from mowgli_etl._closeable import _Closeable
from mowgli_etl.model.concept_net_predicates import HAS_A, MADE_OF, PART_OF
from mowgli_etl.model.kg_edge import KgEdge
from mowgli_etl.model.mowgli_predicates import WN_SYNSET
from mowgli_etl.mo... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class PlaylistItemsWidget(QWidget):
def __init__(self, text):
super(PlaylistItemsWidget, self).__init__()
self.text = text
self.setupUi(self)
def setupUi(self, F... |
import argparse
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
pgf_with_custom_preamble = {
"font.family": "serif", # use serif/main font for text elements
"text.usetex": True, # use inline math for ticks
# "pgf.rcfonts": False, # don't setup fonts from rc ... |
import numpy as np
import torch
import torch.nn as nn
from torch.nn.modules.pooling import MaxPool2d, AvgPool2d
from utils.rnn_utils import PackedRNN
class CharBiLSTMPool(nn.Module):
def __init__(self, char_vocab, char_embed_dim=100, char_hidden_dim=25, pool="last", dropout=0.):
super(CharBiLSTMPool, sel... |
import re
import struct
import hashlib
import base64
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA, SHA256, SHA512
ALGORITHMS = frozenset(['rsa-sha1', 'rsa-sha256', 'rsa-sha512', 'hmac-sha1', 'hmac-sha256', 'hmac-sha512'])
HASHES = {'sha1': SHA,
'sha256': SHA256,
'sha512': SHA512}... |
import battleship.grid as grid
import battleship.ship as ship
import unittest
CRUISER_SIZE = 3
CRUISER_X = 2
CRUISER_Y = 5
GRID_HEIGHT = 3
GRID_WIDTH = 4
class ShipTest(unittest.TestCase):
def test_horizontal_segments(self):
s = ship.Cruiser(CRUISER_X, CRUISER_Y)
segments = s.get_segments()
... |
from threading import local
# a thread-local object holding arbitrary data
localData = local()
marker = []
# helper functions to get/set local values or optionally initialize them
def getLocal(name, factory=lambda: None):
value = getattr(localData, name, marker)
if value is marker:
value = factory()... |
# 850 x 1100 page size for 8.5 inch and 11 inch page
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
import sys
import os
def flip_image(img):
w, h = img.shape[::-1]
center = (w/2,h/2)
M = cv.getRotationMatrix2D(center, 180, 1.0)
imgUP = cv.warpAffine(img, M, (w, h))
return ... |
from __future__ import division
import re
import numpy as np
class ParseError(Exception):
pass
class Symbol(object):
regex = ''
def __init__(self, token):
self.token = token
@classmethod
def match(cls, string):
match = re.match(cls.regex, string)
if match:
r... |
from typing import Dict
from pendulum import DateTime, tz
class RateLimiter:
def __init__(self):
self._usage_time_by_user: Dict[int, Dict[int, DateTime]] = {}
self._timezone = tz.timezone("Europe/Berlin")
def can_use(self, context_id: int, user_id: int, at_time: DateTime) -> bool:
la... |
from __future__ import print_function, absolute_import
from lreid import core, data_loader, models, evaluation, tools, visualization, losses, operation
__version__ = '1.0.0'
__author__ = 'Nan Pu'
__homepage__ = 'https://tpcd.github.io/'
__description__ = 'Deep learning Continual Representation Learning in PyTorch'
_... |
# Copyright 2018 The Bazel Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
from ranks_points import rank_distance, RANKS_POINTS
from ranking_api import call_ranking_api
SHITTY_CARDS = ['2', '3', '4', '5', '6']
OKAY_CARDS = ['7', '8', '9', '10']
GOOD_CARDS = ['Q', 'J']
HIGH_CARDS = ['A', 'K']
class Player:
VERSION = "comment in"
def betRequest(self, game_state):
player_inde... |
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
guild_ids = ['guild id']
@client.event
async def on_ready():
print('Bot is read... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ... |
"""A list of all BigQuery SQL key words."""
# https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#reserved_keywords
bigquery_reserved_keywords = """ALL
AND
ANY
ARRAY
AS
ASC
ASSERT_ROWS_MODIFIED
AT
BETWEEN
BY
CASE
CAST
COLLATE
CONTAINS
CREATE
CROSS
CUBE
CURRENT
DEFAULT
DEFINE
DESC
DISTINCT
ELSE
END
EN... |
#!/usr/bin/env python
from time import sleep
from drive import RosAriaDriver
from math import sin, cos
### replace X with the robot number
robot=RosAriaDriver('/PIONIER4')
skan=robot.ReadLaser()
### read and write in json format
import json
with open('data_stereo.json','w') as json_data_file:
json.dump(skan,json... |
description = 'Temporary setup for the mota controller at AMOR'
includes = ['detector_stage']
devices = dict(
nu = device('nicos_sinq.amor.devices.logical_motor.DetectorAngleMotor',
description = 'Intended detector angle',
com = 'com',
coz = 'coz',
coz_scale_factor = 4100,
... |
import hashlib
import math
from http import HTTPStatus
from fastapi import Request
from lnurl import ( # type: ignore
LnurlErrorResponse,
LnurlPayActionResponse,
LnurlPayResponse,
)
from starlette.exceptions import HTTPException
from lnbits.core.services import create_invoice
from lnbits.utils.exchange_r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.