text stringlengths 3.07k 12.6k |
|---|
# -*- coding: utf-8 -*-
from odoo import models, fields, api
import odoo.addons.decimal_precision as dp
class AccountInvoice(models.Model):
_inherit = "account.invoice"
lieuEvent_ = fields.Char("Lieu de l'événement")
dateEvent_ = fields.Date("Date l'événement")
dateMontage_ = fields.Date("Date de monta... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import logging
import torch.nn as nn
from nni.nas.pytorch.utils import global_mutable_counting
logger = logging.getLogger(__name__)
class Mutable(nn.Module):
"""
Mutable is designed to function as a normal layer, with all necessary o... |
""" aka_cnn.py - This code defines a CNN to be used in the MLHEP competitions. It is based on
the baseline classifier, but some changes will be made to hopefully make it perform better!
Authors: <NAME>
Adapted from model.py at https://github.com/yandexdataschool/mlhep-2021-baseline
7/23/21
python3
"""
import pytorch_... |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Given an array of points, find the closest pair.
Naive implementation: O(n^2)
"""
__author__ = '<NAME>'
import copy
import math
from typing import List
def find_closest_pair_1d(points: List[float]) -> List[float]:
"""
Finds the closest pair in the given 1D... |
#!/usr/bin/env python
# Import libraries
import argparse
import re
import textwrap
# Global variables
name = "CSV Accumulator"
ver = "0.1"
sep = ""
# Parse command line arguments
def parseArgs ():
parser = argparse.ArgumentParser(
formatter_class = argparse.RawDescriptionHelpFormatter,
de... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
#!/usr/bin/python
# Copyright 2021 Dell Inc. or its subsidiaries. All Rights Reserved
# Copyright: (c) 2018, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTAT... |
from rooms.geography import pointformatting
_connected_offsets = [
(-1, -1), (0, -1), (1, -1),
(-1, 0), (1, 0),
(-1, 1), (0, 1), (1, 1)
]
class Point(object):
def __init__(self, x, y, point_map=None):
self.x = x
self.y = y
self.position = (x, y)
self.point_map = point... |
# -*- coding: utf-8 -*-
"""NOISE ROUTINES
This module contains methods for adding and removing noise from data.
:Author: <NAME> <<EMAIL>>
"""
from builtins import zip
import numpy as np
def add_noise(data, sigma=1.0, noise_type='gauss'):
r"""Add noise to data
This method adds Gaussian or Poisson noise t... |
import math
import numpy as np
import random
import string
import copy
import cv2
def printMethods(obj):
for x in dir(obj):
print( x, ':', type(eval("obj."+x)) )
def randomname(n):
randlst = [random.choice(string.ascii_letters + string.digits) for i in range(n)]
return ''.join(randlst)
def str2floats(x):
retur... |
from collections import Iterable
import logging
from django.apps import apps
from django.db.models.signals import post_save, pre_delete
from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
from django.utils.translation im... |
import numpy as np
import multiprocessing as mp
from sandbox.ex2.parallel_trpo.simple_container import SimpleContainer
from sandbox.ex2.utils.replay_buffer import SimpleReplayPool
def sample_batch(data, data_size, batch_size):
idxs = np.random.randint(data_size, size=batch_size)
return data[idxs]
class Exempl... |
import sys
import os
import csv
import subprocess
import json
def get_subdirs(item):
return os.listdir(item)
def equal_sound(out, expected):
for item in expected:
if not item in out:
return False
for edge in expected[item]:
if not edge in out[item]:
retu... |
"""Module stores the lgc_vs_lgt function providing a model for NFW conc vs. time
"""
from collections import OrderedDict
from jax import jit as jjit
from jax import numpy as jnp
CONC_MIN = 2.0
LGC_LOG10_CLIP = jnp.log10(jnp.log10(CONC_MIN))
_X0, _K = 0.0, 0.1
DEFAULT_CONC_PARAMS = OrderedDict(
conc_lgtc=0.8, conc... |
# Copyright 2021 Adobe. All rights reserved.
# This file is licensed to you 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 o... |
from typing import Collection, List
import numpy as np
from glomeruli_segmentation.data_classes import BlendMode, Rect, Tile
from glomeruli_segmentation.util import combine_masks
square = np.ones((10, 10))
rect1 = Rect(upper_left=(0, 0), width=10, height=10)
rect2 = Rect(upper_left=(10, 0), width=10, height=10)
rect... |
# -*- coding: utf-8 -*-
#
# Dao-Ke-Dao: Universal Message Module
#
# Written in 2019 by Moky <<EMAIL>>
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any ... |
import numpy as np
import pandas as pd
from pathlib import Path
from datetime import datetime
import re
from spam_lists import SPAMHAUS_DBL
import spf
import checkdmarc
'''
Reading the raw data file trec07.csv, and preprocessing the data by getting rid of null values and replacing True,False with 0 and 1... |
#---Global Variables-----------------------------------------------------------#
convert = {
"Unit": {"":1}
}
SI = {
"f":10**-15, "p":10**-12, "n":10**-9, "µ":10**-6, "m":10**-3, "c":10**-2, "d":10**-1,
"da":10**1, "h":10**2, "k":10**3, "M":10**6, "G":10**9, "T":10**12, "P":10**15
}
#---Classes--... |
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
def PLACEHOLDER_FLOW(frames):
return np.array(
[[[x, y] for x in np.linspace(-1, 1, frames[0].shape[1])] for y in np.linspace(-1, 1, frames[0].shape[0])])
PLACEHOLDER_FLOW_VISUALIZATION = cv2.imread('resources/example_flow_visualiza... |
import wave, struct, math # To calculate the WAV file content
import numpy as np # To handle matrices
from PIL import Image # To open the input image and convert it to grayscale
import scipy.ndimage # To resample using nearest neighbour
'''
Loads a picture, converts it to greyscale, then to numpy array, normalise... |
# -*- coding: utf-8 -*-
"""navigator testcase"""
import os
import unittest
import json
from optparse import OptionParser
from appium import webdriver
from lib.emulator import ADB
from lib.manifest import Manifest
from lib.logger import MyLogger
from lib.uiaction import UIAction
logger = MyLogger(name='NavigatorTest... |
import logging
import json
from io import BytesIO
from CANNode import CANNode
from types import SimpleNamespace
from time import sleep
from json.decoder import JSONDecodeError
from http.client import HTTPConnection, HTTPException
from http.server import BaseHTTPRequestHandler
from jsonschema import RefResolver, Draft7V... |
# -*- coding: utf-8 -*-
import locale
import logging
from django.conf import settings
from django.core.mail import EmailMessage
from django.utils import timezone
from apps.feedback.models import FeedbackRelation
from apps.marks.models import Mark, MarkUser
def feedback_mail():
logger = logging.getLogger("feedb... |
"""Submodule for handling internal signals."""
from ..config.interface import InterfaceConfig
from .mixins import Shaped, Named, Unique, Configured
from .interface_options import InterfaceOptions
class Internal(Named, Shaped, Unique):
"""Represents an internal signal."""
def __init__(self, name, shape):
... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect, Http404
from .models import Topic, Entry... |
import math
import numpy as np
def rotate(pt, v1, v2, theta):
m = np.zeros((4, 4))
a = v1[0]
b = v1[1]
c = v1[2]
p = ((v2 - v1) / np.linalg.norm(v2 - v1)).reshape(-1)
u = p[0]
v = p[1]
w = p[2]
uu = u * u
uv = u * v
uw = u * w
vv = v * v
vw = v * w
ww = w * w
... |
#!/usr/bin/env python
import googleapiclient.discovery
import argparse
import collections
import jinja2
import os
import os.path
import hashlib
import docker
import time
from shutil import copyfile, copymode
zones = []
public_ips = {}
local_ips = {}
client = docker.APIClient(base_url='unix://var/run/docker.sock')
epo... |
from django.shortcuts import render, get_object_or_404, redirect
from django.http import JsonResponse, Http404
from django.views import View
from .models import Project, CardType, Field, CardTypeData, Font, Card
from .apps import CardsConfig
class TemplateView:
def __init__(self, request, view_name):
te... |
__all__ = [
"Logging",
"logging",
"log_traceback",
"critical_error",
"log_to_file"
]
import os
import sys
import time
import traceback
import functools
from .common import PLATFORM
from .text import indent
from .timeutils import format_time
try:
from colorama import Fore, Style, init
init... |
import logging
import argparse
import time
import math
import torch
import torch.nn as nn
import os
from torch.utils.data import DataLoader
from utils.data_loader import load_corpus_data, NMTDataset, collate
from utils.tools import (sort_src_sentence_by_length, save_transformer, load_transformer,
... |
"""
Various utils functions for output analysis
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import json, re
from pathlib import Path
from typing import Tuple
from pathlib import Path
from data_loader import DataModule
from basecaller import Basecaller
import utils
def create_train_h... |
# encoding: utf-8
from __future__ import with_statement
import random
from whoosh.compat import b, xrange, iteritems
from whoosh.filedb.filestore import RamStorage
from whoosh.filedb.filetables import HashReader, HashWriter
from whoosh.filedb.filetables import OrderedHashWriter, OrderedHashReader
from whoosh.util.tes... |
import datetime
from typing import List
from flask import render_template, request, redirect, url_for, abort, flash
from .. import db, app
from ..handler.session import login_required, get_operator_id, is_auth_in
from ..model import PurchaseOrder, PurchaseOrderItem, Book
@app.route("/purchase")
@login_required
def ... |
""" Euromy_play: stores Euromillions plays and give summary of wins """
from datetime import date
from .euromil import euro_results
from .euromil_utils import EuroResult, EuroPlay, EURO_RANKS_NORMAL, EURO_RANKS_STAR_PLUS
class Plays:
""" Stores plays and is used to validate if plays are wins or looses """
de... |
from tkinter import *
from tkinter import messagebox
import sys, os
import json
global python
global icon
appdata = os.getenv('APPDATA')
if 'win32' in sys.platform: #change this to a settings file to add the python executeable
icon = r'{}/doggobot/icon.ico'.format(appdata)
python = 'python'
else:
icon = r'... |
### example code of GIN using pytorch geometrics
import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.nn import global_mean_pool
from torch_geometric.data import DataLoader
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
import argparse
import time
import nu... |
import click
import csv
import json
import re
import pprint
from fuzzywuzzy import fuzz
import requests
import click
import logging
import contextlib
from pathlib import Path
import os
log_format = logging.Formatter(
"[%(asctime)s][%(filename)s:%(lineno)4s - %(funcName)10s()] %(message)s"
)
handler = logging.Strea... |
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from fate_of_dice.common.dice import Dice
from fate_of_dice.resources.resource_handler import ResourceImageHandler
from fate_of_dice.system import DiceResult
from .argument_parser import parse, SkillCheckArguments
from .skill_dice ... |
'''Tools for creating simple configuration setups for libraries that require
3rd-party API/service connectivity and the like
Using:
First, you'll want to come up with a boilerplate for this configuration. This
can either be just a string
```
### Configuration boilerplate
CONFIG_BP = (
nsi.config.base_config('My... |
'''
Function:
小米商城模拟登录
Author:
Charles
微信公众号:
Charles的皮卡丘
更新日期:
2022-03-10
'''
import re
import time
import json
import random
import hashlib
import requests
'''PC端登录小米商城'''
class mieshopPC():
is_callable = True
def __init__(self, **kwargs):
for key, value in kwargs.items(): setattr(se... |
import math
import numpy as np
import torch
import scipy.ndimage
import skimage.measure
import PIL
def inference_image(net, image, shouldpad=False):
"""Helper function to inference an PIL image with a net, shouldpad in the case of U-Net"""
resized = resize_image(image)
resized = np.array(resized)
padd... |
from googletrans import Translator
from .models import CardFolder, MultiCard, Card
# from signal import signal
#
# def _handler(signum, frame):
# print("Forever is over!")
# raise Exception("end of time")
def edit_folder_translate(folder):
folder.being_edited = True
folder.save()
for multicard in... |
import curses
import time
import sys
import os
import random
import threading
class MainScreen:
def __init__(self, screen):
self.screen = screen
self.screen.bkgd(" ", curses.color_pair(1))
self.screen.border()
screen.addstr(0, 2, "Main Window", curses.color_pair(2))
self.y, ... |
"""Provide context managers for use in unit tests."""
import contextlib
import os
import os.path
import sys
import tempfile
from io import StringIO
@contextlib.contextmanager
def capture(a_callable, *args, **kwargs):
"""Capture status, stdout, and stderr from a function or method call"""
(orig_stdout, sys.st... |
import albumentations as A
import numpy as np
import cv2
import random
#-----------------------------
# Transforms during test time
#-----------------------------
class SSDInputTransform(object):
''' Input: image: numpy.ndarray in uint8
Output: numpy.ndarray in float32 and padding
'''
def __init__(... |
import math
from multiprocessing import Pool
import numpy as np
import gym.spaces.prng as space_prng
from rl_teacher.utils import get_timesteps_per_episode
def _slice_path(path, segment_length, start_pos=0):
# TODO return var
return {
k: np.asarray(v[start_pos:(start_pos + segment_length)])
fo... |
# Copyright (c) 2022, Vbalder7
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the fol... |
"""
This is a skeleton file that can serve as a starting point for a Python
console script. To run this script uncomment the following lines in the
``[options.entry_points]`` section in ``setup.cfg``::
console_scripts =
fibonacci = k8s_annotations_exporter.skeleton:run
Then run ``pip install .`` (or ``pi... |
"""
transfer_transaction
====================
Transfer transaction.
License
-------
Copyright 2019 NEM
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
... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import (QTimer, QCoreApplication, Qt, qsrand, QTime, QRectF, QPointF, pyqtSignal, QSize)
from PyQt5.QtGui import (QBrush, QColor, QPainter, QPixmap, QFont, QPalette)
from PyQt5.QtWidgets import (QWidget, QApplication, QGraphicsScene, QGraphicsView, QPushButto... |
"""
weasyprint.tests.testing_utils
------------------------------
Helpers for tests.
"""
import contextlib
import functools
import logging
import os.path
import sys
import threading
import wsgiref.simple_server
from weasyprint import CSS, HTML, images
from weasyprint.css import get_all_computed_styles
f... |
import os
from msgOperations import MSGOperations
from subprocess import Popen
import utils
import psutil
import stat
NUM_OF_GPUs_PER_NODE = 8
WORKING_DIR = utils.working_dir()
def create_working_directory():
work_dir = os.path.exists(WORKING_DIR)
if not work_dir:
os.mkdir(WORKING_DIR)
def create_msg... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2018 by AnnealPy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD 3-Clause license.
#
# The full license is in the file LICENCE, distributed with this software.
# --------... |
import sark
from oregami.reg_utils import logger, is_func, UsageBits
from oregami.reg_insn import RegInstruction
from oregami.reg_utils import AskStr, conf, RegName
# TODOS:
# - if blocks may be consecutive, do only one rename - Done.
# - Add functionality to define as type for all references - Done.
# - If register ... |
'''
A warm-start implementation of maximum cardinality bipartite matching
via Hopcroft-Karp algorithm
warm-start means that it can start from any feasible matching (that is user-provided)
references:
https://github.com/matejker/network/blob/beb591a570a8fb66d5dc4c4b48d3ff1e4f8e9134/network/algorithms/matching.py
htt... |
from Keywords import *
from Lexer import lexicalize
from time import time
start = time()
class AST:
def print_node(Node: list, args):
"""
print_node
|
args
"""
Node.append(["print_node", args])
def let_node(Node: list, name, expr):... |
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Laplace
import os
import torch
class noise_Conv2dFunction3(torch.autograd.Function):
@staticmethod
def forward(ctx, input, noise_std, noise_type):
# torch.autograd.set_detect_anomaly(True)
input = input.clon... |
"""
Functions and decorator for classes.
"""
__all__ = [
"add_to",
"default_repr_pretty",
"add_parameters_to_doc",
"add_kwargs_of",
"compute_property",
"static_property",
"staticproperty",
"class_property",
"classproperty",
"call_method",
]
from types import MethodType
from cop... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
from unicodedata import normalize
from pandas.compat import PY3, iteritems, u_safe
import pandas.core.strings as strings
# soundmarks require special handlings
_HKANA = 'ァアィイゥウェエォオカキクケコサシスセソタチッツテトナニヌネノハヒフヘホマミムメモャヤュユョヨラリルレロワヲン゙ー・「」。、'
_ZA... |
import random
#Starting Balance
global money
money = 100
#Introduction
print("Welcome to Stevie's Casino!")
print("Here are some credits to get you started!")
print("Credits: " + str(money))
#Write your game of chance functions here
#Coin Toss (Pick "Heads" or "Tails")
def coin_toss(call, bet):
global money
pri... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import ast # using ast.literal_eval here for speed. In reality this is dangerous because it could result in execution of arbitrary code (injection)
from collections import namedtuple
from types import FunctionType
Instruction = namedtuple('Instruction','opcode inA inB inC')
PuzzleInput = namedtuple('PuzzleInput','sa... |
from collections import defaultdict, Counter
import numpy as np
class ConfusionMatrix(object):
def __init__(self, labels, default_label):
self.counts = defaultdict(Counter)
self.labels = labels
self.default_label = default_label
@staticmethod
def to_table(data, row_labels, column... |
from random import random, randint, choice
from copy import deepcopy
from math import log
class fwrapper:
"""
A wrapper for the functions that will be used on function nodes.
Its member variables are name of the function, the function itself,
and the number of parameters it takes.
"""
def __i... |
import mcp2515
import spidev
import RPi.GPIO as GPIO
RX_msg = []
spi= spidev.SpiDev()
def reset():
reset_instruction = [0xc0]
spi.writebytes(reset_instruction)
def readReg(addr):
buf_rd = [0x03, addr, 0x55]
buf_rd = spi.xfer2(buf_rd)
return int(buf_rd[2])
def writeReg(addr, val):
buf_wrt =... |
from flask import Flask
from flask import request
import json
import requests
from database_functions import create_poll_record
from database_functions import create_poll_result_record
from database_functions import cancel_poll_record
def read_config():
"""
Read the config.json file and populate global variab... |
# Copyright 2020 pydicom authors. See LICENSE file for details.
"""Pydicom command line interface program
Each subcommand is a module within pydicom.cli, which
defines an add_subparser(subparsers) function to set argparse
attributes, and calls set_defaults(func=callback_function)
"""
import argparse
import sys
impor... |
'''
Copyright (C) 2019-2021, <NAME> <<EMAIL>>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
# Copyright 2018 Google Inc.
# Copyright 2019 Yelp
#
# 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 agre... |
# Copyright (c) 2019 Uber Technologies, 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... |
from autofit.tools import fit
from autolens import exc
from autolens.lens.util import lens_fit_stack_util as stack_util
from autolens.lens import ray_tracing
def fit_lens_image_stack_with_tracer(lens_data_stack, tracer, padded_tracer=None):
"""Fit a lens image with a model tracer, automatically determining the ty... |
from pathlib import Path
import os
import pickle
import numpy as np
from tqdm import tqdm
def load_pcd_as_nparray(pcd_file):
points = []
with open(pcd_file, 'r') as f:
lines = f.readlines()
for line in lines[11:]:
point = line.split()
points.append(point)
return np.asarray(poi... |
import xmatters.utils
import xmatters.connection
import xmatters.objects.common
class GroupReference(xmatters.connection.ApiBase):
def __init__(self, parent, data):
super(GroupReference, self).__init__(parent, data)
self.id = data.get('id') #: :vartype: str
self.target_name = data.get('... |
# statOT core
# Author: <NAME> (<EMAIL>)
import numpy as np
import pandas as pd
from numpy import linalg
import ot
import copy
def statot(x, C = None, eps = None, method = "ent", g = None,
dt = None,
maxiter = 5000, tol = 1e-9,
verbose = False):
"""Fit statOT model
:pa... |
"""
utilities to extract features from SavedModel and save it in a pickle file
"""
import csv
import pickle
import argparse
from collections import defaultdict
import tensorflow as tf
import numpy as np
import pandas as pd
class ReadImage:
""" class to read the images for inference """
def __init__(self... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Filename: _LocalSets.py
# @Author: <NAME>
# @Time: 18/3/22 11:14
# @Version: 3.0
import sys
import numpy as np
import pandas as pd
from sklearn.metrics import pairwise_distances
class LocalSets:
"""
<NAME>., <NAME>., & <NAME>. (2015). Three n... |
# Dependencies:
# portpicker (pip install portpicker)
# tcmalloc4 (sudo apt-get install google-perftools)
# TF 0.12
#
#
# Benchmarks on Xeon E5-2630 v3 @ 2.40GHz
#
# export LD_PRELOAD=/usr/lib/libtcmalloc.so.4
# python benchmark_grpc_recv.py --data_mb=128
# Local rate: 15214.63 MB/s
# Distributed rate: 569.27 MB/... |
''' Import csv files that contain information on the constants required by HGC.
This will be transformed to a
pickle file with the same information in a dict of named tuples '''
from collections import namedtuple
from pathlib import Path
import cloudpickle as pickle
import pandas as pd
from pyparsing import Gr... |
import os
import copy
import openpyxl
from pathlib import Path
from itertools import combinations
from simpleai.search import (
CspProblem,
backtrack,
HIGHEST_DEGREE_VARIABLE,
MOST_CONSTRAINED_VARIABLE,
LEAST_CONSTRAINING_VALUE,
)
HEAD_COUNSELORS = {'Brodi','Ceci','Ignacio','Jocelyn','John','Lily'... |
import pytest
import subprocess
@pytest.mark.parametrize('sep', ['-', '+'])
def test_list_keybinds(hlwm, sep):
# single key, 1-word command:
hlwm.call(f'keybind x quit')
# 2 modifiers, 3-word command:
hlwm.call(f'keybind Mod1{sep}Shift{sep}a resize left +5')
keybinds = hlwm.call('list_keybinds')
... |
# -*- coding: utf-8 -*-
import re
from flask import request, redirect, url_for, abort, render_template, flash, \
current_app
from einfachjabber.utils import *
from einfachjabber.apps.mainsite import mainsite
from einfachjabber.models import OSList, TutorialDoc
@mainsite.route('/')
def start():
pagetitle =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Data Container: abstract classes
"""
from __future__ import (
print_function,
division,
absolute_import,
unicode_literals)
from six.moves import xrange
# =============================================================================
# Imports
# ========... |
# Intended to be invoked from cmake - don't run directly.
import os
import pathlib
import setuptools
import setuptools.command.build_ext
import setuptools.command.build_py
import shutil
import subprocess
import sys
MODE = None
curpath = pathlib.Path(os.path.dirname(os.path.realpath(__file__)))
os.chdir(curpath)
lib... |
# -*- coding: utf-8 -*-
#
# Copyright 2018-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
"""Test :class:`qibo.abstractions.gates.M` when used with registers."""
import pytest
import numpy as np
from qibo import K, models, gates
def assert_dicts_equal(d1, d2):
assert d1.keys() == d2.keys()
for k, v in d1.items():
if isinstance(v, dict):
assert v == d2[k]
else:
... |
from dataclasses import dataclass
from datetime import datetime
from math import isinf
from typing import Dict, List
from slack_sdk import WebClient
from pytz import UTC
from hunter.data_selector import DataSelector
from hunter.series import ChangePointGroup, AnalyzedSeries
@dataclass
class NotificationError(Except... |
# -*- coding: utf-8 -*-
#
#
# Project name: OpenVAS2Report: A set of tools to manager OpenVAS XML report files.
# Project URL: https://github.com/cr0hn/openvas_to_report
#
# Copyright (c) 2015, cr0hn<-AT->cr0hn.com
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modificatio... |
# -*- coding: utf-8 -*-
import unittest
import os
from io import StringIO, BytesIO
import h5py
from ribopy import Ribo
from ribopy import create
from ribopy.merge import merge_ribos
from ribopy.settings import *
from ribopy.core.exceptions import *
from ribopy.rnaseq import set_rnaseq, get_rnaseq
import sys
test_dir... |
"""
@author: <NAME>
@copyright: Copyright 2019, dialogue-generation
@license: MIT
@email: <EMAIL>
@date: 2019.04.04.
"""
# pylint: disable=no-member
# pylint: disable=not-callable
import os
import torch
import random
from torch.nn.modules import (
ModuleList, Module)
from torch.nn import (
Lin... |
# Copyright 2004 <NAME>, 2006 <NAME>, <NAME>
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""defines class that will print in a user friendly format declarations tree and
declarations Py++ configuration in... |
import math, pyglet, inktilities
import random
from pyglet.window import key, mouse
###### RESSOURCES ######
pyglet.resource.path = ['./resources/img']
pyglet.resource.reindex()
pen_image = pyglet.resource.image('pen.png')
ink_image = pyglet.resource.image('ink.png')
splatter_image = pyglet.resource.image('splatter.... |
#coding:utf8
import os
import time
import datetime
import sys
import glob
from pprint import pprint
from google.cloud import storage
from google.cloud import speech_v1
from google.cloud.speech_v1 import enums
# 変数設定
## GCSのバケット名を指定
bucketName = '<バケット名を記入してください>'
## https://cloud.google.com/speech-to-text/docs/languag... |
# code was heavily based on https://github.com/TachibanaYoshino/AnimeGANv2
# Users should be careful about adopting these functions in any commercial matters.
# https://github.com/TachibanaYoshino/AnimeGANv2#license
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from .builder import GENERATORS
... |
import numpy as np
import os
import scipy.misc
def crop_image(image_in, image_ref, rotation, bounding_box, padding=0.15, jitter=0.15, flip=True, image_size=224):
# based on https://github.com/shubhtuls/drc/blob/master/utils/cropUtils.lua
left, top, width_box, height_box = bounding_box
height_image, width... |
from __future__ import print_function
import math
import sys
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import... |
# Copyright 2020 DeepMind Technologies Limited.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
#!/usr/bin/python
# (c) 2021, NetApp, Inc
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
module: na_ontap_snaplock_clock
short_description: NetApp ONTAP Sets the... |
from random import randint
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework import generics, permissions, status, mixins, serializers
from rest_framework.authtoken.models import Token
from rest_framework.compat import au... |
from collections import OrderedDict
from common.serializers.msgpack_serializer import MsgPackSerializer
serializer = MsgPackSerializer()
def check(value):
assert value == serializer.deserialize(serializer.serialize(value))
def test_serialize_int():
check(1)
check(111324324324324)
check(-1)
che... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.