content stringlengths 5 1.05M |
|---|
from lib.base import PowerDNSClientAction, PowerDNSClientError
class RecordGetAction(PowerDNSClientAction):
"""
Get record data from a zone.
"""
def run(self, server_id, zone_name, name, response_timeout=5):
super().run(response_timeout)
try:
return (True, self.record_get(s... |
import datetime
from django.contrib.auth.models import User
from django.db import models
from .constants import (
DEFAULT_MEMBERSHIP_PERIOD,
DEFAULT_POSITION_PERIOD,
FEE_AMOUNT,
FEE_PAYMENT_TYPE,
MEMBER_POSITION,
)
class Member(models.Model):
class Meta:
ordering = ('id', 'user__fir... |
import subprocess
import os.path
# from repos_small import repos
from repos_full import repos
working_dir = "/tmp/the-great-archiving"
def run_command(cmd, dir=None):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=dir)
out, err = p.communicate()
if p.returncode ... |
import ImageMethods
import common
import OSMethods |
__all__ = ["SentProcessor", "DialogProcessor"]
import random
import warnings
from dataclasses import dataclass
from typing import Sequence, Optional, ClassVar
import nltk
import torch
import utils
from utils import VocabularyFactory
from datasets import Turn
from datasets import Dialog
from .common import DialogStat... |
#!/usr/bin/env python3
"""
Analyze binary dump for bank accounts jepsen test.
To create dump set tserver flag dump_transactions to true and reproduce the issue.
In will generate DUMP.* files to logs dir.
Copy files from all nodes to the same folder and specify this folder as an argument to analysis
script.
"""
impor... |
import json
from jenks import jenks
def test_json():
data = json.load(open('test.json'))
breaks = jenks(data, 5)
assert [round(float(v), 5) for v in breaks] == \
[0.00281, 2.09355, 4.2055, 6.17815, 8.09176, 9.99798]
def test_short():
data = [1, 2, 3, 100]
breaks = jenks(data, 2)
assert... |
def bfs(nodes, edges, start):
size = len(nodes)
checks = [False] * size
queue = []
path = []
# init dfs
queue.append(start)
checks[start] = True
path.append(start)
# do dfs
while len(queue) > 0:
this = queue.pop(0)
for n in range(len(edges[this])):
... |
import json
import os
import sys
import pathlib
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
root_dir = str(pathlib.Path(__file__).absolute().parents[5])
sys.path.insert(0, os.path.join(root_dir, 'modelflow'))
from mode... |
import json
def get_json_from_file(filename):
with open('tests/test_data/%s' % filename) as json_file:
return json.load(json_file)
# Test data
valid_droplet = {
"name": "t1.techno24x7.com",
"region": "nyc1",
"size": "s-8vcpu-16gb",
"image": 68259296,
"ssh_keys": [27410347, 27608055, ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-29 00:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='data',
... |
import logging
import requests
from time import sleep
from kalliope.core.NeuronModule import (
NeuronModule,
MissingParameterException,
InvalidParameterException,
)
logging.basicConfig()
logger = logging.getLogger("kalliope")
Spotify_Actions = (
"ADD",
"CURRENT",
"NEXT",
"LOAD",
"PAUS... |
# -*- coding: utf-8 -*-
"""
Modzy
Modzy QGIS plugin
-------------------
begin : 2022-01-01
copyright : (C) 2022 by Modzy
email : support@modzy.com
This script initializes the plugin, making it known to QGIS.
"""
__auth... |
import unittest
from unittest.mock import patch
from pathlib import Path
from .. import *
class _TestGameEngine(game_engine.BaseClass):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.ID = kwargs.get('ID', str(id(self)))
self.register = kwargs.get('register', True)
se... |
from django.db import models
class Cliente(models.Model):
nombre = models.CharField(max_length=60)
apellido_paterno = models.CharField(max_length=60)
apellido_materno = models.CharField(max_length=60)
direccion = models.CharField(max_length=60)
edad = models.CharField(max_length=60)
dni = mod... |
import tensorflow as tf
import numpy as np
import math
class NeuInfer(object):
"""
The proposed NeuInfer model
"""
def g_theta(self, o_i, o_j, scope='g_theta', reuse=tf.AUTO_REUSE):
"""
g_theta: Obtain the interaction vector of the o_i (hrt) and o_j (aivi)
"""
with tf.var... |
from datetime import date, datetime
from forms_api.fields.base_field import ERROR_REQUIRED
from forms_api.fields.date_field import (
ERROR_NOT_VALID_DATE,
DateField,
coerce_date
)
from tests.fields.utils import FieldTestCase
class TestDateField(FieldTestCase):
def test_common(self):
self.do_c... |
from .tests import TestWCAPI
|
class alfabeta:
def searchMoveComputer1(self, initialState):
alfa = -250000
beta = 250000
(v, (line, column)) = self.maxim(initialState, alfa, beta)
return (line, column)
def searchMoveComputer2(self, initialState):
alfa = -250000
beta = 250000
(v, (line,... |
strinput = str(input("Input String"))
char=""
result = ([])
count = 0
for i in strinput:
result.append(i)
for i in result:
if char == i:
count = count + 1
else:
if count != 0:
print(char,count)
count = 1
char = i
print(char, count) |
import torch
import numpy as np
eps = 1e-8
class PCKh(object):
"""docstring for PCKh"""
def __init__(self, opts):
super(PCKh, self).__init__()
self.opts = opts
self.LB = -0.5 + eps if self.opts.TargetType == 'direct' else 0 + eps
def getPreds(self, hm):
assert len(hm.shape)... |
#!/usr/bin/python
# #/***************************************************************************
# RoVi1 scrip for all exersice Robotcs part
# Copyright (c) 2018, Mathias W. Madsen <matam14@student.sdu.dk> <mwittenm@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or withou... |
from structures.ngram_trie import NgramTrie
import random
import math
class LanguageModel(object):
def __init__(self, n, reference):
self.n = n # order of n_gram
self.lambda_ = 0.9
self.delta = 0.1
self.ref = reference # pointer to doc_analyzer.stats
def linear_interpolation(se... |
#!/usr/bin/env python
import os
os.environ.setdefault('SETTINGS_MODULE', 'data.settings_modules.vagrant')
from flask_script import Manager
from data.settings import DATABASES
from web import app
manager = Manager(app)
@manager.command
def dbshell():
db = DATABASES['mydb']
args = ["psql", "--host=%s" % db['HO... |
# This Python file uses the following encoding: utf-8
# ___________________________________________________________________
# tempfiles.py
# rosevomit.core.tempfiles
# ___________________________________________________________________
"""A logic module that handles files in the /temp directory."""
import os
import pat... |
#
# PySNMP MIB module CISCO-FCIP-MGMT-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-FCIP-MGMT-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:58:19 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
#!/usr/bin/python3.5
import argparse
import asyncio
import logging
import typing
from autobahn.asyncio.websocket import WebSocketServerFactory
from autobahn.asyncio.websocket import WebSocketServerProtocol
from autobahn.websocket.protocol import ConnectionRequest
from autobahn.websocket.types import IncomingMessage
L... |
import numpy as np
from utils import OUNoise, ReplayBuffer
from actor import Actor
from critic import Critic
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# Parameters for continuous control are taken from DDPG paper.
# Continuous Control with Deep Reinfo... |
from django.apps import AppConfig
class AnimalappConfig(AppConfig):
name = 'animalapp'
|
from typing import List
import clue
from clue import BLANK, HAS_CARD, DOESNT_HAVE_CARD, MASTER_DETECTIVE
class Scoresheet:
"""
Stores all the info you learn during a game
"""
def __init__(
self,
players_names: List[str],
current_player: str,
game: clue.Game = MASTER_DE... |
"""
Copyright (C) 2018 Intel Corporation
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,
softw... |
from .base_page import BasePage
from .locators import ProductPageLocators
class ProductPage(BasePage):
def add_to_basket(self):
assert self.is_element_present(*ProductPageLocators.ADD_BUTTON), \
"Button is not present"
button = self.browser.find_element(*ProductPageLocator... |
from aioredis.abc import AbcChannel, AbcConnection, AbcPool
__all__ = [
"AbcConnection",
"AbcPool",
"AbcChannel",
"AbcCluster",
]
class AbcCluster(AbcConnection):
pass
|
import hashlib
def crack_sha1_hash(hash, use_salts=False):
if use_salts:
with open('known-salts.txt', 'r') as f:
salts = [salt.strip() for salt in f.readlines()]
with open('top-10000-passwords.txt', 'r') as f:
passwords = [password.strip() for password in f.readlines()]
for p... |
import django
import pytest
from django.core import management
def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}},
... |
# -*- coding:utf-8 -*-
from util import maybe_download
def prepare_ptb( files = {'train': './ptb/ptb.train.txt',
'test': './ptb/ptb.test.txt',
'valid': './ptb/ptb.valid_txt'} ):
train_url = 'https://raw.githubusercontent.com/tomsercu/lstm/master/data/ptb.train.t... |
import os
import re
import glob
import pickle
def make_filename(obj, attr=None, filename=None):
def splitpath(path):
if path is None:
print('No valid file specified.')
tmp = path.split('/')
fname = tmp[-1]
path = os.path.abspath('/'.join(tmp[:-1])) + '/'
return... |
'''
Tests for the file state
'''
# Import python libs
import os
#
# Import salt libs
from saltunittest import TestLoader, TextTestRunner
import integration
from integration import TestDaemon
class CMDTest(integration.ModuleCase):
'''
Validate the cmd state
'''
def test_run(self):
'''
c... |
#!/usr/bin/env python2
# Copyright 2017 The Imaging Source Europe GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
from app.api.v1.models.party_models import PartyModels
import json
from flask import make_response, jsonify, request
class validate:
@classmethod
def check_party_if_exist(cls):
data = request.get_json()
name = data['name']
hqAddress = data['hqAddress']
logoUrl = data['logoUrl'... |
import requests
from .exceptions import *
class RequestsHelper:
def __init__(self):
self._baseUrl = ''
self._headers = {}
@staticmethod
def _processResponse(response):
if response.status_code in [200]:
# this will raise json.decoder.JSONDecodeError on failure
# i'm intentionnaly not cat... |
def lambda_handler(event, context):
import boto3
import math
import json
client = boto3.client('ec2')
raw_json = event['Records'][0]['Sns']['Message']
details = json.loads(raw_json)
dimensions = details['Trigger']['Dimensions']
filesystem = ""
instance_id = ""
for dimension in dimensions:
if... |
'''
01 - Creating timezone aware datetimes
----------------------------------------------------
- Import timezone.
- Set the tzinfo to UTC, without using timedelta.
----------------------------------------------------
'''
# Import datetime, timezone
from datetime import datetime, timedelta, timezone
# October 1, 2017... |
#!/usr/bin/env python2
import sys
import datetime
if len(sys.argv) != 4:
print "%s YEAR COPYYEAR NUMDAYS" % sys.argv[0]
sys.exit(0)
YEAR = int(sys.argv[1])
COPYYEAR = int(sys.argv[2])
DAY_COUNT = int(sys.argv[3])
description = """abcdefghijklmnopqrstuvwqyz.?{}-abcdefghijklmnopqrstuvwqyz.?{}abcdefghijklmnopqr... |
from dico1 import entrer_dico
dico1 = entrer_dico('fichier1.csv', int)
dico1['Amaury'] = 16
for nom, age in dico1.items():
print(f"{nom} a {age} ans.") |
class Deque(object):
def __init__(self):
self._items = []
def is_empty(self):
return self._items == []
def add_front(self, item):
self._items.append(item)
def add_rear(self, item):
self._items.insert(0, item)
def remove_front(self):
return self._items.pop(... |
"""Abstraction for a collection of transformations that can be applied together on any crystal."""
import copy
from typing import Optional, Tuple
import numpy as np
from atompack.crystal.crystal import Crystal
from atompack.crystal.spatial import Orientation, Plane
class Transform(object):
"""Representation of... |
#!/usr/bin/env python
# coding: utf-8
import csv
from time import time
from math import ceil
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, Cropping2D, MaxPooling2D, Lambda, BatchNormalization, Dropout, Activation
import matplotlib.image as mpimg
import numpy as np
from sklearn.mo... |
# A quick intro to implement the Distributed Data Parallel (DDP) training in Pytorch.
# To simply this example, we directly load the ResNet50 using ```torch.hub.load()```,
# and train it from the scratch using the CIFAR10 dataset.
# Run this python script in terminal like "python3 DDP_training.py -n 1 -g 8 -nr 0"
imp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-10-31 02:43
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
from django.utils.timezone import utc
import django_pr... |
import datetime
import pytest
import pytz
import requests # XXX: C4-211
import webtest
from dateutil.parser import isoparse
from ..ingestion.common import CGAP_CORE_PROJECT
from ..types.variant import build_variant_sample_annotation_id
from .variant_fixtures import VARIANT_SAMPLE_URL
pytestmark = [pytest.mark.worki... |
import graphene
from graphene_django.types import DjangoObjectType
from main.models import DummyModel
class DummyType(DjangoObjectType):
class Meta:
model = DummyModel
class Query(graphene.ObjectType):
all_dummies = graphene.List(DummyType)
def resolve_all_dummies(self, info, **kwargs):
... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("localgroups", "0002_localgroup_ordering")]
operations = [
migrations.AddField(
model_name="localgroup",
name="last_edited",
field=models.DateTimeField(blank=True, edi... |
# Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmcls.models import build_loss
def test_asymmetric_loss():
# test asymmetric_loss
cls_score = torch.Tensor([[5, -5, 0], [5, -5, 0]])
label = torch.Tensor([[1, 0, 1], [0, 1, 0]])
weight = torch.tensor([0.5, 0.5])
loss... |
import unicodedata
from collections import defaultdict
from csv import DictReader
from biothings.utils.dataload import dict_sweep, open_anyfile
def load_data(input_file):
with open_anyfile(input_file) as in_f:
for line in in_f:
_id,caid = line.strip().split()
yield {
... |
# -*- coding: utf-8 -*-
"""
dfmapper
~~~~~~~~
:copyright: (c) 2018 by Tsuyoshi Tokuda.
:license: MIT, see LICENSE for more details.
"""
from dfmapper.mapper import DataFrameMapper
from dfmapper.column import (
BoolColumn,
DateTimeColumn,
FloatColumn,
IntColumn,
StrColumn,
creat... |
import smart_imports
smart_imports.all()
def calculate_power_fractions(all_powers):
# находим минимальное отрицательное влияние и компенсируем его при расчёте долей
minimum_power = 0.0
for power in all_powers.values():
minimum_power = min(minimum_power, power)
total_power = 0.0
for po... |
"""This module is for parsing and conversion functions that needs
objects from both music library and music service data structures
"""
from __future__ import absolute_import
import logging
from .xml import (
XML, ns_tag
)
from .data_structures import _DIDL_CLASS_TO_CLASS
from .exceptions import DIDLMetadataEr... |
import os
from flask import Flask, request, render_template, send_from_directory
from into_model import check_model
__author__ = 'narmada'
google_api_key = <your street view api key>
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
@app.route("/")
def index():
retur... |
import logging
from os.path import abspath, join, dirname
from os import pardir
_ROOT = abspath(
join(
dirname(abspath(__file__)),
pardir
)
)
# SCRAPER_LOG = join(_ROOT, "db", "log.json")
LOGGING_LEVEL = "INFO"
log = logging
log.basicConfig() # format='%(asctime)s %(message)s')
log.getLogge... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import k as kB, u
from latexplot import latexplot
import matplotlib as mpl
pgf_with_latex = { # setup matplotlib
"pgf.texsystem": "pdflatex",
"font.family": "serif",
"pgf.preamble": [
r"\usepackage[utf8]{in... |
import numpy as np
import torch
from pymoo.factory import get_mutation
from pymoo.core.mutation import Mutation
from lambo import utils
from lambo.tasks.chem.logp import prop_func
from lambo.models.mlm import sample_tokens
def get_mlm_mutation(mlm_obj, problem, cand_idx, res_idx):
seqs = [problem.candidate_poo... |
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019 Benjamin Marandel - All Rights Reserved.
################################################################################
"""
This module defines the class ESTPPolicyOnDemandScan.
"""
import x... |
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon En... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from settings.base import _
pictograms = {
'ADAPTER_PLUG': {
'filename': 'adapter_plug_1.png',
'title': _('Adapter Plug'),
'search_keywords': [
_('adapter plug'), _('adapter'), _('plug'), _('outlet'),
_('power adaptor')... |
import tornado.ioloop
import tornado.web
from tornado.options import define,parse_command_line,options
define('port',default=8081,type=int) #定义默认的启动端口号为8081
class MainHandler(tornado.web.RequestHandler): #请求处理的类视图
#继承于RequestHandler类
def get(self):
self.write('命令行启动的时候我可以自定义端口号') #以字符串为参数写入到http的响应中
... |
import aladhan
import pytest
@pytest.mark.asyncio
async def test_current():
async with aladhan.Client(True) as client:
assert isinstance(await client.get_current_time("Africa/Algiers"), str)
assert isinstance(await client.get_current_date("Africa/Algiers"), str)
assert isinstance(
... |
from flask_restful import Resource, reqparse, request, abort, fields, marshal_with, \
marshal
from flask import jsonify
from http import HTTPStatus
from models import User
from Services.GetUserService import GetUserService
from extensions import db
from Services.S3StoryService import *
import werkzeug.datastructure... |
"""
Django settings for eeia_moteur_recherche project.
Generated by 'django-admin startproject' using Django 3.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""... |
from sdl2 import *
from ctypes import *
class APU:
sample_rate = 44100
buffer_size = 512
def __init__(self):
self._sound_1 = Sound1()
self._sound_2 = Sound2()
self._sound_3 = Sound3()
self._sound_4 = Sound4()
self._sound_5 = Sound4()
self.channel_1_volume ... |
from teanaps.nlp import MorphologicalAnalyzer
from teanaps.nlp import NamedEntityRecognizer
from teanaps.nlp import SyntaxAnalyzer
import configure as con
from bs4 import BeautifulSoup
import urllib.request
import json
class SkillHandler():
def __init__(self):
self.ma = MorphologicalAnalyzer()
... |
from gensim.models import Word2Vec
import logging
logging.basicConfig(filename="embed.log", level=logging.DEBUG)
from gensim.models.word2vec import PathLineSentences
import copy
import numpy as np
import pickle
class EmbeddingsLearner(object):
def __init__(self, path_to_docs):
self.sentences = PathLineSe... |
from .database import Database
from .Room import Room
from .Token import Token
class Permissions:
_token = None
_room = None
def token(self):
return Token.from_id(self._token)
def room(self):
return Room.from_id(self._room)
def write(self):
c = Database().get_cursor()
... |
"""
Missing Int: Given an input file with four billion non-negative integers, provide an algorithm to
generate an integer that is not contained in the file. Assume you have 1 GB of memory available for
this task.
In - file_name: str
Out - int
1GB fits how many ints?
1 int is 4 bytes
1GB is ~ 1000_000_000 bytes
mean... |
import os
from jinja2 import (
ChoiceLoader,
Environment,
FileSystemLoader,
PackageLoader,
Template,
select_autoescape,
)
from . import LockingDict, config, environment
ENV: Environment = Environment(
loader=ChoiceLoader(
[
FileSystemLoader(
[os.sep.jo... |
import io
import os
from PIL import Image
class ImageWrapper:
def __init__(self, path: str):
self.path = path
self.basename = os.path.basename(self.path)
self.filename, self.extension = os.path.splitext(self.basename)
self._image = None
self._bytes = None
with ope... |
"""
Support for Netgear LTE modems.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/netgear_lte/
"""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
import attr
import aiohttp
from homeassistant.const import (
... |
"""Copy the contents from ranger.py to ~/.config/ranger/commands.py and
modify the username."""
import os
import subprocess
from ranger.api.commands import Command
from ranger.container.file import File
class screenshothelper(Command):
""":screenshothelper <file>.
Upload files with screenshot-helper
"""... |
#!/usr/bin/env python
from jinja2 import Environment, FileSystemLoader
from netaddr import IPNetwork, IPAddress
network = IPNetwork("172.16.1.0/24")
subnets = [str(subnet) for subnet in list(network.subnet(31))[:10]]
interfaces = ["ge-0/0/{}".format(x) for x in range(10)]
template_name = "manyj.txt"
env = Environmen... |
import torch
import numpy as np
import pickle
torch.manual_seed(17)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(17)
import argparse
import torch.nn as nn
import torch.nn.functional as F
import matplotlib
import os
from rational.torch import Rational, RecurrentRationa... |
#Embedded file name: nginx.py
import urlparse
import re
if 0:
i11iIiiIii
def assign(service, arg):
if service != '''www''':
return
else:
OO0o = urlparse.urlparse(arg)
return (True, '''%s://%s/''' % (OO0o.scheme, OO0o.netloc))
if 0:
Iii1I1 + OO0O0O % iiiii % ii1I - ooO0OO... |
# Copyright 2021 Fedlearn 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 writi... |
#
from .Entity import Entity
#
class Operation(Entity):
class meta:
type = 'operation'
name = 'operation'
model = {}
addToModel = False
#
def __init__(self, args={}):
super().__init__(args)
self.signature = ""
self.local_namespace = ""
self... |
# Done by Carlos Amaral (2020/09/22)
# SCU 4.8 - Use a while loop
i = 0
while i < 10:
i = i + 1
print("This is an important message!")
|
import numpy as np
import accel.math.pyceres as ceres
""" linalg -> osqp -> pyceres
linalg:
min r^Tr
s.t. r = Ax - b
osqp:
min r^Tr
"""
# TODO
import numpy as np
from scipy.optimize import linprog
class LinearProgram(object):
MIN = 0
MAX = 1
EQ = 2
GEQ = 3
LEQ = 4
"""A flexing, adaptive ... |
"""
Question 5
Create a dictionary containing as keys the letters from A-Z, the values should be random numbers created from the
random module. Can you draw a bar of the results.
"""
import matplotlib.pyplot as plt
import random
keys_number = dict()
keys = 'abcdefghijklmnopqrstuvwxyz'.upper()
for letter in keys:
ke... |
# roifile_demo.py
"""Demonstrate the roifile module.
Use the roifile and tifffile modules to read and write the results of image
segmentation from/to ImageJ TIFF files.
"""
import numpy
from matplotlib import pyplot
from skimage.measure import find_contours, label, regionprops
from tifffile import TiffFile, imwrite... |
# Copyright (C) 2022 Hottinger Bruel and Kjaer Benelux B.V.
# Schutweg 15a
# 5145 NP Waalwijk
# The Netherlands
# http://www.hbm.com
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without r... |
#!/usr/bin/env python
from gomatic import *
configurator = GoCdConfigurator(HostRestClient("localhost:8153"))
f = open("/var/lib/... |
from django.db import models
class LookupGroup(models.Model):
name = models.CharField(max_length=255)
lookup_id = models.CharField(max_length=255, unique=True)
def __str__(self):
return "%s (%s)" % (self.name, self.lookup_id)
|
from setuptools import setup
def read(fname):
return open(fname, 'rb').read().decode('utf-8')
setup(
name="pyzenfolio3",
version='0.10.0',
author='Lucas Messenger',
description=("Light-weight Zenfolio API Python wrapper."),
python_requires='>=3.6',
long_description=read('README.md'),
... |
from styx_msgs.msg import TrafficLight
import os
import sys
import time
from PIL import Image
import numpy as np
import tensorflow as tf
import rospy
DETECTION_THRESHOLD = 0.8
class TLClassifier(object):
def __init__(self, model_path):
# Import tensorflow graph
self.detection_graph = tf.Graph()... |
#!/usr/bin/env python
"""
This script is mainly for running autotests on the build server, however, it
can also be used by engineers to run the tests locally on their machines.
It takes as optional parameters the path to the folder containing the test
executables (which must have names ending in _tests), and a list... |
t = int(input("Podaj liczbę przypadków (wyrazów sumy): \n"))
s = 0
for i in range(t):
x = int(input("podaj wyraz sumy:\n"))
s = s + x
print("Suma ",t," wyrazów wynosi: ",s)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: David Corre
# email: corre@lal.in2p3.fr
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import ascii, fits
from astropy.table import vstack, Table
from astropy import wcs
from astropy.wcs import WCS
import astropy.coordinates as coord
from as... |
import argparse
import glog
import os
import json
if __name__ == "__main__":
""" Parse invalid JSON output to the valid one. """
CLI = argparse.ArgumentParser(
description='Provide the input folder and output folder')
CLI.add_argument(
'-i',
'--input',
default="final_pns",
... |
#
# (C) Copyright 2012-2013 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergove... |
# Copyright 2007 Baptiste Lepilleur and The JsonCpp Authors
# Distributed under MIT license, or public domain if desired and
# recognized in your jurisdiction.
# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
from __future__ import print_function
from __future__ import unicode_literals
f... |
import subprocess
import unittest
import copy
import pickle
import math
import os
import numpy as np
from scipy.constants import N_A
from monty.serialization import loadfn, dumpfn
from pymatgen.util.testing import PymatgenTest
from mrnet.network.reaction_generation import ReactionIterator, EntriesBox
from mrnet.stoch... |
import unittest
import numpy as np
from .gui import *
class TestOptionsDialog(unittest.TestCase):
def test_io(self):
dialog = OptionsDialog(0,0) # Index zero for human players
output_getter = dialog.get_players()
target_output = (0,0)
np.testing.assert_equal(output_getter, target_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.