content stringlengths 5 1.05M |
|---|
from PIL import Image
def paint1(r, c):
#paint pattern 1 (6x6). [r][c] is the reference point.
#top
board.putpixel((r+2, c+1), c1)
board.putpixel((r+3, c+1), c1)
#left
board.putpixel((r+1, c+2), c1)
board.putpixel((r+1, c+3), c1)
#right
board.putpixel((r+4, c+2), c1)
board.putpi... |
import os
import tensorflow as tf
from PIL import Image
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
# physical_devices = tf.config.experimental.list_physical_devices('GPU')
# assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
# tf.config.experimental.s... |
import xadmin
from .models import Like
class LikeAdmin(object):
list_display = ["sender", "receiver_content_type", "receiver_object_id", "timestamp", 'id']
xadmin.site.register(Like, LikeAdmin)
|
import re
from setuptools import setup, find_packages
with open("README.md", encoding="utf-8") as readme_file, open(
"CHANGELOG.md"
) as history_file:
readme = readme_file.read()
history = history_file.read()
with open("requirements-dev.txt") as dev_requirements_file:
dev_requirements = [
line... |
"""
autovacuum_cleanup
A maintenance workflow that runs `VACUUM ANALYZE` nightly on all materialized views in
the MOVE database, to mitigate service degradation and/or downtime due to autovacuum
operations.
This was put in place after [issue #482](https://github.com/CityofToronto/bdit_flashcrow/issues/482).
The defau... |
from django.contrib.auth.base_user import BaseUserManager
from django.db.models import Manager
from django.dispatch import Signal
from django.utils.translation import ugettext_lazy as _
import users.models
class SuperuserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
... |
from __future__ import print_function
import argparse
from datetime import datetime
import os
import sys
import html_dashboard
"""
MIT License
Copyright (c) 2017 Chapin Bryce, Preston Miller
Please share comments and questions at:
https://github.com/PythonForensics/PythonForensicsCookbook
or email pyforcookb... |
# Generated by Django 3.1.4 on 2021-05-07 16:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Store', '0017_auto_20210507_1951'),
]
operations = [
migrations.RenameField(
model_name='order',
old_name='date_ordered',
... |
"""
script to parse reports from cr_sfditep-2012.xslsx
parses CC and RH reports
after parsing them, they need to be concatenated to the ones from vcare to
train a tfidf model
"""
import pandas as pd
from clintk.text_parser.parser import ReportsParser
from clintk.utils.connection import get_engine, sql2df
import ar... |
# Generated by Django 4.0.2 on 2022-02-11 13:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reviews', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='review',
name='accuracy',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/1/2 14:23
# @Author : CaiQinYi
# @Site :
# @File : manage.py
# @Software: PyCharm
'''
#C:\Python36\Scripts\pipreqs.exe ./ --encoding=utf8 --force
'''
import sys
import os
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import to... |
# Copyright 2018 Capital One Services, 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... |
#!/usr/bin/python3
f = open('wontsee.txt', 'w')
f.write('wont see this string')
f.close()
f = open('willsee.log', 'w')
f.write('will see this string')
f.close()
|
#!/usr/bin/env Python
# -*- coding: utf-8 -*-
'''
=====================================================================================
Copyright (c) 2017 - 2018 Université de Lorraine & Luleå tekniska universitet
Author: Luca Di Stasio <luca.distasio@gmail.com>
<luca.distasio@ingpec.eu>
This ... |
import random, sys, time
DNA_STR=[('G','C'),('C','G'),('T','A'),('A','T')]
PAUSE=0.1
DNA_ROWS=[
' ##',
' #{}-{}#',
' #{}---{}#',
' #{}-----{}#',
' #{}------{}#',
' #{}------{}#',
' #{}-----{}#',
' #{}---{}#',
' #{}-{}#',
' ##',
' #{}-{}#',
... |
# CONVERSOR DE METRO PARA OUTROS TIPOS DE MEDIDAS
mt = float(input('Digite um valor (metro):'))
km = mt / 1000
hm = mt / 100
dam = mt / 10
dm = mt * 10
cm = mt * 100
mm = mt * 1000
print(f'\n {mt}M equivale a {km}km.\n {mt}M equivale a {hm}hm.\n {mt}M equivale a {dam}dam.\n {mt}M equivale a {dm}dm'
f'\n {mt}M eq... |
"""Generic command module."""
from abc import ABC
from abc import abstractmethod
from dataclasses import dataclass
from typing import List
from typing import Protocol
from typing import Tuple
from typing import Union
from buttplug.core import LinearSubcommand
from buttplug.core import RotateSubcommand
from buttplug.co... |
pkgname = "base-files"
pkgver = "0.1"
pkgrel = 0
build_style = "meta"
pkgdesc = "Chimera Linux base system files"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:meta"
url = "https://chimera-linux.org"
# no tests
options = ["!check", "bootstrap", "keepempty", "brokenlinks"]
def do_install(self):
# bas... |
from flask import Blueprint, render_template, Response, jsonify
from flask.ext.login import login_required
from . import app
from .celery import start_container as async_start_container
bp_container = Blueprint('container', __name__)
@bp_container.route('/')
def index():
return render_template("index.html")
@b... |
# coding=utf-8
"""Main module."""
import logging
import math
import mimetypes
from os import PathLike, getenv, path
from pathlib import Path
from typing import Dict, List, Optional, Union
import httpx
import trio
import typer
from alive_progress import alive_bar
from dotenv import load_dotenv
from format_byte import f... |
import pytest
from tests.functional.coercers.common import resolve_unwrapped_field
@pytest.mark.asyncio
@pytest.mark.ttftt_engine(
name="coercion",
resolvers={"Query.nonNullStringField": resolve_unwrapped_field},
)
@pytest.mark.parametrize(
"query,variables,expected",
[
(
"""query... |
"""Contains functions for preparation of data on Safe Passage routes"""
import geopandas as gpd
import pandas as pd
def read_routes_file(shapefile_path, school_year):
"""Reads shapefile of Safe Passage route
and adds the respective school year as a column
Parameters
----------
shapefile_path : st... |
from unittest.mock import Mock, patch, call
from moto import mock_sqs
import boto3
import unittest
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from sqs_msg_transfer import sqs_move_msg
source_queue_name = "source-queue"
destination_queue_name = "destination-queue"
region = "us-e... |
#!/usr/bin/env python
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for the SyzyAsan integration tests."""
import json
import os
import sys
import common
# Bring in the SyzyAsan test mod... |
"""Handle table and view objects"""
class ViewParsingErrorException(Exception):
"""Exception for a failed parsing of a BeamSQLView"""
class TableParsingErrorException(Exception):
"""Exception for a failed parsing of a BeamSQLTable"""
def create_ddl_from_beamsqltables(beamsqltable, logger):
"""
cre... |
import json
import operator
import string
from collections import defaultdict
from nltk.corpus import stopwords
from tokenization import preprocess
# remember to include the other import from the previous post
com = defaultdict(lambda: defaultdict(int))
lst_of_data = []
punctuation = list(string.punctuation) # !!... |
import numpy as np
data = np.loadtxt('input.txt')
answer = []
# part 1
for x in data:
y = data + x
if (y == 2020).any():
ans1 = int((2020 - x) * x)
break
answer.append('Part 1: '+str(ans1))
# part 2
for i in range(len(data)):
for j in range(i, len(data)):
z = data + data[i] + data... |
from HTMLParser import HTMLParser
import datetime
from ...base import BaseParser, datetime_to_string, string_to_datetime
from .image import Image
from .option import Option
from .variant import Variant
class Product(BaseParser):
@property
def title(self):
return self._dict.get('title')
@title.s... |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2022, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
from charms import layer
from charms.reactive import set_flag, clear_flag, when, when_not, hookenv
@when('charm.started')
def charm_ready():
layer.status.active('')
@when('minio.available')
def configure_minio(http):
http.configure(port=hookenv.config('port'), hostname=hookenv.application_name())
@when('l... |
#!/usr/bin/python
'''---------------------------------------
# Basic User Configuration
---------------------------------------'''
# KNN Parameters
N = 4194304
D = 2
Dist = 1 # 0 = Manhattan; 1 = Euclidean
K = 10
# FPGA Platform Specifications
FPGA_part_name = 'xcu200-fsgd2104-2-e' # xcu200-fsgd2104-2-e = U200;... |
# SPDX-FileCopyrightText: 2019 Kevin J. Walters for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_midi.polyphonic_key_pressure`
================================================================================
Polyphonic Key Pressure MIDI message.
* Author(s): Kevin J. Walters
Implementation No... |
"""
This demo script serves as a template for new user scripts. cFSAT is not
intended to be a full featured ground system so the ScriptRunner context
provides sending commands and receiving/waiting on telemetry values.
The script executes in the context of a ScriptRunner object which is a
CmdTlmProcess child class.
"... |
# Lint as: python3
# pylint: disable=g-bad-file-header
# Copyright 2020 DeepMind Technologies Limited. 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.a... |
# encoding: utf-8
"""
Utilities for getting information about IPython and the system it's running in.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
... |
# Copyright 2016 Open Source Robotics Foundation, 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... |
#If statements
if 1<2:
if 2<3:
print("True!")
if 1<2:
print('First Block')
if 20<3:
print("Second Block")
if 1 >2:
print("hello")
elif 3 == 3:
print("elif ran")
else:
print("last")
#loops
#for loops
seq = [1,2,3,4,5,6]
for jelly in seq:
# code here
print(jelly)
d = {"... |
import yaml
def load_config():
with open('config.yaml', 'r') as configfile:
config = yaml.load(configfile)
print("loaded config")
return config
|
from setuptools import setup
setup(name='pyflatten',
version='1.0.1',
description='A utility for flattening nested data structures.',
author='Eric J. Ma',
author_email='ericmajinglong@gmail.com',
url='https://github.com/ericmjl/pyflatten',
license='MIT',
packages=['pyflatten']... |
import csv
from glob import glob
from django.core.management.base import BaseCommand
from comparisontool.models import BAHRate
class Command(BaseCommand):
help = 'Load the specified CSV into the BAH database'
def add_arguments(self, parser):
parser.add_argument('path_spec')
def handle(self, *a... |
"""This module initializes the categories app."""
|
import synapse.common as s_common
import synapse.cortex as s_cortex
from synapse.tests.common import *
class DnsModelTest(SynTest):
def test_model_dns_a(self):
with self.getRamCore() as core:
t0 = core.formTufoByProp('inet:dns:a', 'WOOT.com/1.2.3.4')
self.eq(t0[1].get('inet:dns:a... |
"""this module contains all the robot related setup data.
Might consider exposed as arguments in the future.
"""
import os
import pytest
from compas.robots import RobotModel
import compas_fab
from compas_fab.robots import Robot as RobotClass
from compas_fab.robots import RobotSemantics
from pybullet_planning import P... |
import subprocess
from lambda_utils import clear_tmp
CHROMOSOME_ALIASES = {
'M': 'MT',
'x': 'X',
'y': 'Y',
}
CHROMOSOME_LENGTHS_MBP = {
'1': 248.956422,
'2': 242.193529,
'3': 198.295559,
'4': 190.214555,
'5': 181.538259,
'6': 170.805979,
'7': 159.345973,
'8': 145.138636,
... |
import coremltools
coreml_model = coremltools.converters.caffe.convert(
('models/EmotiW_VGG_S.caffemodel', 'models/deploy.prototxt'),
image_input_names='data',
class_labels='models/emotions.txt'
)
coreml_model.author = 'Gil Levi and Tal Hassner'
coreml_model.license = 'Unknown'
coreml_model.short_descripti... |
import numpy as np
from numpy import einsum, asarray, eye
from .MaterialBase import Material
from Kuru.Tensor import trace, Voigt
#####################################################################################################
# NEARLY INCOMPRESSIBLE NEOHOOKEAN
###############... |
# This is a placeholder version of this file; in an actual installation, it
# is generated from scratch by the installer. The constants defined here
# are exposed by constants.py
DEFAULT_DATABASE_HOST = None # XXX
DEFAULT_PROXYCACHE_HOST = None # XXX
MASTER_MANAGER_HOST = None # XXX - used to define BUNDLES_SRC... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import numpy as np
import nibabel as nb
from scipy.interpolate import interpn
from datetime import datetime as dt
from nipype import logging
LOGGER = logging... |
from .base import FeedbackScore
import pandas as pd
class RegressionReferenceScore(FeedbackScore):
def score(self, annotation):
item = annotation.item
references = item.annotations.filter(user=None)
if references:
ref_values = list(references.values_list("data", flat=True))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-02-16
Last_modify: 2016-02-16
******************************************
'''
'''
Given a string containing just the charact... |
import os
import string
import random
import getpass
def hunderd_folders(number_of_folders, length_of_folder_name):
'''Create 'n' number of folders inside python_FOLDER in your desktop'''
try:
path = 'C:\\Users\\{}\\Desktop\\python_Folder'.format(getpass.getuser())
if not os.path... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 13:13:34 2015
The Point module stores the X, Y, Z of a point and performs basic Point opeartions.
All Points are immutable so that they can be hashed and to prevent deep/shallow
copy problems.
sid
@author: lvanhulle
"""
import numpy
import constants as c
import matri... |
#!/usr/bin/python -O
# -*- coding: utf-8 -*-
# 2014 Stephan Boyer
from language import *
##############################################################################
# Unification
##############################################################################
# solve a single equation
def unify(term_a, term_b):
... |
from collections import namedtuple
#from common.data import CachedDataLoader, makedirs
import os.path
from common import io
import os
TaskCore = namedtuple('TaskCore', ['cached_data_loader', 'data_dir', 'target', 'pipeline',
'classifier', 'normalize', 'gen_preictal', 'cv_ratio','bi... |
from __future__ import annotations
import pytest
from tests.conftest import targets
pytestmark = pytest.mark.flaky
@pytest.mark.asyncio
@pytest.mark.xfail
@targets(
"redis_stack",
"redis_stack_raw",
"redis_stack_resp3",
"redis_stack_raw_resp3",
)
async def test_modules_list(client, _s):
module_... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# Copyright 2016-2017 Curtis Sand <curtissand@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 l... |
class person(object):
def __init__(self,name):
self.name=name
def disp(self):
print(self.name)
class student(person):
def __init__(self,name,rno):
super().__init__(name)
self.rno=rno
def disp1(self):
super().disp()
return self.rno
name=str(inpu... |
"""
Classifier that uses the Amazon Rekognition API
"""
import logging
from time import sleep
import boto3
from botocore.exceptions import ClientError
from newspaperclassifier.classifiers import ClassifierABC
FILE_LIMIT = 5242880 # AWS limits to 5MB images
THROUGHPUT_EXCEPTION = "ProvisionedThroughputExceededExcept... |
from __future__ import division # Use floating point for math calculations
import math
from datetime import datetime
from flask import Blueprint
from CTFd.models import (
db,
Solves,
Fails,
Flags,
Challenges,
ChallengeFiles,
Tags,
Hints,
)
from CTFd.plugins.flags import get_flag_class... |
from unittest.mock import Mock, patch
from gwaith.main import get_all_rates
@patch('gwaith.main.get_currency_feed_urls', return_value={'PLN': 'url'})
@patch('gwaith.main.get_rates')
def test_get_all_rates(get_rates, get_currency_feed_urls):
m_processor = Mock()
for _ in get_all_rates(processor=m_processor):
... |
from collections import OrderedDict
from unittest import mock
from .. import *
from bfg9000.path import Path
from bfg9000.safe_str import jbos, literal, shell_literal
from bfg9000.shell import posix
from bfg9000.shell.list import shell_list
class TestSplit(TestCase):
def test_single(self):
self.assertEq... |
#!/usr/bin/env python3
import argparse
from Bio import SeqIO
from Bio import pairwise2
from Bio.pairwise2 import format_alignment
import sys
parser = argparse.ArgumentParser()
parser.add_argument('fasta', type=argparse.FileType('r'))
parser.add_argument('--seed_length', type=int, default=23)
parser.add_argument('--sl... |
"""
Handle the function to draw graph to display on the corespond DES which take raw data from defaul source or selectFile then take the filter data from Model to display with suitable graph
"""
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Fi... |
from azul import symbol_fetcher_registry, BaseSymbolFetcher
@symbol_fetcher_registry.register('faang')
class FaangSymbolFetcher(BaseSymbolFetcher):
def __init__(self):
super().__init__()
def symbols(self):
return ['FB', 'AMZN', 'AAPL', 'NFLX', 'GOOG']
|
import pandas as pd
import pathlib
def load_data(file_name, prepare_func=None, **kwargs):
DATA_PATH = pathlib.Path(__file__).parent.joinpath('data').resolve()
data = pd.read_csv(DATA_PATH.joinpath(file_name), **kwargs)
if prepare_func:
data = prepare_func(data)
return data
def load_copy(fil... |
import requests
import json
ORG = 'glib-sample'
ID = '123456'
base_url = 'http://35.187.158.185:8080/upload'
url = '/'.join([base_url, ORG, ID])
files = {'intents': open('intents.txt.sample', 'rb'),
'entities': open('entities.txt.sample', 'rb'),
'synonyms': open('synonyms.txt.sample', 'rb')}
r = r... |
from typing import List
UvciList = List[str]
class UvciData:
def __init__(self, new: UvciList = [], removed: UvciList = []) -> None:
self._new: UvciList = new
self._removed: UvciList = removed
def add_uvcis(self, new: UvciList = [], removed: UvciList = []) -> None:
self._new += new
... |
from turtle import Turtle
UP = 90
START_X = 0
START_Y = -280
BORDER_BOUNDS = 280
MOVE_AMNT = 20
class Player(Turtle):
def __init__(self):
super().__init__()
self.shape("turtle")
self.pu()
self.color("cyan")
self.setheading(UP)
self.goto(START_X, START_Y)
def ... |
# Create a function
def function():
return "Function text"
# Lambda function that adds 1 to given integer and adds it to the variable number
number = lambda n: n + 1
|
from collections import OrderedDict
import numpy as np
import pandas as pd
from tests import generate_random_tickers, generate_random_dates, assert_output, project_test
@project_test
def test_get_high_lows_lookback(fn):
tickers = generate_random_tickers(3)
dates = generate_random_dates(4)
fn_inputs = {
... |
import cffi
#
# This is only a demo based on the GMP library.
# There is a rather more complete (but perhaps outdated) version available at:
# http://bazaar.launchpad.net/~tolot-solar-empire/+junk/gmpy_cffi/files
#
ffibuilder = cffi.FFI()
ffibuilder.cdef("""
typedef struct { ...; } MP_INT;
type... |
# Generated by Django 2.2.11 on 2020-03-24 17:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Project', '0015_project_comments_user'),
]
operations = [
migrations.AddField(
model_name='projects',
name='reports... |
# -*- coding: utf-8 -*-
""" Implements capturing from Pyro4 server.
"""
from EasyVision.base import lru_cache
from .base import *
import Pyro4
import socket
from EasyVision.server import Command
try:
import cPickle as pickle
except:
import pickle
class PyroCapture(VisionBase):
"""Class for capturing fr... |
# -*- coding: utf-8 -*-
from .base import VaspNudgedElasticBandTask
from .materials_virtual_lab_ci import MatVirtualLabClimbingImageNudgedElasticBand
from .mit import MITNudgedElasticBand
|
from rest_framework import routers
from .api import RoutineViewSet
router = routers.DefaultRouter()
router.register('api/routines', RoutineViewSet, 'routines')
urlpatterns = router.urls |
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: all
# notebook_metadata_filter: all,-language_info,-toc,-latex_envs
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# ... |
import alphastarmini.core
import alphastarmini.lib
#print("alphastarmini init")
|
def hdf_difference(file1, file2, column = False, column_number = 0, number_species = 0):
'''
Inputs: file1 = an hdf file of abundances
file2 = a second hdf file of abundances
column = option to analyze a specific column, defaults to False
column_number = requ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""FNN is metric depended for noisy data.
The FNN fraction is metric depended for noisy time series. In
particular, the second FNN test, which measures the "boundedness" of the
reconstructed attractor depends heavily on the metric used. E.g., if
the Chebyshev metric is ... |
import getpass
from optparse import make_option
from hashlib import sha1
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS
class Command(BaseCommand):
option_list = BaseCommand.option_list + (make_option(
... |
__author__ = 'Will.Smith'
# -----------------------------------------------------------------------------
# Name: DiscardReason.py
# Purpose: Model for Discard Reasons
#
# Author: Will Smith <will.smith@noaa.gov>
#
# Created: Jan 01, 2016
# License: MIT
# ----------------------------------------... |
from typing import Dict, Tuple
from unittest.mock import patch
import pytest
from bson.objectid import ObjectId
from crawler.constants import (
COLLECTION_PRIORITY_SAMPLES,
COLLECTION_SAMPLES,
DART_STATE_PENDING,
FIELD_COORDINATE,
FIELD_MONGODB_ID,
FIELD_MUST_SEQUENCE,
FIELD_PLATE_BARCODE,... |
from collections import Counter,defaultdict
from utils.super_heap import SuperHeap
from utils.neighborhoods import knn_and_rnn
from sklearn.metrics import accuracy_score
from utils.helper_functions import key_with_max_val
class kNN_LDP_Node:
def __init__(self, label_distribution, knn, index, rnn=None):
... |
#!/usr/bin/env python3
"""Peter Rasmussen, Programming Assignment 4, test_regression_perceptron.py
"""
# Standard library imports
import collections as c
from copy import deepcopy
import json
from pathlib import Path
import warnings
# Third party imports
import numpy as np
import pandas as pd
from numba import jit, n... |
import os
import numpy as np
import torch.distributed as dist
from torch.utils.data import DataLoader, SubsetRandomSampler
from torch.utils.data.distributed import DistributedSampler
from .transform import get_transform
from .dataset import ImageFolder
def get_loader(args, two_crop=False, prefix="train", return_coo... |
def by_spot(xs, spot):
return by_inj(xs, spot.token)
def by_inj(xs, inj):
return _by_pred(xs, lambda x: x.inj == inj)
def by_dep(xs, dep):
return _by_pred(xs, lambda x: x.dep == dep)
def _by_pred(xs, pred):
filtered = filter(pred, xs)
return filtered[0] if len(filtered) > 0 else None
|
from django.apps import AppConfig
class PamblogConfig(AppConfig):
name = 'pamblog'
|
"""Unit tests."""
from molecule import api
def test_driver_is_detected(DRIVER):
"""Asserts that molecule recognizes the driver."""
assert DRIVER in [str(d) for d in api.drivers()]
|
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input
from callbacks import resultshullplots
from app import app
resultshull = dbc.Container([
dbc.Col([
dbc.Row(dbc.Col(html.H4('Results'))),
db... |
from dataclasses import dataclass, field
from typing import Optional
__NAMESPACE__ = "http://www.opengis.net/wfs/2.0"
@dataclass
class TransactionSummaryType:
total_inserted: Optional[int] = field(
default=None,
metadata={
"name": "totalInserted",
"type": "Element",
... |
# Generated by Django 3.2 on 2021-11-11 06:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0007_alter_event_body'),
]
operations = [
migrations.AlterField(
model_name='event',
name='address',
... |
from django.forms import Form
from django.forms.fields import (
BooleanField, CharField, ChoiceField, MultipleChoiceField)
from django.forms.widgets import CheckboxSelectMultiple, RadioSelect
from labels.utils import labelset_has_plus_code
class ExportAnnotationsForm(Form):
optional_columns_choices = (
... |
# from http.client import OK
# from urllib import request, response
# import frappe
# import requests
# import json
# from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
# import os
# @frappe.whitelist(allow_guest=True)
# def webhook(*args,**kwargs):
# from dotenv import load_dotenv
# ... |
"""
# - scheduling rate tips
- Do "But the most commonly used method is when the validation loss does not improve for a few epochs." according to https://debuggercafe.com/using-learning-rate-scheduler-and-early-stopping-with-pytorch/
- for epochs it seems every epoch step is common: https://pytorch.org/docs/stable/opt... |
""" Contains the password recovery model """
from django.db import models
from django_extensions.db.models import TimeStampedModel
class PasswordRecovery(TimeStampedModel):
"""
Extends class TimeStampedModel.
This class add fields created and modified
"""
user = models.ForeignKey("User", null=True... |
# SPDX-License-Identifier: Apache-2.0
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: tflite
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class BucketizeOptions(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, off... |
from fastapi import Depends, status, Request, HTTPException
from fastapi import APIRouter
from fastapi.security import HTTPBasic
from sqlalchemy.orm import Session
from typing import List
import os
from dotenv import load_dotenv
load_dotenv()
from ..auth.authentication import authenticate_admin, authenticate_webuser
s... |
from phi.tf.flow import *
from phi.model import *
class RandomSmoke(FieldSequenceModel):
def __init__(self, size, steps=12):
FieldSequenceModel.__init__(self, "Random Smoke Simulation",
"PhiFlow demo showcasing complete smoke simulation within tensorflow",
... |
n = int(input("Number: "))
if n > 0:
print(f"{n} is positive!")
elif n < 0:
print(f"{n} is negative")
else:
print("is zero") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.