content stringlengths 5 1.05M |
|---|
''' This module contains a bunch of functions which facilitate specialized iteration patterns. '''
import itertools
import collections
__all__ = ['windowed', 'chunked', 'chop', 'generates', 'truncated', 'paired', 'united', 'flattened']
def windowed (iterable, size, step=1, trail=False) :
''' This function yield... |
import os
import sys
import keypirinha as kp
import keypirinha_util as kpu
from MovieDB import constants
from .settingsparser import SettingsParser
from .suggestions.errorsuggestion import ErrorSuggestion
from .suggestions.textsuggestion import TextSuggestion
from .userinputparser import UserInputParser
sys.path.app... |
import SimpleITK as sitk
import numpy
import OpenEXR
import json
import os
import warnings
from .utils import __TIFF_HEADERS_ID, __get_pixeltype_from_channel, __get_exrpixel_from_channel,\
__change_array_type
from .pixeltype import PixelType
def convert_directory(path, output_pixel_type=None, verbose=True):
"... |
# This file is Copyright (c) 2019 Arnaud Durand <arnaud.durand@unifr.ch>
# License: BSD
from litex.build.generic_platform import *
from litex.build.lattice import LatticePlatform
# IOs ----------------------------------------------------------------------------------------------
_io = [
("clk12", 0, Pins("A10"),... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 27 15:06:40 2017
@author: Diogo Leite
"""
# here the FK values was selected in lastas positions according to Species_new object class
from DAL import *
from configuration.configuration_data import *
class _Species_sql_new(object):
"""
This class manipulate the ... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import signal
from sppm import settings
from sppm.cmd_action import action_shutdown
from sppm.process_status_lock import ProcessStatusLock
from sppm.settings import hlog, SPPM_CONFIG
# noinspection PyUnusedLocal
def sigint_handler(sig, frame):
hlog.debug('收到 Ctrl+... |
import requests
import os
import logging
import uuid
from datetime import datetime, timedelta, time
from requests.exceptions import HTTPError
log = logging.getLogger(__name__)
class VcoClient:
"""
A class that provides a client for interacting with the Velocloud orchestrator_url
...
Attributes:
... |
import argparse
import cv2 as cv
import numpy as np
import scipy
import math
import time
import copy
import matplotlib
#%matplotlib inline
import pylab as plt
import json
from PIL import Image
from shutil import copyfile
# from skimage import img_as_float
from functools import reduce
from renderopenpose import *
from ... |
#!/usr/bin/env python3
import argparse
import glob
import os
import os.path as p
import subprocess
import sys
DIR_OF_THIS_SCRIPT = p.dirname( p.abspath( __file__ ) )
DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' )
# We don't include python-future (not to be confused with pythonfutures) because
# it ... |
from django.urls import path
from . import views
# URLconf - calls the view and maps it to a URL
urlpatterns = [
path('', views.index, name='index'),
]
|
"""
Fibonacci Sequence
- Enter a number and have the program generate the Fibonacci sequence
to that number or to the Nth number.
Call By
- python fib.py
"""
def fib():
length = int(raw_input('How many numbers of the fibonacci sequence would you like to see?: '))
numbers = []
while len(numbers) < lengt... |
#!/usr/bin/env python3
from __future__ import print_function
import re
import csv
import pickle
from os import environ
from datetime import date
from collections import defaultdict
from collections import namedtuple, defaultdict
from lxml import etree
from hyputils.hypothesis import HypothesisUtils, HypothesisAnnotatio... |
#!/usr/bin/python3
from rplidar import RPLidar
def rplidar_init():
try:
lidar = RPLidar('/dev/ttyUSB1')
except:
lidar = RPLidar('/dev/ttyUSB0')
lidar.start_motor()
info = lidar.get_info()
print(info)
health = lidar.get_health()
print(health)
return lidar
lidar = rplid... |
from collections import Counter
class Searcher:
"""Find movie by query."""
def __init__(self, subtitle_api, poster_api):
self.subtitle_api = subtitle_api
self.poster_api = poster_api
def search(self, query, limit=10):
"""Find movie by query.
:param query: query for movie... |
import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class DynamicNode(Node, ArmLogicTreeNode):
'''Dynamic node'''
bl_idname = 'LNDynamicNode'
bl_label = 'Dynamic'
bl_icon = 'CURVE_PATH'
def init(self, context):
self.outputs.ne... |
from zipfile import ZipFile
import tornado.ioloop
import tornado.web
import shutil
import os
class ZipHandler(tornado.web.RequestHandler):
def post(self):
id = self.get_argument("id"),
username = self.get_argument("user", strip=True),
servername = self.get_argument("server", strip=True),
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import json
class Net2(nn.Module):
def __init__(self,batch):
super(Net2, self).__init__()
self.cnv1 = nn.Conv2d(1, 16,3,padding=1)
self.cnv2 = nn.Conv... |
from sympy import I, Integer
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Bra, Ket, StateBase
def test_innerproduct():
k = Ket('k')
b = Bra('b')
ip = InnerProduct(b, k)
assert isinstance(ip, InnerPr... |
__version__ = '1.1.6-alpha'
|
# coding=utf-8
# Copyright 2018 The TF-Agents 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... |
from setuptools import setup
setup(
name='pretext',
version='0.1',
py_modules=['pretext'],
install_requires=[
'Click',
'lxml',
'PyYAML',
'appdirs',
# 'os',
],
entry_points='''
[console_scripts]
pretext=pretext:cli
''',
... |
# Nonlinear regression using variational inference for parameters.
# For simplicity we treat output noise variance as a fixed parameter.
# Adapted from
# https://brendanhasz.github.io/2019/07/23/bayesian-density-net.html
import superimport
from __future__ import absolute_import
from __future__ import division
from _... |
import pytest
from stock_indicators import indicators
class TestSlope:
def test_standard(self, quotes):
results = indicators.get_slope(quotes, 20)
assert 502 == len(results)
assert 483 == len(list(filter(lambda x: x.slope is not None, results)))
assert 483 == len(list(filte... |
from skbuild import setup
from packaging.version import LegacyVersion
from skbuild.exceptions import SKBuildError
from skbuild.cmaker import get_cmake_version
# Add CMake as a build requirement if cmake is not installed or is too low a version
setup_requires = []
try:
if LegacyVersion(get_cmake_version()) < Legacy... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import serializers
from irekua_database.models import AnnotationVote
from irekua_rest_api.serializers.base import IrekuaModelSerializer
from irekua_rest_api.serializers.base import IrekuaHyperlinkedModelSerializer
from irekua_rest_api... |
import random
def as_int(n):
"""
Convert the argument to a builtin integer.
The return value is guaranteed to be equal to the input. ValueError is
raised if the input has a non-integral value.
Examples
========
>>> from sympy.core.compatibility import as_int
>>> from sympy import sqrt
... |
#!/usr/bin/env python
#
# Copyright 2010 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 require... |
""" Module routines for pre-processing data for expansion policy training
"""
import argparse
import os
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelBinarizer, LabelEncoder
from scipy import sparse
from aizynthfinder.training.utils import (
Config,
split_and_save_data,
smi... |
import os
import pytest
here = os.path.abspath(os.path.dirname(__file__))
@pytest.fixture
def sample_cmip6():
return os.path.join(here, 'sample-catalogs/cmip6-netcdf.json')
@pytest.fixture
def sample_bad_input():
return os.path.join(here, 'sample-catalogs/bad.json')
|
from mypy_boto3_builder.service_name import ServiceNameCatalog
from mypy_boto3_builder.type_maps.method_argument_map import get_method_arguments_stub
class TestMethodArgumentMap:
def test_get_method_arguments_stub(self) -> None:
assert get_method_arguments_stub(
ServiceNameCatalog.ec2, "Instan... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def amis(path):
"""Car Speeding and Warning Signs
The `amis` data fram... |
"""Unit tests for reviewbot.tools.cargotool."""
from __future__ import unicode_literals
import json
import os
import tempfile
import kgb
import six
from reviewbot.tools.cargotool import CargoTool
from reviewbot.tools.testing import (BaseToolTestCase,
ToolTestCaseMetaclass,
... |
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier("C:/Users/user/Desktop/AI with Computer Vision/Computer-Vision/Github/Module 5 Face Recognition/chp 5_4_gathering_selfies/cascades/haarcascade.xml")
eye_cascade = cv2.CascadeClassifier("C:/Users/user/Desktop/AI with Computer Vision/Computer-Vision/Git... |
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import annotations
import asyncio
import logging
from mautrix impor... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\designer\SelectWord.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impor... |
import numpy as np
from typing import Union, Iterator
from sampling_utils.helper_functions import _remove_diagonal
def get_max_samples(population: Union[list, np.ndarray], dont_pick_closest: int) -> int:
# sort first
population = sorted(population)
# if there's nothing to choose
if len(population) =... |
from aws_xray_sdk.core import xray_recorder, patch_all
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware
from flask import Flask
import requests
app = Flask(__name__)
xray_recorder.configure(service='sample-flask-xray-app')
plugins = ('ECSPlugin', 'EC2Plugin')
xray_recorder.configure(plugins=plugins)
patc... |
import unittest
import os
from test.aiml_tests.client import TestClient
from programy.config import BrainFileConfiguration
class BasicTestClient(TestClient):
def __init__(self):
TestClient.__init__(self)
def load_configuration(self, arguments):
super(BasicTestClient, self).load_configuration(... |
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from django.contrib.auth.models import User
from django.views.generic i... |
import matplotlib
matplotlib.use('Agg')
from matplotlib import cm, colors
import matplotlib.pyplot as plt
import numpy as np
import scipy.sparse as sp
import argparse
import csv
import sys
from node_learning import *
from exponential_families import *
from utils import *
if __name__ == '__main__':
parser = argpars... |
"""Algorithms to determine the roots of polynomials"""
from sympy.polynomials.base import *
from sympy.polynomials import div_, groebner_
def cubic(f):
"""Computes the roots of a cubic polynomial.
Usage:
======
This function is called by the wrapper L{roots}, don't use it
directly. The in... |
"""
Copyright (c) 2018-2021 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... |
import os
import argparse
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import shutil
import numpy as np
import tensorflow as tf
from yolo.dataset_voc import Dataset
from yolo.yolov3 import Create_Yolov3, YOLOv3, decode, compute_loss, bbox_iou
from yolo.configs import *
from yolo.utils import read_class_names, n... |
# coding: utf-8
from __future__ import unicode_literals
from SpiderFactory import SpiderFactory
import Queue
import threading
class BaseConsumer(threading.Thread):
def __init__(self, q, cq, nq, name='BaseCon'):
super(BaseConsumer, self).__init__()
self.q = q
self.cq = cq
self.... |
import os
import sqlite3
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows, get_next_unused_name, open_sqlite_db_readonly
def get_browser_name(file_name):
if 'brave' in file_name.lower():
return 'Brave'
elif 'microsoft' in ... |
"""Test the module condensed nearest neighbour."""
from __future__ import print_function
import numpy as np
from numpy.testing import assert_array_equal, assert_equal, assert_raises_regex
from sklearn.neighbors import KNeighborsClassifier
from imblearn.under_sampling import CondensedNearestNeighbour
# Generate a gl... |
import json
from pathlib import Path
import sc2
from sc2.constants import *
class MyBot(sc2.BotAI):
with open(Path(__file__).parent / "../botinfo.json") as f:
NAME = json.load(f)["name"]
async def on_step(self, iteration):
await self.build_supply_if_needed()
await self.build_workers()... |
## creates function for the chromosome/region visual
from graphics import *
## finds the x-coordinate of the box that represents the region
def findX(start, l):
## length = length of total chromosome
length = l
perc = (int(start)*1000)/length
return 50+perc
## returns the length of the tota... |
# Importamos las librerias necesarias
import socket
# Establecemos el tipo de socket/conexion
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 5000 # Puerto de comunicacion
sock.bind(('localhost',port)) # IP y Puerto de conexion en una Tupla
print ("esperando conexiones en el puerto ", port)
# Vamos a e... |
"""文本预处理类"""
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.externals import joblib
import numpy as np
from collections import Counter
class Vocabulary(object):
def __init__(self, max_size... |
import json
import requests
class Post():
MINIMUM_LENGTH = 100
def __init__(self, text):
self.text = text
self.has_accepted_size = self.has_minumum_size((len(self.text)))
def has_minumum_size(self, text_length):
return text_length > self.MINIMUM_LENGTH
def publish_post(self)... |
from app import db, app
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from flask_login import UserMixin
from flask_user import roles_required, UserManager
from hashlib import md5
from app import login
class Departments(UserMixin, db.Model):
id = db.Column(... |
from re import compile
from json import dumps
from flask import request, jsonify
from functools import wraps
from models import Service
from shared import zmq_relay_socket
uuid = compile(r'^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$')
service = compile(r'^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{6}... |
import json
from typing import Dict
from google_play_scraper.constants.regex import Regex
from google_play_scraper.constants.request import Formats
from google_play_scraper.utils.request import post
from google_play_scraper.constants.element import ElementSpecs
def permissions(app_id: str, lang: str = "en", country:... |
from sanic import request, response
from frontegg.baseConfig.frontegg_proxy import FronteggProxy
import typing
from .secure_access import context_provider as fe_context_provider, authentication_middleware as fe_authentication_middleware
RequestT = typing.TypeVar('RequestT')
class Frontegg(FronteggProxy):
def __i... |
from pytest import mark
from testpackage.high import green
|
from django.db import models, migrations
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('libretto', '0001_initial'),
]
operations = [
migrations.... |
from ..enums.direction import Direction
class Coordinate:
"""
A class to represent a position on an X/Y screen
"""
def __init__(self, x_position: int, y_position: int):
"""
Create a new Coordinate
Args:
x_position: The int value representing the position on a x-ax... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceYuntaskDetailGetModel(object):
def __init__(self):
self._merchant_pid = None
self._task_template_id = None
@property
def merchant_pid(self):
return ... |
# -*- coding:utf-8 -*-
import os.path as op
_base = op.join(op.dirname(op.abspath(__file__)), '..', '..')
import sys
sys.path.append(_base)
import pandas as pd
from eio import eio
@eio()
def sample1(hidden_layer_sizes: tuple,
activation: str,
validation_fraction:float) -> dict:
dict_out = {
... |
from bot_python_sdk.device_status import DeviceStatus
class Configuration:
def __init__(self):
self.maker_id = ''
self.device_id = ''
self.device_status = DeviceStatus.NEW
self.public_key = ''
self.private_key = ''
self.initialized = False
def is_initialized(s... |
""" top-level recreate script
Copyright (c) 2021 M. Jonasse (martin.jonasse@mail.ch)
"""
import sys
from recreate.scripting import app
def run(input_path='default', output_path='default'):
""" replace file attibutes with original creation datetime
arguments:
input use input path only ... |
from torch.nn.utils import clip_grad_norm_
import torch.optim
import torch.nn as nn
import copy
import re
from .hook import Hook
from zerovl.utils import logger
from zerovl.core.optimizer import LR, LARS
from zerovl.core.hooks.log import LogMetrics
try:
from apex import amp
except ImportError:
pass
class ... |
from pf_conan import CMakeConanFile
import conans
class PitchforkConanFile(conans.ConanFile):
name = 'pf-conan'
version = '0.1.0'
exports = 'pf_conan/*'
# We have no settings
settings = None
# We have no options
options = None
def package_id(self):
self.info.header_only()
|
"""Classes used for tracking game state.
The game state is defined as all the data which is being used by the game
itself. This excludes things like the package listing, the logging class, and
various other bits defined in the rpg.app.Game class.
"""
from enum import IntEnum, unique
from rpg.data import actor, resour... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from flows.transform import Transform
class Flip(Transform):
def forward(self, x, context=None):
return x.flip(-1), 0
def inverse(self, x, context=None):
return x.flip(-1), 0
"""
copied & adapted from
https://github.com/y0ast/... |
import pymorphy2
import argparse
from isv_nlp_utils.constants import DEFAULT_UNITS
from isv_nlp_utils.flavorizacija import (
CS_FLAVOR, PL_FLAVOR, RU_FLAVOR, SR_FLAVOR,
rus_letter_change, pol_letter_change, cz_letter_change, srb_letter_change
)
import os
def flavorise(word, golden_pos_tag, isv_morph, flavor,... |
#importing libs
import pandas as pd
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
#open data set file as csv file
file_content = pd.read_csv ("breast-cancer.csv")
#concverting diagnoses to numbers to able to use in machine lear... |
import functools
import re
from dataclasses import dataclass
from typing import Optional, List, Dict, Set, Union, Tuple, Iterable
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models import PROTECT, CASCADE, QuerySet, Q
from django.urls import reverse
from lazy impor... |
# Brute force parameter optimization for TSM2
# by Cody Rivera
# you will need to modify your subprocess.check_output calls to use this script
# in other installations
import subprocess
import csv
from os import system
# True Raw Optimal Parameters - Not adjusted
optParamsSingle = {
(10240, 2) : (2, 44),
... |
import pyscipopt as scip
import geco.mips.loading.orlib as orlib
from geco.mips.facility_location.generic import capacitated_warehouse_location
def cap_numeric_reader(file):
"""
Reads cap(NUMBER) Capacitated Warehouse Location instance params mentioned in [1].
Parameters
----------
file: file-lik... |
# coding: utf-8
# Copyright 2017 challenger.ai
# 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... |
class Plugin(object):
def install_plugin(self, _app):
def hello():
print "Hello, World"
def goodbye():
print "Goodbye, World"
cmd_types = {
'ADB Actions': [
{'label': 'Print Hello World', 'command': hello},
],
'O... |
"""checks for Object Calisthenics rule 7: Small entities."""
from astroid import If
from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
from pylint.interfaces import IAstroidChecker
class SmallEntitiesChecker(BaseChecker):
"""checks for classes and modules to be smal... |
from django.conf.urls import patterns, url
from shop.views.product import (ProductListView, ProductDetailView)
urlpatterns = patterns('',
url(r'^$',
ProductListView.as_view(),
name='product_list'
),
url(r'^(?P<slug>[0-9A-Za-z-_.//]+)/$',
ProductDetailView.as_view(),
nam... |
"""
Use napari's tqdm wrapper to display the progress of long-running operations
in the viewer.
"""
import numpy as np
import napari
from time import sleep
from napari.qt import progress
from qtpy.QtWidgets import QPushButton, QVBoxLayout, QWidget
from skimage.filters import (
threshold_isodata,
threshold_l... |
# -*- coding: utf-8 -*-
"""The :mod:`pybel.parser` module contains utilities for parsing BEL documents and BEL statements."""
from .modifiers import *
from .parse_bel import BELParser
from .parse_control import ControlParser
from .parse_identifier import IdentifierParser
from .parse_metadata import MetadataParser
|
import time
from locust import HttpUser, between, task
class QuickstartUser(HttpUser):
wait_time = between(1, 2)
@task
def day_to_hour(self):
self.client.get("/dh/5")
@task
def day_to_minute(self):
self.client.get("/dm/2")
|
from django.apps import apps
from django.contrib.admin.filters import RelatedFieldListFilter
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import NoReverseMatch, reverse
from django.utils.html import format_html
from enumchoicefield.admin import EnumListFilter
from wagtail.con... |
from .campaigns import Campaigns
from .ad_groups import AdGroups
from .product_ads import ProductAds
from .bid_recommendations import BidRecommendations
from .keywords import Keywords
from .negative_keywords import NegativeKeywords
from .campaign_negative_keywords import CampaignNegativeKeywords
from .suggested_keyword... |
from pympler import tracker
def get_mem_stats():
memory_tracker = tracker.SummaryTracker()
summary = memory_tracker.create_summary()
stats = {}
for entry in summary:
ref, n, sz = entry
entry_type = ref.split(' ')[0]
stat = stats.get(entry_type, {})
stat['num'] = stat.... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from ampligraph.datasets import load_from_csv
from ampligraph.discovery import find_clusters
from ampligraph.evaluation import train_test_split_no_unseen
from ampligraph.utils import restore_model
from sklearn.cluster import KM... |
#!/usr/bin/env python
#
# Copyright (C) 2018 The GrayHats Cybersecurity Club
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED... |
import os
import numpy as np
import tensorflow as tf
class Statistics(object):
def __init__(self, sess, summary_writer, average_summary):
self.sess = sess
self.average_summary = average_summary
self.average_summary_count = 0
self.writer = summary_writer
with tf.variable_scope('summary'):
... |
import argparse
import binascii
from flask import Flask, request, render_template, jsonify
from werkzeug.exceptions import BadRequest
from config import SDMMAC_PARAM, ENC_FILE_DATA_PARAM, ENC_PICC_DATA_PARAM, SDM_FILE_READ_KEY, SDM_META_READ_KEY
from ntag424 import decrypt_sun_message, InvalidMessage
app = Flask(__n... |
# MIT License
#
# Copyright (c) 2020 Brockmann Consult GmbH
#
# 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, modi... |
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
"Authman ran faster than Harry because he is an athlete.",
"Authman and Harry ran faster and faster and faster.",
]
bow = CountVectorizer()
X = bow.fit_transform(corpus) # Sparse Matrix
print(bow.get_feature_names())
print(X.toarray(... |
"""This module is the implementation of the Regularized AE with L2 decoder parameter regularization
proposed in (https://arxiv.org/abs/1903.12436).
Available samplers
-------------------
.. autosummary::
~pythae.samplers.NormalSampler
~pythae.samplers.GaussianMixtureSampler
~pythae.samplers.MAFSampler
... |
from django.test import TestCase, RequestFactory
from .mixins import TwoUserMixin, ProposalGroupMixin, ViewMixin
from consensus_engine.views import EditGroupMembershipView
from consensus_engine.models import ProposalGroup, GroupMembership
from django.core.exceptions import PermissionDenied
class EditGroupMembershipVi... |
import numpy as np
import os
import tensorflow as tf
import time
import model.inference as inference
import utils.config as config_utils
import utils.gpu as gpu
import preprocessing
from utils.face_class import FaceClass
from model import loss_box, loss_class
from utils.model_type import ModelType
from preprocessing... |
#!/usr/bin/env python
import os
import re
import sys
import fnmatch
import shutil
import argparse
sys.path.insert(0, '../ext/mod-pbxproj/mod_pbxproj')
from subprocess import Popen, PIPE
from mod_pbxproj import XcodeProject
Log = None
dd = None
def main():
parser = argparse.ArgumentParser(description="Adjust S... |
import datetime
import os
from hardhat.recipes.base import GnuRecipe
from hardhat.environment import toolchain_env
def make_cross_prefix_dir(prefix_dir):
return os.path.join(prefix_dir, 'cross')
mpfr_version = '3.1.6'
mpfr_sha256 = 'cf4f4b2d80abb79e820e78c8077b6725' \
'bbbb4e8f41896783c899087be0e9... |
"""
Current report shared resources
"""
# pylint: disable=abstract-method,arguments-renamed
# stdlib
import asyncio as aio
from datetime import date
from typing import List, Optional, Tuple, Union
# module
from avwx.base import ManagedReport
from avwx.service import get_service
from avwx.static.core import NA_UNITS,... |
import pickle
with open("Train.pickle", "rb") as f:
Image_Array_Train, Sketch_Array_Train, Image_Name_Train, Sketch_Name_Train = pickle.load(f)
with open("Test.pickle", "rb") as f:
Image_Array_Test, Sketch_Array_Test, Image_Name_Test, Sketch_Name_Test = pickle.load(f)
with open('sketch_train.pickle',"rb") as f... |
import torch
import utils
import config
import numpy as np
import torch.optim as optim
import matplotlib.pyplot as plt
import os
from models import Generator, Critic, initialize_weights
import torchvision.transforms as transforms
import torchvision.utils as vutils
from PIL import Image
def load_models(ep... |
#You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.
#At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to t... |
import os
from invoke import task, Exit
from environment import base_dir, environment
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.%s' % environment)
manage_file = os.path.join('./', 'manage.py')
@task
def clean(context):
context.run('find {} -name "*.pyc" -exec rm {{}} \;'.format(base_dir))
@t... |
#!python
import pytest
from ..src.day_01 import sum_iterate, file_lines_to_array, first_duplicate
import os
script_directory = os.path.dirname(os.path.realpath(__file__))
data_file = os.path.join(script_directory, 'data', 'day_01_input.csv')
@pytest.mark.parametrize("dup_input, dup_exp", [
[[1, 3, 5, 3, 6, 8, 1... |
from .blobfile import (
copy,
exists,
glob,
isdir,
listdir,
makedirs,
remove,
rmdir,
stat,
walk,
basename,
dirname,
join,
cache_key,
get_url,
md5,
set_log_callback,
BlobFile,
)
__all__ = [
"copy",
"exists",
"glo... |
# Copyright (c) Facebook, Inc. and its affiliates.
import random
import os
import torch
import numpy as np
import higher
import mbirl
import matplotlib.pyplot as plt
from differentiable_robot_model import DifferentiableRobotModel
from mbirl.learnable_costs import LearnableWeightedCost, LearnableTimeDepWeightedCost, L... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.