text stringlengths 1 927k |
|---|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# 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... |
"""
File to define the entry point to Model Server
"""
import os
import re
import subprocess
import sys
import tempfile
from builtins import str
import platform
import psutil
from ts.version import __version__
from ts.arg_parser import ArgParser
def start():
"""
This is the entry point for model server
... |
#!/usr/bin/env python
import cv2
import numpy as np
import math
import csv
import rospy
from sensor_msgs.msg import Image
from geometry_msgs.msg import PoseStamped
from std_msgs.msg import Float32
from cv_bridge import CvBridge, CvBridgeError
import sys
import threading
from dynamic_reconfigure.server import Server
fr... |
#
# @lc app=leetcode id=623 lang=python3
#
# [623] Add One Row to Tree
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class... |
#
# PySNMP MIB module MOXA-IAW5x50A_IO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MOXA-IAW5x50A_IO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:03:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import os
import pickle
import re
from collections import defaultdict
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix, roc_auc_score... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
from __future__ import absolute_import, print_function
import ... |
from biocyc.base_data_file_parser import BaseDataFileParser
from common.constants import *
from common.graph_models import *
ATTR_NAMES = {
'UNIQUE-ID': (PROP_BIOCYC_ID, 'str'),
'COMMON-NAME': (PROP_NAME, 'str'),
'ABBREV-NAME': (PROP_ABBREV_NAME, 'str'),
'MOLECULAR-WEIGHT-KD': (PROP_MOL_WEIGHT_KD, 'st... |
#boggle matrix analysis main app
def find_adjacent_nodes(row_index, col_index):
adjacent_nodes = []
temp_num_pair = []
count = 0
while count < 9:
if count == 0:
temp_num_pair = [row_index-1, col_index-1]
elif count == 1:
temp_num_pair = [row_index-1, col_index]
... |
import gym
from gym.spaces.discrete import Discrete
from gym.spaces import Box
import matplotlib.pyplot as plt
from collections import deque
from .boxworld_gen import *
class BoxWorld(gym.Env):
"""Boxworld representation
Args:
n (int): Size of the field (n x n)
goal_length (int): Number of keys t... |
#Numeral
print("Hola Mundo") |
#!/usr/bin/env python3
from ..variational import CholeskyVariationalDistribution, GridInterpolationVariationalStrategy
from .abstract_variational_gp import AbstractVariationalGP
import warnings
class GridInducingVariationalGP(AbstractVariationalGP):
def __init__(self, grid_size, grid_bounds):
warnings.wa... |
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import sys
import glob
import os
import json
from Training.Client import ServiceClient
import Training.Stanford
import Training.OpenNLP
import Training.GATE
import TokenType
"""
This is the Feature Library which will take the input files and
user selected features. It will determine the sequence of pipeline to be cal... |
"""
Test parameters i.e. sample data, known past errors, etc.
"""
from functools import lru_cache
from pathlib import Path
from traceback import print_tb
from typing import List
import geopandas as gpd
import numpy as np
import pandas as pd
import pytest
from click.testing import Result
from hypothesis.strategies impo... |
"""
Django settings for Zero project.
Generated by 'django-admin startproject' using Django 3.2.6.
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 pathlib im... |
import re
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
from django.forms import widgets
from django.core.mail import send_mail
from django.conf import settings as django_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import... |
import ast
def ast_attr(fields):
""" fields is string of attrs (e.g. 'self.call.me.now') or list of ast args"""
if isinstance(fields, str):
if "." in fields:
fields_list = fields.split(".")
return ast.Attribute(attr=fields_list[-1], value=ast_attr(".".join(fields_list[:-1])))
... |
# -*- coding: utf-8 -*-
"""
Created on: 2019/4/10 13:46
@author: its_cyx
"""
from utils import load_mldata
from sklearn.linear_model import Perceptron
X_train, y_train, X_test, y_test = load_mldata.fetch_mnist()
# 二分类:数字5和其他
y_train_5 = (y_train == 5)
y_train_5 = y_train_5.ravel()
y_test_5 = (y_test == 5)
y_test_5 ... |
"""py.test config"""
import collections
import sys
import threading
from collections import deque
from time import sleep
import pytest
from circuits import BaseComponent, Debugger, Manager, handler
from circuits.core.manager import TIMEOUT
class Watcher(BaseComponent):
def init(self):
self._lock = thr... |
import json
import datetime
import traceback
import re
from base64 import b64encode
from ast import literal_eval
from flask import Blueprint, render_template, make_response, url_for, current_app, request, redirect, jsonify, abort, flash, session
from flask_login import login_required, current_user
from ..decorators im... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/firework/shared_firework_two.iff"
result.attribute_template_id = -1... |
from operator import eq
def assert_contains(collection, *items, **kwargs):
"""Check that each item in `items` is in `collection`.
Parameters
----------
collection : list
*items : list
Query items.
count : int, optional
The number of times each item should occur in `collection`... |
from main import p, initial_node
from solution import Solution
initial_depth = int(input('please input initial depth:'))
solution = Solution()
def recursive_dls(node, problem, limit):
if problem.goal_test(node.state):
solution.print_goal(node.state)
depth = 0
path = []
while node.... |
import json
import logging
import random
import time
import traceback
from ceph.rados_utils import RadosHelper
log = logging.getLogger(__name__)
def run(ceph_cluster, **kw):
"""
CEPH-83571452 RADOS:
Corrupt snap info of an object and run
list-inconsistent-snapset
Steps:
1. create a repli... |
"""This module represents the object to write to azure queue that the DM is listening to."""
import json
import uuid
from datetime import datetime
class _IngestionBlobInfo:
def __init__(self, blob_descriptor, ingestion_properties, auth_context=None):
self.properties = dict()
self.properties["Blob... |
from typing import Callable, Union
import torch
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.typing import OptPairTensor, Adj, Size
from unsupervised.convs.inits import reset
class WGINConv(MessagePassing):
def __init__(self, nn: Callable, eps: float = 0., train_... |
import sets
import ckan
from ckan.plugins import SingletonPlugin, implements, IPackageController
from ckan.plugins import IGroupController, IOrganizationController, ITagController
import pylons
from ckan.logic import get_action
from pylons import config
LANGS = ['en', 'fr', 'de', 'es', 'it', 'nl', 'ro', 'pt', 'pl']
d... |
from collections import Counter
import sqlite3
import os
from math import ceil
import datetime
import time
def leap_year(year):
"""
checks year parameter to see if the given year is a leap year.
:param year: accepts INT between 0-9999
:return: BOOLEAN True or False
"""
if year % 400 == 0:
... |
# // _ooOoo_
# // o8888888o
# // 88" . "88
# // (| -_- |)
# // O\ = /O
# // ____/`---'\____
# // .' \\| |// `.
# // / \\||| : |||// \
# // / _||||| -:- |||||- \
# // ... |
FILE_PATH = "test.json"
EXAMPLE_JSON = '{"_type": "Holder", "_module": "tests.test_classes.holder", "objects": [{"_type": "Foo", "_module": "tests.test_classes.foo"}, {"_type": "Bar", "_module": "tests.test_classes.bar"}]}'
# Formatted EXAMPLE_JSON
# {
# "_type": "Holder",
# "_module": "tests.test_classes.hol... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typi... |
# Input: number of iterations L
# number of labels k
# matrix X of features, with n rows (samples), d columns (features)
# X[i,j] is the j-th feature of the i-th sample
# vector y of labels, with n rows (samples), 1 column
# y[i] is the label (1 or 2 ... or k) of the i-th samp... |
"""
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2007-2015 Dirk Beyer
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
... |
line = input().split(" ")
n = int(line[0])
k = int(line[1])
for _ in range(k):
if n % 10 == 0:
n /= 10
else:
n -= 1
print(int(n)) |
import logging
import re
from collections.abc import MutableSet
from datetime import datetime
from sqlalchemy import Column, DateTime, ForeignKey, Integer, Unicode, and_, func
from sqlalchemy.orm import relationship
from flexget import plugin
from flexget.db_schema import versioned_base, with_session
from flexget.ent... |
#!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
import click
from globus_cli.parsing import command, task_id_arg
from globus_cli.safeio import FORMAT_TEXT_RECORD, formatted_print
from globus_cli.services.transfer import get_client, iterable_response_to_dict
COMMON_FIELDS = [
("Label", "label"),
("Task ID", "task_id"),
("Is Paused", "is_paused"),
("... |
# ************************************************************
# |docname| - Routines shared between the server and WAF build
# ************************************************************
#
# Imports
# =======
# These are listed in the order prescribed by `PEP 8
# <http://www.python.org/dev/peps/pep-0008/#imports>`_.
... |
import unittest
from test import test_support
import string
import StringIO
mimetools = test_support.import_module("mimetools", deprecated=True)
msgtext1 = mimetools.Message(StringIO.StringIO(
"""Content-Type: text/plain; charset=iso-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Foo!
"""))
class MimeToolsT... |
from distutils.core import setup
import matcensor.main
setup(
name='matcensor',
version=matcensor.main.__version__,
packages=['matcensor'],
url='https://github.com/Ar4ikov/matcensor',
license='Apache 2.0',
author='Nikita Archikov',
author_email='bizy18588@gmail.com',
description='A simp... |
import platform
from datetime import datetime, timezone
import pytest
import jsii
from json import loads
from jsii_calc import (
AbstractClassReturner,
Add,
AllTypes,
AllTypesEnum,
AmbiguousParameters,
AsyncVirtualMethods,
Bell,
Calculator,
ClassWithPrivateConstructorAndAutomati... |
"""model.__init__.""" |
######################################################################
#
# File: b2sdk/v1/__init__.py
#
# Copyright 2019 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
from b2sdk.v2 import * # noqa
f... |
###
### Copyright (C) 2018-2020 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ....lib.gstreamer.msdk.util import *
from ....lib.gstreamer.msdk.decoder import DecoderTest
spec = load_test_spec("av1", "decode", "8bit")
@slash.requires(*platform.have_caps("decode", "av1_... |
import json
import os
from abc import ABC, abstractmethod
from src import DATA_FOLDER, UNZIPED_FOLDER_NAME
from src import settings
from src.db_models.models import dict_db_models
from src.io import CNAE_JSON_NAME, NATJU_JSON_NAME, QUAL_SOCIO_JSON_NAME, MOTIVOS_JSON_NAME, PAIS_JSON_NAME, \
MUNIC_JSON_NAME
from src... |
# -*- encoding: utf-8 -*-
from shapely.wkt import loads as wkt_loads
import dsl
from . import FixtureTest
class RoadSortKeysRoads(FixtureTest):
def test_motorway(self):
# regular roads
self.generate_fixtures(dsl.way(26765956, wkt_loads('LINESTRING (-122.47355250051 37.80545687798148, -122.47367862... |
from boutdata.collect import collect
from boututils import calculus as calc
import math
import numpy as np
import bout_field as bf
phi=bf.Field(name='phi',dx=0.1)
n=bf.Field(name='n',dx=0.1)
vort=bf.Field(name='vort',dx=0.1)
print('collecting data')
phi.collect()
n.collect()
vort.collect()
print('computing mean fie... |
from fake_useragent import UserAgent
class Fetcher:
TYPE_GET = 'get'
TYPE_POST = 'post'
DEFAULT_TIMEOUT = 5.0
def __init__(self, logger):
self._logger = logger
self._agent = UserAgent()
self._headers = {
'dnt': '1', # Do Not Track
'user-agent': self._... |
"""
Последовательность Фибоначчи определяется так:
F[0] = 0, F[1] = 1, ..., F[n] = F[n-1] + F[n-2].
По данному числу n определите n-е число Фибоначчи F[n].
Формат ввода
Вводится натуральное число n.
"""
num1 = num2 = 1
n = int(input()) - 2
while n > 0:
num1, num2 = num2, num1 + num2
n -= 1
print(num2) |
import basket_completion as bc
import basket_generation as bg
import sys
import itertools
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import pandas
import warnings
import pickle
warnings.simplefilter(action='ignore', category=FutureWarning)
sys.path.insert(0, "../node2vec_embedding... |
from itertools import zip_longest
import matplotlib.pyplot as plt
import numpy as np
def extract_sublist(source, idx, default=0):
"""Return list from elements at idx for each sublist in source
or default if such element is empty string.
Args:
source (list): List of sublists.
idx (int): Elem... |
#!/usr/bin/env python
"""
CREATED AT: 2021/10/7
Des:
https://leetcode.com/problems/ugly-number/
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Easy
"""
class Solution:
def isUgly(self, n: int) -> bool:
"""
1013 / 1013 test cases passed.
Status: Accepted
Runtime: 32 ms
... |
# -*- coding: utf-8 -*-
"""
pyxform is a Python library designed to make authoring XForms for ODK
Collect easy.
"""
__version__ = "1.5.0"
from pyxform.builder import (
SurveyElementBuilder,
create_survey,
create_survey_element_from_dict,
create_survey_from_path,
create_survey_from_xls,
)
from pyxf... |
import re
import numpy as np
from collections import namedtuple
from cStringIO import StringIO
from PIL import Image
from selenium.webdriver.remote.webelement import WebElement
from wge.rl import State
from wge.utils import Phrase
class MiniWoBState(State):
"""MiniWoB state.
Warning: The return types might... |
#!/usr/bin/env python
# MIT License
# Copyright (c) 2017 Massimiliano Patacchiola
# https://mpatacchiola.github.io/blog/
#
# 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 restriction... |
#
# Copyright 2021 Logical Clocks AB
#
# 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 ag... |
# Copyright 2020 Alexis Lopez Zubieta
#
# 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 restriction, including without limitation the
# rights to use, copy, modify, merge, publi... |
import PIL
import PIL.Image
from functional import compose
import numpy as np
import argparse
lmap = compose(list, map)
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, earthians and Contributors
# See license.txt
from __future__ import unicode_literals
import unittest
class TestClinicalProcedureTemplate(unittest.TestCase):
pass |
# Generated by Django 2.1.2 on 2018-11-10 16:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('barns', '0004_auto_20181111_0014'),
]
operations = [
migrations.AddField(
model_name='sensordat... |
import asyncio
import collections
import dataclasses
import logging
import time
from concurrent.futures.process import ProcessPoolExecutor
from typing import Dict, List, Optional, Set, Tuple
from blspy import G1Element
from chiabip158 import PyBIP158
from hddcoin.util import cached_bls
from hddcoin.consensus.block_rec... |
"""
Copyright 2017-2018 Fizyr (https://fizyr.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 w... |
import csv
import re
from datetime import *
from time import *
from threading import Timer
import cpd_data
from tweepy import OAuthHandler
import tweepy
import sys
sys.path.append('code/tools')
sys.path.append('code/classification')
from features import get_feats
from tools import write_out_data
from cascade import ca... |
n1 = float(input('Nota 1: '))
n2 = float(input('Nota 2 :'))
print ('Média : {:.2f}'.format((n1+n2)/2)) |
from pathlib import Path
import ibis
import ibis.expr.types as ir
from ibis.backends.pandas.core import execute_and_reset
class FileClient(ibis.client.Client):
def __init__(self, backend, root):
self.dialect = backend.dialect
self.extension = backend.extension
self.table_class = backend.t... |
'''
Week 2 Coding Question (Isaac Chepkwony):
Reversing a sublist: Given the head of a linked list and two positions 'p' and 'q',
reverse the linked list from position 'p' to 'q'.
Ex.:
Original List 1-> 2-> 3-> 4-> 5-> null if p=2 and q=4
Resulting List 1-> 4-> 3-> 2-> 5-> null
----------------------------------------... |
# Ensure we get the local copy of tornado instead of what's on the standard path
import os
import sys
import time
sys.path.insert(0, os.path.abspath(".."))
import tornado
master_doc = "index"
project = "Tornado"
copyright = "2009-%s, The Tornado Authors" % time.strftime("%Y")
version = release = tornado.version
lan... |
#!/usr/bin/env python3
# ////////////////////////////////////////
# // seqLED.py
# // Blinks the USR LEDs in sequence.
# // Wiring:
# // Setup:
# // See:
# ////////////////////////////////////////
# // Tested: rcn-ee: 2021.12.15 - BBGG - 5.15.6-bone14
import Adafruit_BBIO.GPIO as GPIO
import time
LEDs=4
for i in ran... |
# credits to the respective owner xD
# imported by @heyworld
import requests
import re
import random
import urllib
import os
from telethon.tl import functions
import asyncio
from userbot import CMD_HELP
from userbot.events import register
COLLECTION_STRING = [
"epic-fantasy-wallpaper",
"castle-in-the-sky-... |
import unittest
import os.path
import pandas as pd
# import numpy as np
from quantipy import dataframe_fix_string_types
from quantipy.core.link import Link
from quantipy.core.stack import Stack
from quantipy.core.helpers.functions import load_json
from quantipy.core.view_generators.view_maps import QuantipyViews
class... |
# 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... |
# -*- coding: utf-8 -*-
from django.db import models, migrations
import webapp.apps.taxbrain.models
class Migration(migrations.Migration):
dependencies = [
('taxbrain', '0010_auto_20151016_0302'),
]
operations = [
migrations.AddField(
model_name='taxsaveinputs',
... |
# coding: utf-8
"""
ThingsBoard REST API
ThingsBoard Professional Edition IoT platform REST API documentation. # noqa: E501
OpenAPI spec version: 3.3.3PAAS-RC1
Contact: info@thingsboard.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_impo... |
# Owner(s): ["oncall: jit"]
import unittest
import os
import random
import enum
import copy
from functools import reduce
import operator
import warnings
import torch
from torch.nn import functional
from torch.profiler import profile, ProfilerActivity
from torch.testing._internal.codegen.random_topo_test import runDe... |
import pyrealsense2 as rs
import numpy as np
import cv2
import cv2.aruco as aruco
import glob
calibFile = cv2.FileStorage("calibData.xml", cv2.FILE_STORAGE_READ)
cmnode = calibFile.getNode("cameraMatrix")
mtx = cmnode.mat()
dcnode = calibFile.getNode("distCoeff")
dist = dcnode.mat()
criteria = (cv2.TERM_CRITERIA_EPS ... |
from django.conf.urls import include, url
from django.views.generic import TemplateView
urlpatterns = [
url(r'^interes_candidato/$',
TemplateView.as_view(template_name='registro_interes_candidato.html'),
name='interes_candidato'),
] |
"""
Copyright 2021 Dynatrace LLC
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
... |
__version__ = "0.1.0"
default_app_config = "rest_scaffold.apps.CustomConfig" |
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Matti Hamalainen <msh@nmr.mgh.harvard.edu>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Mads Jensen <mje.mads@gmail.com>
#
# License: BSD (3-clause)
import copy
import os.path as op
import numpy as np
from scipy imp... |
import pytest
from mock import patch
from src import ena_api
def get_acc(l):
return [r['run_accession'] for r in l]
def mocked_requests_post(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_... |
#!/usr/bin/env python
"""Extract final configurations for restarting serial runs."""
import argparse
import pdb
import sys
from origamipy import files
def main():
args = parse_args()
for temp in args.temps:
traj_inp_filename = '{}-{}.trj'.format(args.inp_filebase, temp)
traj_file = files.Un... |
import numpy as np
# prewitt x and y filters
PREWITTX = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], np.float32)
PREWITTY = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]], np.float32)
# Sobel x and y filters
SOBELX = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32)
SOBELY = np.array([[-1, -2, -1], [0, 0, 0... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import sqlite3
from collections import OrderedDict
from datetime import datetime, timedelta
import logging
import pandas as pd
from shapely.geometry import Polygon
from impactutils.extern.openquake.geodetic import geodetic_distance
EQTABLE = OrderedDict([('id', 'integer primary key'),
('sid', ... |
"""empty message
Revision ID: 20479bdf1e77
Revises:
Create Date: 2021-03-15 06:57:55.526838
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '20479bdf1e77'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
import os
import pickle
import subprocess
from ctypes import cdll, POINTER, c_int, c_double, c_bool, c_char_p, c_void_p
from numpy import array, ndarray, zeros, arange, issubdtype, integer, uintp, intc
from numpy.ctypeslib import ndpointer
def infer_simple_ctype(var):
if isinstance(var, int):
return c_in... |
#!/usr/bin/env python3
import cv2
import depthai as dai
stepSize = 0.02
newConfig = False
# Create pipeline
pipeline = dai.Pipeline()
# Define sources and outputs
monoLeft = pipeline.create(dai.node.MonoCamera)
monoRight = pipeline.create(dai.node.MonoCamera)
stereo = pipeline.create(dai.node.StereoDepth)
spatialL... |
#!/usr/bin/env python
import sys
import os
import wx
import six
import time
import datetime
import operator
from wx.lib.embeddedimage import PyEmbeddedImage
import images
try:
dirName = os.path.dirname(os.path.abspath(__file__))
except:
dirName = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path.appen... |
from typing import Any, Optional, Tuple, Type
from differently.exceptions import DeserializationError
from differently.json_differently import JsonDifferently
from differently.list_differently import ListDifferently
from differently.yaml_differently import YamlDifferently
def deserialize_value(
v: Optional[str],... |
from geem.models import Package
from rest_framework import serializers
# This skips contents field
class ResourceSummarySerializer(serializers.HyperlinkedModelSerializer):
#owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Package
fields = (
'id',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import os
for fn in glob.glob('results/*/*/log.txt'):
dname = os.path.dirname(fn)
new_fn = fn.replace('log.txt', 'log_heavy.txt')
os.rename(fn, new_fn)
fp = open('{}/log.txt'.format(dname), 'w')
for line in open(new_fn):
if 'iter' n... |
# download.py
import os
import sys
import urllib3
from urllib.parse import urlparse
import pandas as pd
import itertools
import shutil
from urllib3.util import Retry
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
classes = ["cat", "fish"]
set_types = ["train", "test", "val"]
def download_image... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__a... |
#
# Copyright 2020--2021 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
from setuptools import setup
VERSION = "1.1.0"
def readme():
with open("README.md") as f:
return f.read()
setup(
name="wimiapi",
version=VERSION,
description="Package to fetch the current external ip",
long_description_content_type="text/markdown",
long_description=readme(),
keywo... |
from bigml.api import BigML
api = BigML()
source1_file = "iris.csv"
args = \
{'fields': {'000000': {'name': 'sepal length', 'optype': 'numeric'},
'000001': {'name': 'sepal width', 'optype': 'numeric'},
'000002': {'name': 'petal length', 'optype': 'numeric'},
'000003': {'name': 'petal width', 'optype': 'numeric'},
'0000... |
###
# Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2008, James Vega
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyri... |
import sys
import click
import os
import datetime
from unittest import TestCase, main
from frigate.video import process_frames, start_or_restart_ffmpeg, capture_frames, get_frame_shape
from frigate.util import DictFrameManager, EventsPerSecond, draw_box_with_label
from frigate.motion import MotionDetector
from frigate.... |
# -*- coding: utf-8 -*-
"""
File Name: best-time-to-buy-and-sell-stock-with-transaction-fee.py
Author : jynnezhang
Date: 2020/12/17 1:40 下午
Description:
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
dp[i][0] 表示第 i 天交易完后手里没有股票的最大利润,
dp[i][1] 表示第 i 天交易完后手里持有一支股票的最... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.