content stringlengths 5 1.05M |
|---|
import json
def GetWayPoints():
with open('maps.json') as json_file:
data = json.load(json_file)
length = len(data)
#print(length)
map1 = data[1]
waypoints = map1["waypoints"]
#print(waypoints)
#print(len(waypoints))
wpoly = []
for point in wa... |
import time
import board
import busio
import digitalio
import neopixel
import adafruit_gps
from lora_e5_atcontrol import E5_ATControl
from helium_config import helium_config
# Initialize push button.
btn = digitalio.DigitalInOut(board.GP20)
btn.direction = digitalio.Direction.INPUT
# Initialize neopixels.
num_pixel... |
#!/usr/bin/env python3
#Spencer Fronberg
#OpenSpace Project
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import timeit
#import PIL.Image
from PIL import Image
import cv2
def pil_test():
cm_hot = mpl.cm.get_cmap('hot')
cm_purples = mpl.cm.get_cmap(... |
import os
import json
import argparse
class Relation():
def __init__(self, entity_1_id, relation_name, entity_2_id):
self.entity_1_id = entity_1_id
self.relation_name = relation_name
self.entity_2_id = entity_2_id
class InceptionToken():
def __init__(self, id, position, text, entity_na... |
#
# @copyright@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
#
import sys
import stack.commands
from stack.commands.sync.host import Parallel
from stack.commands.sync.host import timeout
from stack.repo ... |
# -*- coding: utf-8 -*-
import numpy as np
class WaveBandDetector:
def __init__(self):
self.chl_wb = [13, 5, 15, 8, 7, 11, 4, 14, 3, 10, 6] # index of channel
self.chl_frontal_left = 13
self.chl_frontal_right = 5
# Frequency bands of neural activity
self.waveband = np.array(... |
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.size'] = 16
mpl.rcParams['lines.linewidth'] = 3
mpl.rcParams['text.usetex'] = True # use latex for all text handling
mpl.rcParams['savefig.bbox'] = 'tight'
mpl.rcParams['savefig.format'] = 'pdf' # gives best resolution plots
mpl.rcParams['axes.... |
import numpy as np
from gym.envs.toy_text.cliffwalking import CliffWalkingEnv
class CliffEnv(CliffWalkingEnv):
"""
Extension of the CliffWalking environment to make it compatible with the intreface of the lab sessions
"""
def __init__(self):
super().__init__()
self.startstate = np.rave... |
def century(year):
return year // 100 + (0 if year % 100 == 0 else 1)
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#pylint: disable=E1004,R0912,R0913,R0914,R0915,R0903,R0902,C0302
"""
File : reader.py
Author : Valentin Kuznetsov <vkuznet AT gmail dot com>
Reader module provides various readers for different data-formats:
JSON, CSV, Parquet, ROOT. It also allows access files eit... |
import os, sys
import logging
logger = logging.getLogger(__name__)
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
... |
# coding=utf-8
# Copyright 2022 The ML Fairness Gym 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 applicab... |
"""Perform EDA calculations and output the results in plain text, NMD, and
graphical formats.
Download example :download:`MDM2 trajectory files </doctest/mdm2.tar.gz>`."""
import os.path
from ..apptools import *
from .nmaoptions import *
def addCommand(commands):
subparser = commands.add_parser('eda',
... |
from __future__ import absolute_import, print_function
from .mono_bridge import generate_strip_string, ModInputSignal, MonoBridgeElement, OSCMonoBridgeElement, MonoBridgeProxy
from .mono_button import MonoButtonElement, DescriptiveMonoButtonElement
from .mono_encoder import MonoEncoderElement, CodecEncoderElement, WA... |
from ef.field.solvers import FieldSolver
class FieldSolverPyamg(FieldSolver):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
import pyamg
self._solver = pyamg
def eval_potential(self, charge_density, potential):
self.init_rhs_vector(charge_density, pote... |
import sysrepo as sr
from tabulate import tabulate
from .common import sysrepo_wrap, print_tabular
from natsort import natsorted
import json
import re
import logging
logger = logging.getLogger(__name__)
stdout = logging.getLogger("stdout")
stderr = logging.getLogger("stderr")
class Mgmtif(object):
XPATH_MGMT = ... |
pr_payload = {
"action":"closed",
"number":1,
"pull_request":{
"url":"https://api.github.com/repos/ukor/test_webhook/pulls/1",
"id":307914037,
"node_id":"MDExOlB1bGxSZXF1ZXN0MzA3OTE0MDM3",
"html_url":"https://github.com/ukor/test_webhook/pull/1",
"diff_url":"https://g... |
# fig03_01.py
"""Class average program with sequence-controlled repetition."""
# initialization phase
total = 0 # sum of grades
grade_counter = 0
grades = [98, 76, 71, 87, 83, 90, 57, 79, 82, 94] # list of 10 grades
# processing phase
for grade in grades:
total += grade # add current grade to the running tot... |
import math
import random
def eggholder(args):
''' http://www.sfu.ca/~ssurjano/egg.html '''
x = args["x"]
return (-(x[1] + 47) * math.sin(math.sqrt(abs(x[1] + (x[0] / 2.0) + 47))) - x[0] * math.sin(math.sqrt(abs(x[0] - (x[1] + 47)))), None)
def michal(args):
''' http://www.sfu.ca/~ssurjano/michal.ht... |
import standard_play
import behavior
import skills
import tactics
import robocup
import constants
import main
class OurCornerKick(standard_play.StandardPlay):
MinChipRange = 0.3
MaxChipRange = 3.0
ChipperPower = 0.5
TargetSegmentWidth = 1.5
def __init__(self):
super().__init__(continuous... |
import os
import discord
import asyncio
import subprocess, shlex
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
Serverinformation = """
Discord Music Bot Version 1.3:
All commands n... |
import os
import sys
# Lets get the first parameter which could potentially be a local file name
methodArg = ""
if len(sys.argv) > 1:
methodArg = sys.argv[1]
print("This is the output of my poweroutage action handler python called for " + os.getenv('DATA_PROBLEM_PROBLEMTITLE',""))
print("Received the following me... |
from django.db import models
from dynamic_models import config
def test_default_fields_setting(settings):
default_fields = {"default_integer": models.IntegerField()}
setattr(settings, "DYNAMIC_MODELS", {"DEFAULT_FIELDS": default_fields})
assert config.default_fields() == default_fields
def test_default... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import glob
def grad_thresh(img, thresh=(20,100)):
# Gradient thresholds:
# Grayscale image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Sobel x
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0) # Take the de... |
import enum
import itertools
import logging
import re
from typing import Callable, Dict, Iterable, List, Optional, TextIO, Tuple
import numpy as np
import numpy.typing as npt
from ..cli import run_with_file_argument
from ..io_utils import get_lines
logger = logging.getLogger(__name__)
PATTERN = re.compile(r"^fold al... |
import eos, activity
from chemsep_operation import get_chemical
from chemsep_operation import EosInterface as T_prop
from math import exp, log
def bubble_T(components, z, P, model=None, kij_input = None, kij_tune=None):
""" model = SRK, Ideal, NRTL, UNIQUAC, UNIFAC, MODFAC """
c = components
coun... |
from ramda.is_empty import is_empty
from ramda.private.asserts import *
def is_empty_test():
assert_equal(is_empty([1, 2, 3]), False)
assert_equal(is_empty([]), True)
assert_equal(is_empty(""), True)
assert_equal(is_empty(None), False)
assert_equal(is_empty({}), True)
assert_equal(is_empty({"l... |
from __future__ import print_function
import random
import string
import subprocess
import time
from configparser import SafeConfigParser
import MySQLdb
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.mail import EmailMessage
from django.http import JsonResponse
from django.views.generic im... |
import sys
from libsbml import *
import re
from shutil import copyfile
# A function that does a simple check on any SBML files
##(gets called by main)
##Arguments:
##input_files - list of the SBML files used
def SBML_checker(input_files):
#Counter for number of errors
tot_errors=0
#Reads each SBML file in a for l... |
import numpy as np
import matplotlib.pyplot as plt
import math
from math import pi,pow
from PyPonding import FE
from PyPonding.structures import basic_structure
class osu_test:
# Plan Dimensions
L = 48*12
Le = 4
S = 67
Se = 5
# Joist and Beam Section Properties
E ... |
# Parallel posterior computations for the binomial model.
import numpy as np
import multiprocessing as mp
from numba import jit, prange
from time import time
def mc_multi(chunk_len, parameters, delta_out):
"""
Inner function for multiprocessing call.
Draws from a beta posterior.
"""
delta = np.... |
#SOLUTION FOR P20
'''P20 (*) Remove the K'th element from a list.
Example:
* (remove-at '(a b c d) 2)
(A C D)'''
my_list = ['a','b','c','d','e']
pos= int(input('Element to remove = '))
if pos <= len(my_list): #CHECK IF INPUT IS IN RANGE
my_list.pop(pos-1) #REMOVE THE ELEMENT AT GIVEN INDE... |
'''
classmethod
概念:
这是一个类对象,继承于根类object
作用:
将 function 转为 class method
描述:
类方法会将该方法所在的类对象,隐式地作为第一个参数,就像实例方法接收实例作为第一个参数一样,
简单来说, classmethod = function(cls, ...)
写法如下:
class C:
@classmethod
def f(cls, arg1, arg2, ...):
... |
import sys
sys.path.append('..')
from parsefunc import *
plusMinus = oneOf('+-')
multDiv = oneOf('*/')
def reduceExprs(exprs, ops, default=0):
'''ops is a dict, where keys are binary ops representations (ie, '+', '-')
and values are the corresponding binary functions.
exprs = [num1, op1, nu... |
from supabase_py.lib.storage.storage_bucket_api import StorageBucketAPI
class SupabaseStorageClient(StorageBucketAPI):
"""
Manage the storage bucket and files
Examples
--------
>>> url = storage_file.create_signed_url("poll3o/test2.txt", 80) # signed url
>>> loop.run_until_complete(storage_f... |
import random
class Car_Interface():
'''
Intialize car interface object. Model is default to simple.
If simple acceleration will roughly be a linear combination
of the corresponding factors. model = "complex" introduces
some nonlinearities
'''
def __init__(self, model = "simple"):
... |
from typing import Dict
LEGACY_KEYS = ["exporter_cell_id", "exporter_name", "exporter_params"]
def set_key_if_exists(to_dict: Dict, from_dict: Dict, key: str):
if key in from_dict:
to_dict[key] = from_dict[key]
def convert_if_legacy_datadoc_schedule(schedule_config: Dict) -> Dict:
"""Previously, th... |
from pathlib import Path
from PIL import Image
with Image.open(Path('input/test_image01.jpg')) as im:
print(im.format, im.size, im.mode)
r, g, b = im.split()
im = Image.merge('RGB', (b, r, g))
im.show()
|
# -*- coding: utf-8 -*-
#
# (C) Copyright 2022 Karellen, Inc. (https://www.karellen.co/)
#
# 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
#
#... |
class Benchmark:
def __init__(self, name, fullname):
self.name = name
self.fullname = fullname
self.refs = []
def add_ref(self, command):
self.refs.append(command)
def num_runs_ref(self):
return len(self.refs)
def get_runs_ref(self):
return self.refs
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
#class LoginModel(models.Model):
# username = models.CharField(max_length=40)
# password = models.CharField(max_length=40)
|
import scrapy
from kingfisher_scrapy.base_spider import CompressedFileSpider
class GeorgiaOpenData(CompressedFileSpider):
"""
Domain
State Procurement Agency (SPA)
"""
name = 'georgia_opendata'
data_type = 'release_package'
compressed_file_format = 'release_package'
# The file is a... |
# Copyright (c) 2007 Carnegie Mellon University
#
# You may copy and modify this freely under the same terms as
# Sphinx-III
"""
Sphinx-III format hypothesis segmentation files.
"""
__author__ = "David Huggins-Daines <dhuggins@cs.cmu.edu>"
__version__ = "$Revision: 10058 $"
def open(filename):
"""
Open a Sph... |
def main():
f = open("input/01.input")
nums = [int(l) for l in f.readlines()]
print(nums)
for a in nums:
for b in nums:
if a + b == 2020:
print(a, b, a * b)
return
main()
|
#!/usr/bin/env python2
import functools
import envoy
import os
import os.path
import shlex
import sys
import re
from lxml.html import builder as E, tostring
from lxml import etree
BASE_URL = os.environ.get('TALKS_BASE_URL', "file:///" + os.path.abspath('.') + '/')
def text_to_path(img_name):
# Ugly but prevent... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... |
import sys
import _thread as thread
import threading
cmd = sys.modules["pymol.cmd"]
from pymol import _cmd
# WARNING: internal routines, subject to change
def lock_without_glut(_self=cmd):
with _self.lock_api_glut:
_self.lock(_self)
class LockCM(object):
'''
API lock context manager
'''
... |
def comp_angle_rotor_initial(self):
"""Compute rotor initial angle between rotor and stator d-axes
Parameters
----------
self : MachineSync
A: MachineSync object
Returns
-------
angle_rotor_initial: float
rotor initial angle given by the difference of rotor and stator d-axes ... |
from functional_tests import graphql_utils
TEAM_QUERY = """
query GetTeamForYear($year: Int!) {
team(year: $year) {
members {
number
person {
name
slug
}
role
}
}
}
"""
def test_get_team(api_client, team_factory, team_member_factory):
"""
Users should be ab... |
import numpy as np
from tnpy.operators import SpinOperators
from tnpy.model.model_1d import Model1D
from tnpy.model.utils import boundary_vectors, minors_if_no_penalty
class Thirring(Model1D):
def __init__(
self, n: int, delta: float, ma: float, penalty: float, s_target: int
) -> None:
"""
... |
import sys
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode
from urllib2 import build_opener, ProxyHandler, Request, urlopen
from urllib import urlencode
else:
from urllib.request import build_opener, ProxyHandler, Request, urlopen
from urllib.parse import urlencode
text_type = str
... |
import komand
from .schema import TicketHistoryInput, TicketHistoryOutput
# Custom imports below
from komand_request_tracker.util import utils
class TicketHistory(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="ticket_history",
description="Gets a l... |
#
# vect3crossfun.py
# Cross product of two 3-d vectors using function in Python 3.7
#
# Sparisoma Viridi | https://github.com/dudung
#
# 20210110
# 2009 Start creating this example.
# 2011 Test it and ok.
#
# Define cross function with two arguments
def cross(a, b):
c = [0, 0, 0]
c[0] = a[1] * b[2] - a[2] * b[1]
... |
#
# Copyright 2014 Grupo de Sistemas Inteligentes (GSI) DIT, UPM
#
# 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
#
# Unles... |
from __future__ import absolute_import
from .pipeline_components import *
|
import unittest
from mock import Mock
import xml_models
class Muppet(xml_models.Model):
name = xml_models.CharField(xpath='/root/kiddie/value')
friends = xml_models.CollectionField(xml_models.CharField, xpath='/root/kiddie/friends/friend')
finders = {
(name,): "http://foo.com/muppets/%s"
}
... |
from sympy import symbols, solve, diff, pprint, integrate
# The 2000 census in a particular area gives us an age distribution that is approximately given (in millions) by the function
multiplier = 1000000
x = symbols( 'x' )
F = 39 + 2.11*x - 0.81*x**2
# where x varies from 0 to 9 decades.
# The population of a giv... |
from os import listdir
import os.path
import pandas as pd
class SentenceLoader:
def __init__(self, base_path, language='german', corpus='corpus2', explicit_word_list=None):
self.explicit_word_list = explicit_word_list or []
self.language = language
self.corpus = corpus
self.base_p... |
import time
import pytest
import shibari
rig = shibari.Rig('ebi', 'hishi')
@rig.bind('ebi')
def timestamp():
return str(time.time())
@rig.bind('ebi')
def timestamp_with_args(a, b):
return f"{a}_{str(time.time())}_{b}"
@rig.free('ebi')
def finish():
return "Finish"
@rig.free('ebi')
def finish_fai... |
# coding: utf-8
__author__ = 'salvia'
import socket
import time
import sys
import os
from .command import Command, Commands
from .protocol import BaseIPCProtocol
def check_pid(pid):
""" Check For the existence of a unix pid. """
try:
os.kill(pid, 0)
except OSError:
return False
else:
... |
from typing import Dict
from requests import Response
import requests
from Framework.LogHandler import *
class HttpHandler:
"""
This class is used to handle the HTTP requests
"""
def __init__(self):
pass
def send_get_request(self, base_url: str, paths: str, port: int, params: Dict, heade... |
import torch.optim as optim
import torch.nn as nn
import torch
import models
from data import data_generator
epochs = 400
train_size = 1500
batch_size = 128
steps_per_epoch = round(train_size / batch_size)
net = models.MiniSqueezeNet(1, 10)
criterion = nn.BCELoss()
optimizer = optim.Adam(net.parameters())
data_gen... |
π = 22 / 7
print(π)
|
from satyrus import SatAPI, Posiform
class dwave(SatAPI):
""""""
def solve(self, energy: Posiform, *, num_reads=1_000, num_sweeps=1_000, **params: dict) -> tuple[dict, float]:
"""
Parameters
----------
energy : Posiform
Input Expression
params : dict (option... |
"""Tests of construction of nodes and weights for integration."""
import shutil
import subprocess
import tempfile
import numpy as np
import pytest
import scipy.io
from pyblp import Integration
@pytest.mark.parametrize(['dimensions', 'specification', 'size', 'naive_specification'], [
pytest.param(1, 'monte_carl... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
import requests
#设置参数
param = {"q":"西游记"}
#多个参数格式:{"key1": "value1", "key2": "value2", "key3": "value3"}
#请求网站豆瓣首页
r = requests.get("https://www.douban.com/search",params=param)
#打印状态码
print(r.status_code)
#conten 字节方式的响应体,会自动为你解码 gzip 和deflate 压缩
print(r.content)
#headers 以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回 ... |
"""
User.py - Provides a user object
Provides an User object that represents a IRC User
Copyright (c) 2018 The Fuel Rat Mischief,
All rights reserved.
Licensed under the BSD 3-Clause License.
See LICENSE.md
"""
from __future__ import annotations # enable forward-references
from dataclasses import dataclass
from t... |
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.dates as mdates
import numpy as np
import pandas as pd
import string
from matplotlib.dates import MonthLocator, DayLocator, WeekdayLocator, MO, TU, WE, TH, FR, SA, SU
def plot_rca_timeseries_oneradar(
rca_file, output_directory, baseline_d... |
#!/usr/bin/env python
# Put all dbBact sequences in to the sequence translator update queue
# need to run after adding a new whole seq database / region
'''Put all dbBact sequences in to the sequence translator update queue
need to run after adding a new whole seq database / region
'''
import sys
import requests
im... |
class MockInput:
def __init__(self, data):
self.data = data
def read(self, _):
return self.data
|
#!/usr/bin/env python
"""Usage: qacls_repair.py ROOT
Reads the ACL and posix attributes (owner, group, modes) from the ROOT specified
Determines whether to use ACL or POSIX (look for generated:true/false in the ACL)
does a push of the permission set determined, either the ACL or mode bits
"""
__author__ = 'mbott'
im... |
#!/usr/bin/python
DOCUMENTATION = """
---
module: comware_local_user
short_description: Manage local_user
description:
- Manage local_user
version_added: 1.8
category: Feature (RW)
author:hanyangyang
notes:
- Before using ftp_dir , ensure it already exist in the device.
- Local user group specify the user... |
"""
This script builds a list of all duplicates by file_id & document_id, and then iterates
through all ".minscored" files from the filename lookup, creating a new archive for each
file in the original containing all documents that were not marked as duplicates during
the previous step.
So for each original file, a ... |
from collections import defaultdict
def spiral():
x, y = 0, 0
dx, dy = 0, -1
while True:
if abs(x) == abs(y) and [dx, dy] != [1, 0] or x > 0 and y == 1 - x:
dx, dy = -dy, dx
yield x, y
x, y = x + dx, y + dy
def add_adjacent(x, y, coord_dict):
adj = 0
for dx i... |
from .cross_attention_fusion import FeatureFusion, FeatureFusionEncoder
from ....positional_encoding.untied.absolute import Untied2DPositionalEncoder
from ....positional_encoding.untied.relative import generate_2d_relative_positional_encoding_index, \
RelativePosition2DEncoder
def build_cross_attention_based_enco... |
import typing
import uuid
from datetime import datetime
from decimal import Decimal
import jsl
import sqlalchemy as sa
import sqlalchemy.orm as saorm
import sqlalchemy_jsonfield as sajson
from inverter import dc2pgsqla
from rulez import compile_condition
from sqlalchemy import Column, Index, MetaData, Table, func
from... |
import subprocess
from unittest.mock import MagicMock
import pytest
from briefcase.exceptions import BriefcaseCommandError, InvalidDeviceError
from briefcase.integrations.android_sdk import ADB
def test_force_stop_app(mock_sdk, capsys):
"""Invoking `force_stop_app()` calls `run()` with the appropriate
param... |
#!/usr/bin/env python
"""
CREATED AT: 2021/12/25
Des:
https://leetcode.com/contest/biweekly-contest-68/problems/maximum-number-of-words-found-in-sentences/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
Tag:
See:
Time Spent: min
"""
from typing import List
class Solution:
def mostWordsFound... |
# stdlib imports
import logging
import sys
# third-party imports
import click
import docker
# local imports
from shpkpr.cli import arguments
from shpkpr.cli import options
from shpkpr.cli.entrypoint import CONTEXT_SETTINGS
from shpkpr.deployment import BlueGreenDeployment
from shpkpr.deployment import StandardDeploym... |
# Copyright (C) 2017 Louis Vottero louis.vot@gmail.com All rights reserved.
from __future__ import absolute_import
from ... import qt_ui, qt
from .. import core
from .. import geo
from .. import space
from .. import ui_core
import maya.cmds as cmds
class CheckView(ui_core.MayaWindowMixin):
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Johnny Mariéthoz.
#
# Coons is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Objects permission policy."""
from invenio_records_permissions import RecordPermissionPolicy
from invenio_re... |
"""Main page."""
import allure
from selenium.webdriver import ActionChains
from locators.main_page import MainPageLocators
from selenium.webdriver.common.keys import Keys
class MainPage:
"""Main page class."""
def __init__(self, app):
self.app = app
def search_field(self):
return self.... |
import socket, os
role = os.environ['ROLE']
def startServer():
hosts = int(os.environ['HOSTS'])
connected_hosts = 0
port = int(os.environ['PORT'])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', port))
s.list... |
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
inch = 0.0254
mm = 1e-3
cm = 1e-2
nm = 1e-9
blue = 450 * nm
green = 550 * nm
red = 650 * nm
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
# Dictionary of currency representations:
# key: official ISO 4217 code
# value[0]: numeric representation
# value[1]: number of digits
# value[2]: currency symbol in UTF-8
# value[3]: textual descri... |
import sqlite3, uuid, sys, logging, time, os, json, zlib, hashlib, tempfile
from util import mbtiles_connect, prettify_connect_string, flip_y
from util_convert import convert_tile_to_bbox
logger = logging.getLogger(__name__)
def mbtiles_tilelist(mbtiles_file, **kwargs):
flip_tile_y = kwargs.get('flip_y', False... |
#!/usr/bin/env python
import sys, pickle
import xml.etree.ElementTree
# path to the Swedish Associative Thesaurus version 2 (SALDO) XML-file
saldo_path = 'saldom.xml'
if len(sys.argv) != 2:
print('usage: {} <out>'.format(sys.argv[0]))
quit()
outfile = sys.argv[1]
tree = xml.etree.ElementTree.parse(saldo_pat... |
import matplotlib.pyplot as plt
from skimage import io, transform
from scipy import ndimage
import numpy as np
fpath = 'd:/lecture/computervision/'
image = io.imread(fpath + 'cameraman.tif')
imageTranslated = np.zeros(np.shape(image))
# make transform x->x+15, y->y+30
Tx = 15
Ty = 30
T = np.array([[1., 0., 0.],
... |
# Copyright 2019, zhoudoao@gmail.com.
# 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... |
# [Project AutoKupis2] Auto-sugang project GUI.
# 0.1.0va, 19.12.29. First launched.
# written by acoustikue(SukJoon Oh)
# __ _ __
# ____ __________ __ _______/ /_(_) /____ _____
# / __ `/ ___/ __ \/ / / / ___/ __/ / //_/ / / / _ \
# / /_/ / /__/ /_/ / /_/ (__ ) /... |
from cadmus.parsing.get_attrs import get_attrs
def clean_soup(soup):
# NB we aim to provide a clean version of the text but the original file is always retained for bespoke parsing.
# eg you may wish to keep the tables and figures or author data.
# here is a list of tags that i want to remove before i... |
# *** Import all the required modules here...
import gspread
from PySheetAdaptor.Drivers.PySheetDriver import PySheetDriver
from PySheetAdaptor.Drivers.GoogleDriver import GoogleDriver
from sys import stdout
from PySheetAdaptor.Drivers.UtilityDriver import (
BuildError,
... |
# -*- coding: utf-8 -*-
from storyruntime.enums.ReleaseState import ReleaseState
def test_locking():
assert ReleaseState.QUEUED.value == 'QUEUED'
assert ReleaseState.TERMINATING.value == 'TERMINATING'
assert ReleaseState.TERMINATED.value == 'TERMINATED'
assert ReleaseState.DEPLOYING.value == 'DEPLOYIN... |
from CAPITALIZER import CAPITALIZER
cap = CAPITALIZER()
if __name__ == "__main__":
c = cap.capitalize('id')
d = cap.capitalize('country')
e = cap.capitalize('country_id')
assert c == "ID", "Not capitalized properly"
assert d == "Country", "Wrongly capitalized"
assert e == "Country ID", "Splitt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Calculates the context variables for each green space feature
"""
__author__ = "Christina Ludwig, GIScience Research Group, Heidelberg University"
__email__ = "christina.ludwig@uni-heidelberg.de"
from ohsome import OhsomeClient, OhsomeException
import os
import glob
... |
# Generated by Django 2.1.11 on 2020-01-31 13:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
("auth", "0009_alter_user_last_name_max_length"),
migrations.swappable_d... |
from flask import *
import random
import string
import json
app = Flask(__name__)
with open("./settings/settings.json","r") as file:
settings = json.load(file)
base_url = settings["your_domain_or_url"]
def generate(keys):
code = ''.join(random.SystemRandom().choice(string.ascii_letters + string... |
from types import SimpleNamespace
from unittest.mock import call, Mock
import pytest
from pytest_mock import MockerFixture
from sonar.builders import SonarAPIError
from sonar.builders.docker import docker_push
def test_docker_push_is_retried(mocker: MockerFixture):
a = SimpleNamespace(returncode=1, stderr="some-... |
"""Support for Climate devices of (EMEA/EU-based) Honeywell evohome systems."""
from datetime import datetime, timedelta
import logging
import requests.exceptions
from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
STATE_AUTO, STATE_ECO, STATE_MANUAL, SU... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.