text stringlengths 2 999k |
|---|
import urllib
import untangle
import xmltodict
query = "http://www.SupermarketAPI.com/api.asmx/COMMERCIAL_SearchByProductName?APIKEY=c9c2055184&ItemName="
def Fetch_Price( prod_name ):
new_query = query + urllib.parse.quote(prod_name)
content = urllib.request.urlopen(new_query).read()
content = str(conten... |
import collections
from collections import Counter
from sys import argv
script, filename1, filename2, filename3 = argv
import re
from Bio import SeqIO
p = open(filename1) # HMMTOP output file
record_dict = SeqIO.index(filename2, "fasta") # FASTA file
outfile = open(filename3, "w+") # Filename for extracted sequence... |
from collections import OrderedDict
import tensorflow as tf
import tensorflow.keras as keras
def weight_init(module):
if isinstance(module, keras.layers.Dense):
keras.initializers.glorot_uniform(module.weight)
module.bias.data.zero_()
class Policy(tf.keras.Model):
def __init__(self, input_s... |
#
# Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
import logging
import re
from io import BytesIO
from greengrass_common.function_arn_fields import FunctionArnFields
from greengrass_ipc_python_sdk.ipc_client import IPCClient, IPCException
from greengrasssdk.utils.testing import mock
... |
import numpy as np
import librosa.display
import librosa.output
import matplotlib.pyplot as plt
import sys
def get_file_audio(in_path, out_path):
data, sr = librosa.load(in_path, sr=44100)
_noise = np.array([])
_data = np.array([])
_flag_start = False
for d in data:
if _flag_start:
... |
# Copyright 2017 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 wri... |
'''
Script to train the ranker
Should add some sort of image pool someday...?
'''
import time
from options.train_options import TrainOptions
from data import CreateDataLoader
from models import create_model
from util.visualizer import Visualizer
from models import networks
import pdb
import torch
from collections imp... |
import time
import lib.stm32
import lib.stlinkex
class Flash():
ITCM_BASE = 0x00200000
FLASH_REG_BASE = 0x40023c00
FLASH_KEYR_REG = FLASH_REG_BASE + 0x04
FLASH_SR_REG = FLASH_REG_BASE + 0x0c
FLASH_CR_REG = FLASH_REG_BASE + 0x10
FLASH_CR_LOCK_BIT = 0x80000000
FLASH_CR_PG_BIT = 0x00000... |
import os
import re
import os.path
import re
from montreal_forced_aligner.command_line.validate import run_validate_corpus
root_corpus_dir = '/mnt/d/Data/speech/CommonVoice'
dictionary_root_dir = '/mnt/c/Users/michael/Documents/Dev/mfa-models/dictionary/staging'
config_template = '/data/mmcauliffe/GP_for_MFA/{}.yaml... |
#!/usr/bin/python
# *****************************************************************************
#
# 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 A... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import cv2
from opts_mayank_ddd_demo import opts
from detectors.detector_factory import detector_factory
from datasets.dataset_factory import dataset_factory
image_ext = ['jpg', ... |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.10
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ... |
# -*- coding: utf-8 -*-
import dash_core_components as dcc
import dash_html_components as html
from tutorial import styles
from textwrap import dedent as s
from tutorial import tools
from tutorial.utils.component_block import ComponentBlock
examples = {
'button': tools.load_example('tutorial/examples/core_compon... |
"""Unit tests for io module"""
import platform
import tempfile
import unittest.mock as mock
from pathlib import Path
import pandas as pd
import pytest
from packaging import version
import pandera as pa
import pandera.extensions as pa_ext
import pandera.typing as pat
try:
from pandera import io
except ImportErro... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-05 21:26
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import orchestra.models.communication.mixins
import orchestra.utils.models
class Migration(migrations.... |
import numpy as np
import matplotlib.pyplot as plt
N_DIMS = 5 # DNA size
DNA_SIZE = 10 # DNA (real number)
DNA_BOUND = [0, 20] # solution upper and lower bounds
N_GENERATIONS = 200
POP_SIZE = 100 # population size
N_KID = 50 # n kids per generation
TargePos=[10,10]
def Make... |
# Class handling other actions than scene uploading, which is done in sceneuploader.py
import rexviewer as r
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
import sceneactionsxml
class SceneActions:
def __init__(self, cap_url, controller):
... |
# --------------------------------------------------------
# Pytorch Meta R-CNN
# Written by Anny Xu, Xiaopeng Yan, based on the code from Jianwei Yang
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
... |
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All R... |
def show_fib_series(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def return_fib_series(n):
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
|
#!/usr/bin/env python3
# Copyright 2015-2020 Arm 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
from madmom.io.audio import load_audio_file
import numpy
import librosa
def load_wav(wav_in, stereo=False):
x, fs = load_audio_file(wav_in, sample_rate=44100)
if not stereo:
# stereo to mono if necessary
if len(x.shape) > 1 and x.shape[1] == 2:
x = x.sum(axis=1) / 2
# cast to... |
from flash.graph.classification.data import GraphClassificationData # noqa: F401
from flash.graph.classification.model import GraphClassifier # noqa: F401
|
# author: Karlos Muradyan
# date: 2020-01-24
'''This script does ML analysis by training multiple models, doing hyperparameter
tuning and reporting the results in a csv file.
Usage:
ml_analysis.py --train_csv=<train_csv> --test_csv=<test_csv> --output_csv=<output_csv> --output_png=<output_png>
ml_analysis.py... |
""" Router WAN information """
class Wan(object):
""" WAN information"""
def __init__(self, downspeed, maxdownloadspeed, history, devname, upload,
upspeed, maxuploadspeed, download):
self._downspeed = downspeed
self._maxdownloadspeed = maxdownloadspeed
self._history =... |
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2018 Justin Bewley Lo (justinbewley.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 restriction, including without limi... |
from conans import ConanFile, AutoToolsBuildEnvironment, tools
from conans.errors import ConanInvalidConfiguration
import functools
import os
required_conan_version = ">=1.36.0"
class Librasterlite2Conan(ConanFile):
name = "librasterlite2"
description = (
"librasterlite2 is an open source library tha... |
import sys
sys.path.append("Mask_RCNN")
import os
import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import random
import glob
import skimage
from config import Config
import imagestoosm.config as osmcfg
import utils
import model as modellib
import visualize
from model imp... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/melodic/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# Copyright 2009-2014 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software 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 copyright notice,
# this list of conditions ... |
from astropy.table import Table, join
import numpy as np
import astropy.coordinates as coord
import astropy.units as un
from astropy.time import Time, TimeDelta
from astroplan import Observer
import matplotlib.pyplot as plt
# update IERS Bulletin A table
# from astroplan import download_IERS_A
# download_IERS_A()
dat... |
# Strategy Pattern
from types import MethodType
import math
class IONumber(object):
MAXIMUM_INPUT_NUMBER = math.factorial(10)
MINIMUM_INPUT_NUMER = 0
@classmethod
def decimal_input(cls):
try:
decimal = int(input('Please enter decimal number: '))
except ValueError:
... |
import numpy as np
import gym
from collections import deque
import random
# Ornstein-Ulhenbeck Process
# Taken from #https://github.com/vitchyr/rlkit/blob/master/rlkit/exploration_strategies/ou_strategy.py
class OUNoise(object):
def __init__(self, action_space, mu=0.0, theta=0.15, max_sigma=0.3, min_sigma=0.3, dec... |
from spectrumuncurver import *
su = SpectrumUncurver() |
# coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from ppr... |
from __future__ import annotations
__author__ = "Florent Thoumie"
__email__ = "florent@thoumie.net"
__version__ = "0.3.4"
from .client import AqualinkClient, AqualinkLoginException
from .system import AqualinkSystem, AqualinkPoolSystem
from .device import (
AqualinkAuxToggle,
AqualinkBinarySensor,
Aquali... |
from simulator import DrivingSimulation, FetchSimulation
import numpy as np
class Driver(DrivingSimulation):
"""
Original Driver model from 'Asking easy questions: A user-friendly approach to active reward learning'
Bıyık, E., Palan, M., Landolfi, N. C., Losey, D. P., & Sadigh, D. (2019).arXiv preprint a... |
from resource import DataSet
from network import NetWork
import numpy as np
dataset = DataSet('', 0)
network = NetWork()
import sys
args = {
'-p1': None,
'-p2': None,
'-m': None
}
index = 1
while index < len(sys.argv):
i = sys.argv[index]
if i == '-p1':
args['-p1'] = sys.argv[index + 1]... |
"""The tests for the DD-WRT device tracker platform."""
import os
import unittest
from unittest import mock
import logging
import re
import requests
import requests_mock
from homeassistant import config
from homeassistant.bootstrap import setup_component
from homeassistant.components import device_tracker
from homeass... |
import einops
import torch
import torch.nn.functional as F
from torch.nn.modules.pixelshuffle import PixelShuffle
from torch.nn.utils.parametrizations import spectral_norm
from typing import List
from skillful_nowcasting.common import GBlock, UpsampleGBlock
from skillful_nowcasting.layers import ConvGRU
import logging
... |
"""
GTSAM Copyright 2010-2019, Georgia Tech Research Corporation,
Atlanta, Georgia 30332-0415
All Rights Reserved
See LICENSE for the license information
Point3 unit tests.
Author: Frank Dellaert & Fan Jiang
"""
import unittest
import gtsam
import numpy as np
from gtsam.utils.test_case import GtsamTestCase
class T... |
import os
from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
from conans.tools import Version
class CAFConan(ConanFile):
name = "caf"
version = "0.17.6"
description = "An open source implementation of the Actor Model in C++"
url = "https://github.com/bincraf... |
r"""
Sage categories quickref
- ``sage.categories.primer?`` a primer on Elements, Parents, and Categories
- ``sage.categories.tutorial?`` a tutorial on Elements, Parents, and Categories
- ``Category?`` technical background on categories
- ``Set... |
from django.contrib import admin
from .models import Handler
admin.site.register(Handler)
|
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... |
import sys
from download import download
import argparse
import os
def valid_dir(path):
if not os.path.isdir(path):
raise argparse.ArgumentTypeError('{} is not an existing directory'.format(path))
if not path.endswith(os.sep): path += os.sep
return path
parser = argparse.ArgumentParser()
parser.a... |
# Copyright 2019 The TensorFlow Probability 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 o... |
#!/usr/bin/python
#
# Copyright 2019 Polyaxon, 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 o... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_win.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainW... |
# 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... |
"""Checkout-related utility functions."""
from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
import graphene
from django.core.exceptions import ValidationError
from django.utils import timezone
from prices import Money
from ..account.models import User
from ..core.exceptions import ProductNotPublished
... |
class ReplayBuff:
def __init__(self):
self.reset()
def append(self, S, action, S_new, reward, done):
"""
Separated copies are needed to save, so that we use copy() command
"""
self.d['S'].append(S)
self.d['action'].append(action)
self.d['S_new'].appen... |
# Generated by Django 2.2.8 on 2020-02-20 14:51
import directory_validators.string
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('enrolment', '0010_auto_20191121_1142'),
]
operations = [
migrations.AddField(
model_name='pre... |
testinfra_hosts = ["ansible://all"]
def test_borg_package(host):
ans_dict = host.ansible.get_variables()
package = ans_dict.get('borgbackup_install_from_pkg', False)
if package is True:
borg = host.package("borgbackup")
assert borg.is_installed
else:
borg = host.file("/usr/loca... |
import collections
from enum import Enum
from functools import reduce
from operator import mul
from typing import Iterable, Tuple, TypeVar, Dict, NamedTuple, Optional, Union
import warnings
import logging
import numpy as np
import six
from scipy.linalg import block_diag
from scipy.optimize import OptimizeResult
from c... |
# -*- coding: utf-8 -*-
#
# animalvocalizationgenerativenet documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All con... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
from .action import RunJq
|
import unicodedata
import re
re_digit = re.compile(r'\d')
sample = '1\xbc\xb2\u0969\u136b\u216b\u2466\u2480\u3285'
for char in sample:
print('U+%04x' % ord(char), # <A>
char.center(6), # <B>
're_dig' if re_digit.match(char) else '-', # <C>
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0027_create_boot_scripts'),
]
operations = [
migrations.CreateModel(
name='ApplicationVersionBootScript'... |
# -*- coding: utf-8 -*-
import codecs
from setuptools import find_packages, setup
setup(
name="widgetastic.patternfly",
use_scm_version=True,
author="Milan Falesnik",
author_email="mfalesni@redhat.com",
description='Patternfly widget library for Widgetastic',
long_description=codecs.open('READ... |
"""
Climate on Zigbee Home Automation networks.
For more details on this platform, please refer to the documentation
at https://home-assistant.io/components/zha.climate/
"""
from __future__ import annotations
from datetime import datetime, timedelta
import enum
import functools
from random import randint
from homeas... |
import os
import re
from subprocess import CalledProcessError, check_output
from typing import Any, Dict, List, Text
import polib
import ujson
from django.conf import settings
from django.conf.locale import LANG_INFO
from django.core.management.commands import compilemessages
from django.utils.translation.trans_real ... |
# coding=utf-8
# Copyright The HuggingFace Inc. team. 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... |
'''
Copyright (c) 2017 Yogesh Khatri
This file is part of mac_apt (macOS Artifact Parsing Tool).
Usage or distribution of this software/code is subject to the
terms of the MIT License.
'''
import binascii
import codecs
import collections
import logging
import os
import sqlite3
import sys
import xlsx... |
from hallo.events import EventMessage
def test_fraction_simple(hallo_getter):
test_hallo = hallo_getter({"math"})
test_hallo.function_dispatcher.dispatch(
EventMessage(test_hallo.test_server, None, test_hallo.test_user, "fraction 6/4")
)
data = test_hallo.test_server.get_send_data(1, test_hall... |
import unittest
from mock import MagicMock, Mock, patch
import brew_view
@unittest.skip("TODO")
class AdminAPITest(unittest.TestCase):
# @classmethod
# def setUpClass(cls):
# brew_view.load_app(environment="test")
def setUp(self):
self.app = brew_view.app.test_client()
self.cl... |
from django.conf.urls import url
from . import views
app_name='comments'
urlpatterns=[url(r'^comment/post/(?P<post_pk>[0-9]+)/$', views.post_comment, name='post_comment')] |
from functools import update_wrapper
import numpy as np
import pytest
import aesara
import aesara.sparse
import aesara.tensor as at
from aesara.misc.may_share_memory import may_share_memory
from aesara.tensor import get_vector_length
from aesara.tensor.basic import MakeVector
from aesara.tensor.shape import Shape_i, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import re
from setuptools import setup, find_packages
PKG_NAME = 'bioframe'
README_PATH = 'README.md'
INSTALL_DEPS_PATH = 'requirements.txt'
CLASSIFIERS = [
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"Programmi... |
# -*- coding : utf-8 -*-
import datetime
from tornado.log import app_log
from models.posts import Post
from models.groups import Group
from handlers import BaseHandler
from decorators import authenticated
class GroupHandler(BaseHandler):
def get(self, tag):
group = Group.objects(tag=tag)[0]
post... |
from PIL import Image,ImageFilter
from multiprocessing import Process
import histogram as htg
import aHash as ah
import pHash as ph
import dHash as dh
import cv2
if __name__ == '__main__':
# read image files
img1 = Image.open('images/cow_back3.jpg').resize((224, 224),Image.ANTIALIAS).convert('L')
img2 = I... |
# encoding: utf-8
'''
These dictize functions generally take a domain object (such as Package) and
convert it to a dictionary, including related objects (e.g. for Package it
includes PackageTags, PackageExtras, PackageGroup etc).
The basic recipe is to call:
dictized = ckan.lib.dictization.table_dictize(domain_o... |
# This file is Copyright 2003, 2006, 2007, 2009, 2010 Dean Hall.
#
# This file is part of the Python-on-a-Chip program.
# Python-on-a-Chip is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.
#
# Python-on-a-Chip is distributed in the hope th... |
import discord
from discord.ext import commands
from .emojis import GREEN_TICK, RED_TICK
from .menus import BasicPages, ConfirmView, MenuPages, TablePages
from .utils import reply_to
class Context(commands.Context):
@property
def guild_prefix(self):
return self.bot.guild_prefix(self.guild)
@prop... |
# Link --> https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem
# Code:
def reverse(head):
currentNode = head
nodes = []
while currentNode:
nodes.insert(0, currentNode.data)
currentNode = currentNode.next
newHead = DoublyLinkedList()
for i in range(le... |
import logging
from types import BuiltinMethodType
import requests
from reddit_analyze.api import api
class Reddit(api.API):
"""The Reddit Class obtains data to perform sentiment analysis on
using the Reddit API.
It allows an unauthenticated user to obtain data to analyze various
reddit objects.
... |
from rx import Observable
source1 = Observable.interval(1000).map(lambda s: "Source 1: {0}".format(s))
source2 = Observable.interval(500).map(lambda s: "Source 2: {0}".format(s))
source3 = Observable.interval(2000).map(lambda s: "Source 3: {0}".format(s))
Observable.merge(source1, source2, source3) \
.subscribe(l... |
import cv2
image= cv2.imread('turbidity difference/2.jpg')
image =cv2.resize(image, (0,0), fx=0.2, fy=0.2)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
points=[]
for startx in range(281,286):
for starty in range(371,375):
points.append((startx,starty))
intensities=[]
for x,y in points:
... |
RAWDATA_DIR = '/staging/as/skchoudh/rna-seq-datasets/single/pan_troglodytes/SRP136499'
OUT_DIR = '/staging/as/skchoudh/rna-seq-output//pan_troglodytes/SRP136499'
CDNA_FA_GZ = '/home/cmb-panasas2/skchoudh/genomes/pan_troglodytes/cdna/Pan_troglodytes.Pan_tro_3.0.cdna.all.fa.gz'
CDNA_IDX = '/home/cmb-panasas2/skchoud... |
# -*- coding: utf-8 -*-
from elasticsearch import AsyncElasticsearch
from guillotina import app_settings
from guillotina import configure
from guillotina.catalog.catalog import DefaultSearchUtility
from guillotina.component import get_adapter
from guillotina.component import get_utility
from guillotina.event import not... |
#!/usr/bin/env python
import sys
import pmagpy.command_line_extractor as extractor
from pmagpy import convert_2_magic as convert
def main():
"""
NAME
sufar4-asc_magic.py
DESCRIPTION
converts ascii files generated by SUFAR ver.4.0 to MagIC formated
files for use with PmagPy plotting... |
from fastapi import FastAPI
from typing import Optional
from enum import Enum
from fastapi import FastAPI
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/i... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Tag
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class PublicTag... |
import numpy as np
import sys
#define a function that returns a value
def expo(x):
return np.exp(x) #return the np e^x function
#define a subroutine that does not return a value
def show_expo(n):
for i in range(n):
print(expo(float(i))) #call the expo funtion
#define a main function
def main():
n = 10 #provi... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while(1):
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_red = np.array([90,150,50])
upper_red = np.array([255,255,180])
mask = cv2.inRange(hsv, lower_red, upper_red)
res = cv2.bitwise_and(... |
from typing import Iterable
EMPTY = "L"
FLOOR = "."
OCCUPIED = "#"
DIRECTIONS = [(-1-1j), (-1+0j), (-1+1j), -1j, 1j, (1-1j), (1+0j), (1+1j)]
with open("inputs/day11.txt", 'r') as f:
input_grid = {x + y*1j: s for y, line in enumerate(f.read().splitlines()) for x, s in enumerate(line)}
def get_adjacent(coord:... |
from __future__ import print_function, division
import imgaug as ia
from imgaug import augmenters as iaa
def main():
img = ia.quokka(0.5)
mul = 0.01
augs = [
("iaa.ImpulseNoise(p=0*mul)", iaa.ImpulseNoise(p=0*mul)),
("iaa.ImpulseNoise(p=1*mul)", iaa.ImpulseNoise(p=1*mul)),
... |
#!/usr/bin/env python3
# Copyright (c) 2021 The Logos Foundation
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Test that we can broadcast transactions using the new Lotus sighash.
We build txs using different numbers of inpu... |
import graphene
from dagster_graphql.implementation.fetch_partition_sets import (
get_partition_by_name,
get_partition_config,
get_partition_set_partition_statuses,
get_partition_tags,
get_partitions,
)
from dagster_graphql.implementation.fetch_runs import get_runs
from dagster import check
from da... |
# the class to build the graph, as already described in main.py
class Graph:
def __init__(self):
self.nodes = set()
self.edges = set()
self.neighboors = {}
self.weight_edges = {}
self.coord_nodes = {}
def add_node(self, node):
self.nodes.add(nod... |
import os
from transly.seq2seq.config import SConfig
from transly.seq2seq.version1 import Seq2Seq
"""
word boundary example
"""
filepath = os.path.dirname(os.path.abspath(__file__))
def train(
model_path="./trained_model/",
model_file_name="model.h5",
training_data_path="./train.csv",
):
"""
tr... |
from .base_field import BaseField
from .identifier_field import IdentifierField
from .simple_field import SimpleField
from .connections.relationship_field import RelationshipField
from .connections.pagination_field import PaginationField
|
from os import path, listdir, walk
def split_ext(file_name):
index = file_name.rfind('.')
name = file_name[:index]
ext = file_name[index:]
return name, ext
def list_dirs(dir_path):
dirs = []
for item in listdir(dir_path):
if path.isdir(path.join(dir_path, item)):
dirs.app... |
# Copyright 2018 The TensorFlow Authors. 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 applica... |
# when dates.format is called without a format argument, what format to use?
# FIXME: this is actually wrong - should really use the timezone correctly
DEFAULT_DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
# date formats that we know about, and should try, in order, when parsing
DATE_FORMATS = [
"%Y-%m-%dT%H:%M:%SZ", # e.g... |
# Copyright 2015-2017 IONOS
#
# 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, s... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"Card": "00_card.ipynb",
"Deck": "00_card.ipynb"}
modules = ["card.py"]
doc_url = "https://plablo09.github.io/ejemplo_nbdev/"
git_url = "https://github.com/plablo09/ejemplo_nbdev/tree/main/"
def ... |
from django.db import models
import datetime
# Create your models here.
class User(models.Model):
uid = models.BigIntegerField(verbose_name='UID')
name = models.CharField(max_length=100,verbose_name='昵称')
gold = models.BigIntegerField(default=0,verbose_name='积分')
physical = models.BigIntegerField(defau... |
import os
import googlemaps
import datetime
def commute():
gmaps = googlemaps.Client(key=os.getenv('GOOGLE_API_KEY'))
today = datetime.datetime.today()
arrival_time = datetime.datetime.replace(today, hour=9, minute=00)
result = gmaps.distance_matrix(origins=os.getenv('HOME_POSTAL_ADDRESS'),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.