content stringlengths 5 1.05M |
|---|
import time
import numpy
from lib.training_data import TrainingDataGenerator, stack_images
class Trainer():
random_transform_args = {
'rotation_range': 10,
'zoom_range': 0.05,
'shift_range': 0.05,
'random_flip': 0.4,
}
def __init__(self, model, fn_A, fn_B, batch_size, *ar... |
#!/usr/bin/python3
import requests
import csv
import os
import datetime
import time
import classes.scrap as scrap
def filename(job, city):
# Create filename according to inputs and date
current_date = datetime.datetime.now()
current_date_format = current_date.strftime("%m-%d-%Y-%Hh%M")
current_date_fo... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
DDB_ID = 'id'
DDB_INVOCATION_ID = 'invocationId'
DDB_TABLE_NAME = 'DDB_TABLE_NAME' # This is as per LambdaToDynamoDB AWS construct so do not change value.
DDB_TTL = 'TTL'
DDB_FINISHED_EVENT_DETAILS = 'finished_event_... |
import os
from functools import reduce
from ehive.runnable.IGFBaseProcess import IGFBaseProcess
from igf_data.utils.fileutils import get_datestamp_label
class CollectExpAnalysisChunks(IGFBaseProcess):
def param_defaults(self):
params_dict=super(CollectExpAnalysisChunks,self).param_defaults()
params_dict.upda... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-07-08 12:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizations', '0013_remove_organizationcontact_organization'),
]
operations = [
... |
from x_rebirth_station_calculator.station_data.station_base import Module
from x_rebirth_station_calculator.station_data.station_base import Production
from x_rebirth_station_calculator.station_data.station_base import Consumption
from x_rebirth_station_calculator.station_data import wares
names = {'L044': 'Soy Beaner... |
from __future__ import print_function
import sys
import os
def __sys(cmd, fmt=None, echo=True):
"""Executes a string of OS commands and returns the a list of tuples (return code,command executed)"""
if not fmt:
fmt = {}
r = []
for cmd in [x for x in (cmd % fmt).split("\n") if len(x)]:
i... |
from ooi_harvester.settings.main import harvest_settings
__all__ = ["harvest_settings"]
|
# -*- coding: utf-8 -*-
"""The session command."""
import json
from .base import Base
from jira.api.jira_client import JiraClient
class Session(Base):
"""Manage sessions"""
def run(self):
#print('You supplied the following options:', json.dumps(self.options, indent=2, sort_keys=True))
self.j... |
from django.contrib import admin
from .models import User, Movie, Rating
# Register your models here.
admin.site.register(User)
admin.site.register(Movie)
admin.site.register(Rating)
|
import cv2
faceCascade = cv2.CascadeClassifier('FacialRecognition/haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
cap.set(3, 640) # set Width
cap.set(4, 480) # set Height
while True:
ret, img = cap.read()
img = cv2.flip(img, 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceC... |
from django.http import Http404
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import QuestionSerializer, ChoiceSerializer
from questions.models import Question, Choice
class CreateQuestion(generics.Creat... |
#!/usr/bin/python
from time import sleep
from mininet.net import Mininet
from mininet.node import Controller, OVSKernelAP
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import setLogLevel
def topology():
"Create a network."
net = Mininet(controller=Controller, link=TCLink, acces... |
from __future__ import annotations
import typing
import datetime
import numpy as np
from .core import PassType
from ..constants import R_EARTH
from ..time import julian_date
from .core import PassType
from ..constants import R_EARTH
if typing.TYPE_CHECKING:
from .observer import Observer
class VisualPoints(typ... |
import os
from datetime import datetime
from additional_info import logs, timestamp_format, sub_dir
from dir_structure_generator import dir_structure_generator
from dataset_downloader import dataset_downloader
from dataset_extractor import Data_Extractor
def main():
"""
This is the base function whill will cal... |
import json
from jsonpath_rw_ext import parse
import requests
import codecs
REGIONS_MAP = {
'US West (N. California)': 'us-west-1',
'Asia Pacific (Tokyo)': 'ap-northeast-1',
'Asia Pacific (Seoul)': 'ap-northeast-2',
'US West (Oregon)': 'us-west-2',
'South America (Sao Paulo)': 'sa-east-1',
'US ... |
#!/usr/bin/python
import sys
import re
file = sys.argv[1]
id_file = False
# other modes: all, strip_parens, strip_contents
mode = "none"
for line in open(file):
line = line[:-1]
first_paren = line.rfind("(")
trans = line[:first_paren]
id = line[first_paren+1:-1]
if len(trans) > 0:
... |
'''
Runs SPOT (greedy) / CART algorithm on Yahoo News dataset
Outputs algorithm decision costs for each test-set instance as pickle file
Also outputs optimal decision costs for each test-set instance as pickle file
Takes multiple input arguments:
(1) max_depth: training depth of tree, e.g. "5"
(2) min_weights_per_n... |
class Solution(object):
max = 0
count = 0
def maxAreaOfIsland(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
self.max=0
for r in xrange(len(grid)):
for c in xrange(len(grid[0])):
self.count = 0
self.exp... |
# TODO: Generlize it and move it the model folder
import numpy as np
import torch
import torch.nn as nn
from torch.optim import Adam
from tensorboardX import SummaryWriter
import collections
use_cuda = torch.cuda.is_available()
FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
LongTensor = torch.... |
import os
import sublime
import sublime_plugin
from .WebOS import WebosCommand
class WebosInstallCommand(sublime_plugin.WindowCommand, WebosCommand):
appinfo_data = None
def run(self):
appinfo_path = self.get_appinfo_path()
if not appinfo_path:
sublime.error_message('ERROR: "app... |
''' Random Relu Features. '''
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.utils import check_array, check_random_state
from sklearn.utils.validation import check_is_fitted
# Import the feature mapping base class
from MRCpy.phi import BasePhi
class RandomReLUPhi(BasePhi):
'''
... |
# -*- coding: utf-8 -*-
import requests
import json
import pandas as pd
from datetime import datetime, timedelta
def reindex(df, start_date, end_date, freq):
date = pd.date_range(start = datetime(*start_date), end = datetime(*end_date), freq = freq)
date = [pd.Timestamp(x) for x in date]
df = ... |
# coding=utf-8
import math
import os
from os import listdir
import PIL.Image as Image
import itchat
from numpy import *
itchat.auto_login(enableCmdQR=False)
friends = itchat.get_friends(update=True)[0:]
user = friends[0]["UserName"]
print(user)
os.mkdir(user)
num = 0
for i in friends:
img = itchat.get_head_... |
# coding=utf-8
"""Test fixtures."""
# Copyright (c) 2018 Stefan Braun
#
# 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, ... |
import sys
import archon.facade as facade
import archon.broker as broker
import archon.markets as markets
import archon.model.models as m
import archon.exchange.exchanges as exc
from archon.util import *
import time
import datetime
from util import *
#from order_utils import *
import math
import archon.exchange.e... |
from filecmp import cmp
from pathlib import Path
from shutil import rmtree
from unittest import TestCase
import boto3
from boto3 import resource
from data_loader_plugin.s3 import DataLoader
from moto import mock_s3
class TestExternalDataLoad(TestCase):
def setUp(self) -> None:
self.dir_name = "external_d... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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 applicab... |
'''
Time: 32 ms
Space: 13.7 MB python3
'''
class Solution:
def kthGrammar(self, N: int, K: int) -> int:
# time O(N) or O(logk) for traversing the tree of depth N
# space O(N) or O(logk) for the recursive call stack
if N == 1:
return 0
trans = {'0': '0... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyOpentuner(PythonPackage):
"""An extensible framework for program autotuning."""
hom... |
# Copyright 2014, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
import logging
# mapping from protocol to python class. The protocol matches the string
# used by vtctlclient as a -vtctl_client_protocol parameter.
vtctl_client_co... |
from django.apps import AppConfig
class StorageappConfig(AppConfig):
name = 'storageApp'
|
def fib(n):
"""
Write a recursive function to return the nth Fibonacci number.
The Fibonacci sequence is
0, 1, 1, 2, 3, 5, 8, 13, ....
"""
if n == 1:
return 0
if n == 2:
return 1
return fib(n - 1) + fib(n - 2)
def fib_iterative(n):
"""
Write an iterative functio... |
from __future__ import absolute_import
import six
import re
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from sentry.models import Project, ProjectStatus
from sentry.api.fields.empty_integer import EmptyIntegerField
from sentry.api.serializers.rest_framework import Lis... |
# Name : Pranav Bhandari
# Student ID: 1001551132
# Date : 11/04/2020
import sys, math, numpy as np
class Data:
def __init__(self, distance, classlabel):
self.distance = distance
self.classlabel = classlabel
def __lt__(self, other):
return self.distance < other.distanc... |
import re
file = open('./input', 'r')
lines = file.readlines()
lines = list(map(lambda line: line[:-1], lines))
def list_to_string(l):
s = ''
for c in l: s += c
return s
max_id = 0
for line in lines:
row_raw = line[:7]
col_raw = line[7:]
row_bin = list_to_string(list(map(lambda c: '0' if c == 'F' else '... |
from http import client
from pydoc import resolve
from django.test import TestCase,Client
from django.urls import reverse,resolve
from teproj.views import home,api
from teproj.models import TestModel
import json
class TestViews(TestCase):
def setUp(self):
self.client=Client()
def test_project_list_GET... |
from requests import get
import os
from uuid import uuid4
import logging
class File:
def __init__(self, url):
self.url = url
self.filename = url.split("/")[-1]
self.path = ""
def read(self):
if not self.path:
self.path = os.path.join(os.environ.get("TASKS_UPLOAD_FO... |
from Bio import SeqIO
import pandas as pd
import numpy as np
import math
import re
import os
def invert_new(pdDataFrame, No_genes, pd_column_index, gene_description):
pdDataFrame_dict = pdDataFrame.to_dict()
new_pdDataFrame_dict = {}
for i in No_genes.index:
new_pdDataFrame_dict[i] = list(pdDataFr... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
import errno
import os
import six
import sys
from vistir.compat import FileNotFoundError
if six.PY2:
class FileExistsError(OSError):
def __init__(self, *args, **kwargs):
self.errno = errno.EEXIST
super... |
import numpy as np
from state_evolution import next_state
def mock_odo_gps_data(state, ip):
odo = []
gps = []
perfect_world = []
for _ in range(50):
state = next_state(state, ip) # state update
perfect_world.append(state)
odo.append(state + np.random.normal([0,0,0], [0.1, 0.1, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import bisect
class Region(object):
__slots__ = ["a", "b"]
def __init__(self, a, b):
assert isinstance(a, int)
assert isinstance(b, int)
self.a = a
self.b = b
def __str__(self):
return "Region({}, {})".format(self.a, ... |
from sqlalchemy import Column
from sqlalchemy.types import JSON, Text, Boolean, TIMESTAMP, BigInteger
from sqlalchemy.dialects import postgresql as psql
from steampipe_alchemy.mixins import FormatMixins
from steampipe_alchemy import Base
class AwsWafv2RuleGroup(Base, FormatMixins):
__tablename__ = 'aws_wafv2_rule... |
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path, re_path
from rmp.views import (
index,
contact,
about,
databases,
rmp,
tri,
nrc,
rcris,
brs,
)
urlpatterns = [
path('admin/', admin.... |
import functools
import numbers
from typing import List, Union
import numpy as np
import open3d as o3d # type: ignore
from . import geom3d
def vec2vec_rotation(unit_vec_1, unit_vec_2):
angle = np.arccos(np.dot(unit_vec_1, unit_vec_2))
if angle < 1e-8:
return np.identity(3, dtype=np.float64)
if... |
import pandas as pd
from matplotlib.axes import Axes
from pyhdx.fileIO import csv_to_protein
from functions.base import settings_dict
from functions.formatting import *
from functions.logging import write_log
write_log(__file__)
output = 'save'
output_dir = current_dir / 'figures' / 'Fig_1'
output_dir.mkdir(parents... |
from unittest import TestCase
from oeem_uploader.request import Request
class TestRequest(TestCase):
@classmethod
def setUp(self):
self.request = Request()
def test_get_requests_of_projects(self):
r = self.request.get('projects')
self.assertEqual(r.status_code, 200)
|
#!/usr/bin/env python3
# Display-O-Tron 3000 specific libraries - Install instructions https://tinyurl.com/y653jp56
from dot3k import lcd
from dot3k import backlight
from dot3k import joystick as nav
# Python specific libraries
from gpiozero import CPUTemperature, PingServer
from time import sleep
import signal
impor... |
"""
evaluate OOD detection performance through AUROC score
Example:
python evaluate_cifar_ood.py --dataset FashionMNIST_OOD \
--ood MNIST_OOD,ConstantGray_OOD \
--resultdir results/fmnist_ood_vqvae/Z7K512/e300 \
--ckpt model_epoch_280.pkl \
--config Z7K512.yml \
... |
from .white_list import is_word_white_listed
|
import sys
def getTurn(board):
return bin(board).count("1") % 2 == 0
def printBoard(n):
sys.stdout.write("\n")
sys.stdout.write("\n | ")
t = 0
mask = 2
while mask <= 2**9:
t += 1
if n & mask == mask:
sys.stdout.write("x | ")
elif n & (mask << 9) == (mask <<... |
import connexion
import six
from fabric_cm.credmgr.swagger_server.models.request import Request # noqa: E501
from fabric_cm.credmgr.swagger_server.models.success import Success # noqa: E501
from fabric_cm.credmgr.swagger_server import util
from fabric_cm.credmgr.swagger_server.response import tokens_controller as rc... |
from guardian.shortcuts import get_objects_for_user
from django.http import Http404, HttpResponseRedirect
from django.db.models import Count
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from vdw.samples.models import Sample, Project, Batch, Cohort
from .forms impor... |
"""
Trading-Technical-Indicators (tti) python library
File name: _relative_strength_index.py
Implements the Relative Strength Index technical indicator.
"""
import pandas as pd
from ._technical_indicator import TechnicalIndicator
from ..utils.constants import TRADE_SIGNALS
from ..utils.exceptions import NotEnoug... |
import albumentations as A
import pytorch_lightning as pl
from albumentations.pytorch import ToTensorV2
from dretino.dataloader.utils import get_sampler, CustomDataset
from torch.utils.data import DataLoader
def create_dataloader(
df_train,
df_valid,
df_test,
train_path,
valid_path,
test_path,... |
"""
Miscellaneous utilities for wallscraper
"""
from fractions import Fraction
import sys
import pathlib
WALLPAPER_FOLDER = pathlib.Path(__file__).parent / 'wallpapers'
def get_aspect_ratio(width, height):
# Credit to https://en.wikipedia.org/wiki/Aspect_ratio_(image)
common = [
(4, 3), # (COMMON) ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
变量的过滤条件
"""
import json
import re
from collections import OrderedDict
from .util import utf8, text
from value_type import is_value_type_supported
class Filter(object):
def __init__(self, source, object, object_type, object_subtype, operation, value, type, para... |
#!python3
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(... |
# -*- coding: utf-8 -*-
"""Top-level package for stacklog."""
__author__ = 'Micah Smith'
__email__ = 'micahjsmith@gmail.com'
__version__ = '1.1.0'
import time
from collections import defaultdict
from functools import wraps
from ._time_formatters import format_time
from .compat import clearlist, getnargs
__all__ = ... |
"""Utilities for real-time data augmentation on image data.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras_preprocessing import image
random_rotation = image.random_rotation
random_shift = image.random_shift
random_shear = image.random_shear... |
import os, re, sys
from jinja2 import Environment, FileSystemLoader, select_autoescape
"""
Apply Default Values to Jinja Templates
This script applies default values to
mediawiki LocalSettings.php file.
The configuration templates are useful for Ansible,
but this is useful for experiments/one-offs.
All configurat... |
from matplotlib.ticker import MaxNLocator
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import seaborn as sns
sns.set()
mpl.use("Agg")
color_map = LinearSegmentedColormap.from_list(
'gr', ["g", "w", "r"], N=256) # Red and Green
... |
"""
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
>>> os.chdir(datadir)
"""
import os
from nipype.interfaces.base import (CommandLineI... |
import unittest
import numpy as np
from control.sisotool import sisotool
from control.tests.margin_test import assert_array_almost_equal
from control.rlocus import _RLClickDispatcher
from control.xferfcn import TransferFunction
import matplotlib.pyplot as plt
class TestSisotool(unittest.TestCase):
"""These are tes... |
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
from detectron2.utils.visualizer import ColorMode, Visualizer
from detectron2 import model_zoo
import cv2
import numpy as np
class Detector:
def __init__(self):
self.cfg = get_c... |
##############################################################################
#
# Copyright 2019 Leap Beyond Emerging Technologies B.V. (unless otherwise stated)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ... |
import argparse
import sys
import log
import json
import os
import time
import threading
import pyperclip
class ClipboardWatcher(threading.Thread):
def __init__(self, history):
super(ClipboardWatcher, self).__init__()
self._history = history
self._stopping = False
def run(self):
... |
import os, time, sys, subprocess, platform
from colored import fg, bg, attr
R = "\033[1;31m" # RED
B = "\033[1;34m" # BLUE
C = "\033[1;36m" # CYAN
G = "\033[1;32m" # GREEN
Y = "\033[1;93m" # YELLOW
N = "\033[0m" # NORMAL
B = "\033[1m" # BOLD
P = "\033[35m" # PURPLE
U = "\033[4m" # ... |
import time
from tqdm import tqdm
print("WELCOME TO HACKERS VS COMPUTER SECURITIES")
time.sleep(2)
print("A long war is fought for decades between hackers and computer securites. Now its upon you what you'll do i.e either hack or secure")
time.sleep(6)
playername = input("Enter your name:")
time.sleep(1.5)
choice = in... |
#!python3.6
#encoding:utf-8
import codecs
text = '日本語'
print('----- codecs.encode() -----')
for enc in ['utf-8', 'utf-16LE', 'utf-16BE', 'utf-32', 'shift-jis', 'euc-jp']:
print(text, enc, codecs.encode(text, encoding=enc, errors='strict'))
print('----- str.encode() -----')
for enc in ['utf-8', 'utf-16LE', 'utf-16BE... |
# --------------------------------------------------------
# Deep Iterative Matching Network
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Yi Li, Gu Wang
# --------------------------------------------------------
from __future__ import division, print_function
import os
import cv2
impor... |
'''grover search 5'''
import numpy
import qvantum
q0 = qvantum.Qubit(1, 0)
q1 = qvantum.Qubit(1, 0)
q2 = qvantum.Qubit(1, 0)
q3 = qvantum.Qubit(0, 1)
r = qvantum.Register([q0, q1, q2, q3])
print(r.show())
l0 = qvantum.Layer([qvantum.Hadamard(), qvantum.Hadamard(), qvantum.Hadamard(), qvantum.Hadamard()])
l1 = qvant... |
from math import ceil
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.metrics import pairwise_distances
from sklearn.preprocessing import StandardScaler
import networkx as nx
import community
from .utils import create_rng
def build_v_matrix(X, y):
... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def decisionTreeStruct(model):
n_nodes = model.tree_.node_count
children_left = model.tree_.children_left
children_right = model.tree_.children_right
feature = model.tree_.feature
threshold = model.tree_.threshold
nod... |
import pytest
from tests import _PATH_DATA
from src.data.make_dataset import *
"Testing the size of the dataset"
@pytest.mark.skipif(not os.path.exists(_PATH_DATA), reason="Data does not exist")
def test_data_length():
data= load_dataset('data/raw/reviews_Amazon_Instant_Video_5.json.gz')
assert len(data) == 3... |
#
# lambek.py
#
# Edward Loper
# Created [12/10/00 03:41 AM]
# $Id$
#
"""Lambek Calculus Theorem Prover
"""
# For while I'm coding..
#import term;reload(term)
#import typedterm; reload(typedterm)
_VERBOSE = 0
_VAR_NAMES = 1
_SHOW_VARMAP = not _VAR_NAMES
from term import *
from typedterm import *
from lexicon impor... |
import ulab
from ulab import poly
from ulab import vector
# polynom evaluation
x = ulab.linspace(0, 10, num=9)
p = [1, 2, 3]
y = poly.polyval(p, x)
print(y)
# linear fit
x = ulab.linspace(-5, 5, num=11)
y = x + vector.sin(x)
p = poly.polyfit(x, y, 1)
print(p)
# quadratic fit
x = ulab.linspace(-5, 5, num=11)
y = x*x ... |
import sims4.log
from interactions.payment.payment_cost import PaymentAmount, PaymentAmountUpTo, PaymentBaseDiningBill, PaymentBaseRetailValue, PaymentBills, PaymentBusinessAmount, PaymentCatalogValue, PaymentCurrentValue, PaymentDialog, PaymentFromLiability, PaymentUtility
from interactions.payment.payment_source impo... |
from dbt.runner import RunManager
from dbt.logger import GLOBAL_LOGGER as logger # noqa
class ArchiveTask:
def __init__(self, args, project):
self.args = args
self.project = project
def run(self):
runner = RunManager(
self.project,
self.project['target-path'],... |
from typing import List
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
"""
DFS approach
v = Vertices
e = Edges
d = Depth
Time complexity: O(v + e)
Space complexity: O(d)
"""
... |
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, rclass, rstr
from rpython.rtyper.lltypesystem.lloperation import llop
from rpython.rtyper.llinterp import LLInterpreter
from rpython.rtyper.annlowlevel import llhelper, cast_instance_to_base_ptr
from rpython.rlib.objectmodel import we_are_translated, speci... |
import numpy as np
import torch
class Hook():
def __init__(self, module, backward=False):
if backward==False:
self.hook = module[1].register_forward_hook(self.hook_fn)
self.name = module[0]
else:
self.hook = module[1].register_backward_hook(self.hook_fn)
self.name = module[0]
def hook_fn(self, module... |
#!/usr/bin/env python
"""
A dcmtk style echoscu application.
Used for verifying basic DICOM connectivity and as such has a focus on
providing useful debugging and logging information.
"""
import argparse
import logging
from logging.config import fileConfig
import os
import socket
import sys
import t... |
from django.conf import settings
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.utils import timezone
from apps.printers.models import Printer, PaperLogEntry
import urllib2
import json
from datetime import timedelta
sheets_per_box = 2500.00
class Command(B... |
import sys
import logging
import re
import os
import dill
import inspect
import itertools
from collections import OrderedDict
import numpy as np
from gensim.models.doc2vec import TaggedDocument
from gensim.models import Doc2Vec, Word2Vec
import fasttext
import keras
import keras.preprocessing
import keras.preproce... |
import os
import sys
from os.path import join
from distutils.util import strtobool
from django.core.exceptions import ImproperlyConfigured
import dj_database_url
from configurations import Configuration
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.integrations.redis import RedisIntegrat... |
#################################
## test_rklearn_perceptron.py ##
#################################
# Usage:
# (...) $ cd <top_dir>
# (...) $ python rklearn/tests/test_rklearn_perceptron.py --conf rklearn/tests/config/config.yaml
#############
## Imports ##
#############
import unittest
import os
import sys
impor... |
# This is a generated file, do not edit
from typing import List
import pydantic
from ..rmf_task_msgs.TaskProfile import TaskProfile
class DispatchRequest(pydantic.BaseModel):
fleet_name: str = "" # string
task_profile: TaskProfile = TaskProfile() # rmf_task_msgs/TaskProfile
method: pydantic.conint(ge... |
import urllib
from django.db import models
from django.contrib.auth.models import User
from managers import TokenManager, ConsumerManager, ResourceManager
from consts import KEY_SIZE, SECRET_SIZE, CONSUMER_KEY_SIZE
class Nonce(models.Model):
token_key = models.CharField(max_length=KEY_SIZE)
consumer_key = m... |
import io
import time
import logging
import platform
import itertools
import pkg_resources
from concurrent.futures import Future
import amqpframe
import amqpframe.methods
from amqpframe.frames import FRAME_MIN_SIZE
from fsmpy import FunctionalMachine
from . import fsm
from . import channel
from . import exceptions
f... |
class EskizException(Exception):
pass
class BadRequest(EskizException):
pass
class InvalidCredentials(EskizException):
pass
class TokenBlackListed(EskizException):
pass
class UpdateRetryCountExceeded(EskizException):
pass
|
import abc
import numpy as np
#
# This abstract base class that is the contract for creating Keras NN Models.
#
class Model(metaclass=abc.ABCMeta):
#
# Return a Keras model, There is no expectation about the NN architecture.
#
@abc.abstractmethod
def new_model(self):
pass
#
# ... |
import time
import datetime
def format_time(elapsed):
'''
Takes a time in seconds and returns a string hh:mm:ss
'''
# Round to the nearest second.
elapsed_rounded = int(round((elapsed)))
# Format as hh:mm:ss
return str(datetime.timedelta(seconds=elapsed_rounded))
|
# -*- coding: utf-8 -*-
"""
Created on Sun May 16 20:45:45 2021
@author: WEN
"""
import numpy as np
import collections
class LinearTransform:
def __init__(self, A, **kwargs):
self._pre = kwargs.get('pre', None)
self._post = kwargs.get('post', None)
A = np.array(A, copy=True)
if A... |
import datetime as dt
import threading
from difflib import SequenceMatcher
from beartype.typing import List, Optional, Union
from beartype import beartype
from flet.protocol import Command
from flet.ref import Ref
try:
from typing import Literal
except:
from typing_extensions import Literal
BorderStyles = ... |
# Copyright (c) 2021 Horizon Robotics and ALF Contributors. 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... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google 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... |
"""Jena/Fuseki data API client to manage data."""
from .base import FusekiBaseClient
from ..utils import build_http_file_obj
class FusekiDataClient(FusekiBaseClient):
"""Fuseki 'data' API client (data service)."""
def _build_uri(self, ds_name, *, service_name=None):
"""Build service URI.
:p... |
import web
import application.models.model_clientes as model_clientes #Importa el modelo personas
render = web.template.render('application/views/clientes/', base='../principal/master') #Configura la ubicacion de las vistas |
# -*- coding: utf-8 -*-
"""GPS module."""
import datetime
import gpsd
import logging
class GPS:
"""GPS reading module.
Attributes:
gpsd The gpsd daemon that is used to receive the GPS data
lastposition Last GPS position measured
lasttimeupdate Last time that the GPS ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.