content stringlengths 5 1.05M |
|---|
"""This class stores all of the samples for training. It is able to
construct randomly selected batches of phi's from the stored history.
"""
import numpy as np
import time
floatX = 'float32'
class DataSet(object):
"""A replay memory consisting of circular buffers for observed images,
actions, and rewards.
... |
from .client import ExClient
from .mock import MockTransport
from .models import ResponseMixin
from .transport import AsyncHTTPTransportMixin
|
import asyncio
import logging
import synapse.exc as s_exc
import synapse.telepath as s_telepath
import synapse.lib.base as s_base
import synapse.lib.stormtypes as s_stormtypes
logger = logging.getLogger(__name__)
stormcmds = (
{
'name': 'service.add',
'descr': 'Add a storm service to the cortex.... |
from datetime import date, datetime
import pytz
from Cinema.models.Actor import Discount
from Cinema.models.Actor import Actor
from Cinema.models.Movie import Movie
from Cinema.models.Projection import Projection, Entry
from Cinema.models.Hall import Seat
from django.db.models import Sum
from django.db.models impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
After 40755, what is the next triangle number
that is also pentagonal and hexagonal?
T285 = P165 = H143 = 40755.
"""
def pe45():
"""
>>> pe45()
(1533776805, 27549)
"""
limit = 30000
h = [n * ((n << 1) - 1) for n in range(144, limit)]
p = set... |
from kikola.core.context_processors import path
from kikola.core.decorators import render_to, render_to_json
@render_to_json
def context_processors_path(request):
return path(request)
@render_to('core/render_to.html')
def decorators_render_to(request):
return {'text': 'It works!'}
@render_to('core/render_... |
from .tasks import (
AsyncTasks,
Tasks,
CloudFunction,
as_completed,
GroupTerminalException,
BoundGlobalError,
)
# Backwards compatibility
from descarteslabs.common.tasks import FutureTask, TransientResultError
TransientResultException = TransientResultError
__all__ = [
"AsyncTasks",
... |
#!/usr/bin/env python
#
# utils.py
"""
Utility functions for Markdown -> HTML -> LaTeX conversion.
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (t... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Unit tests for nginxfmt module."""
import contextlib
import logging
import pathlib
import shutil
import tempfile
import unittest
import nginxfmt
__author__ = "Michał Słomkowski"
__license__ = "Apache 2.0"
class TestFormatter(unittest.TestCase):
fmt = nginxfmt.F... |
#!/usr/bin/python3
"""
Revision history:
24 Sep 2020 | 1.0 - initial release
"""
DOCUMENTATION = '''
---
module: hjson_to_json.py
author: Sanjeevi Kumar, Wipro Technologies
version_added: "1.0"
short_description: Read an .hjson file and output JSON
description:
- Read the HJON file specified and out... |
import django_userhistory.models as models
from django.contrib import admin
try:
admin.site.register(models.UserAction)
admin.site.register(models.UserHistory)
admin.site.register(models.UserTrackedContent)
except Exception, e:
pass |
"""
"""
load("@bazel_skylib//lib:shell.bzl", "shell")
def _stately_copy_impl(ctx):
input_files = ctx.files.srcs
if ctx.attr.state_file:
state_file = ctx.attr.state_file
else:
state_file = ".stately.yaml"
args = [
a
for a in ["copy"] + [f.short_path for f in input_files... |
from __future__ import unicode_literals
import logging
from django.utils.translation import ugettext as _
import django.views.decorators.cache
import django.views.decorators.csrf
import django.views.decorators.debug
import django.contrib.auth.decorators
import django.contrib.auth.views
import django.contrib.auth.forms... |
# -*- coding: utf-8 -*-
import unittest
import tempson
from .coloredPrint import *
vm = tempson.vm()
class vmTest(unittest.TestCase):
def test_execute_code (self):
result = vm.evalExpToStr('a + 3', { 'a': 1 }, True)
try:
self.assertEqual(result, '4', 'Evaluate error')
except A... |
#!/usr/bin/env python3
# Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import json
import os.path
import re
import sys
_COMPAT_KEY = '__compat'
_EXPERIME... |
from django.utils import timezone
def get_now():
"""
Separado para poder establecer el tiempo como sea necesario durante los tests
"""
return timezone.now()
def setallattr(obj, **kwargs):
for k in kwargs:
setattr(obj, k, kwargs.get(k))
def dict_except(obj, *args):
result = {}
f... |
"""
Link: https://www.hackerrank.com/challenges/py-if-else/problem?isFullScreen=true
Problem: Python If-ELse
"""
#Solution
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 != 0:
print("Weird")
else:
... |
import unittest
from pymal import account
from pymal.account_objects import account_animes
from pymal import anime
from pymal.account_objects import my_anime
from tests.constants_for_testing import ACCOUNT_TEST_USERNAME, ACCOUNT_TEST_PASSWORD, ANIME_ID
class AccountAnimeListTestCase(unittest.TestCase):
EXPECTED... |
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.views import APIView
from rest_framework import permissions
from views.retrieve_test_view import TEST_QUESTIONS, retrieve_test_data, is_test_public
class TestQuestionsSet(APIView):
def get(self, request):
return retrieve_tes... |
from flask import request
from flask_restplus import Namespace, Resource, fields
from api.utils import validator
from api.service.community_question import get_all_community_questions, create_community_question, get_all_question_comments
from .community_comment import community_comment_schema
import json
api = Names... |
import straws_screen
import gravity_screen
import diagon_screen
# 3440 x 1440
# WIDTH = 3440
# HEIGHT = 1440
# 2880 x 1800
WIDTH = 2880
HEIGHT = 1800
# 800 x 800
# WIDTH = 800
# HEIGHT = 800
#my_screen = straws_screen.StrawsScreen();
my_screen = gravity_screen.GravityScreen();
#my_screen = diagon_screen.DiagonScree... |
"""
File: hailstone.py
Name: Justin Kao
-----------------------
This program should implement a console program that simulates
the execution of the Hailstone sequence, defined by Douglas
Hofstadter. Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
def main():
"""
Use... |
# -*- coding: utf-8 -*-
"""
Base class for Topologies.
You can use this class to create your own topology. Note that every Topology
should implement a way to compute the (1) best particle, the (2) next
position, and the (3) next velocity given the Swarm's attributes at a given
timestep. Not implementing these methods... |
import numpy as np
import numpy.linalg as lin
MAX_ITERS = 20
EPSILON = 1.0e-7
def h(theta, X, y):
margins = y * X.dot(theta)
return 1 / (1 + np.exp(-margins))
def J(theta, X, y):
probs = h(theta, X, y)
mm = probs.size
return (-1 / mm) * np.sum(np.log(probs))
def gradJ(theta, X, y):
... |
#############################################################################
#
# Author: Ruth HUEY, Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2000
#
#############################################################################
#
# $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/autotors4Commands.py,v 1.... |
################################################################################
# siegkx1.py
#
# Post Processor for the Sieg KX1 machine
# It is just an ISO machine, but I don't want the tool definition lines
#
# Dan Heeks, 5th March 2009
import nc
import iso_modal
import math
###########################... |
#!/Users/duhuifeng/Code/RentHouseSite/renthouse/macvenv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from __future__ import absolute_import
from datetime import timedelta
from django.utils import timezone
from rest_framework.response import Response
from sentry.app import tsdb
from sentry.api.base import EnvironmentMixin
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.exceptions import ResourceD... |
# Generated by Django 2.2.1 on 2019-06-08 01:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Palace',
fields=[
... |
import re
from SingleLog.log import Logger
from . import i18n
from . import connect_core
from . import screens
from . import command
from . import _api_util
def has_new_mail(api) -> int:
cmd_list = list()
cmd_list.append(command.go_main_menu)
cmd_list.append(command.ctrl_z)
cmd_list.append('m')
... |
numerator = 32
denominator = 1
print numerator / denominator #dividing by zero, big no-no
#all code below this won't get executed
print "won't get executed"
|
from PIL import Image
import os
import glob
saveToPath = "C:\\Users\\phili\\Desktop\\"
filePath = input("File: ")
filePath = filePath[1:-1]
fileName = filePath.split("\\")[len(filePath.split("\\")) - 1]
image = Image.open(filePath)
size = image.size
print("Current image size of " + fileName + " is: " + str(size))... |
def log(msg, dry_run=False):
prefix = ''
if dry_run:
prefix = '[DRY RUN] '
print('{}{}'.format(prefix, msg))
|
#!/usr/bin/python3
"""
some code taken from huffman.py
"""
import sys
from functools import reduce
from operator import add
from math import log, log2
from random import shuffle, choice, randint, seed
from bruhat.argv import argv
EPSILON = 1e-8
def is_close(a, b):
return abs(a-b) < EPSILON
class Multiset... |
from graphene.types.generic import GenericScalar
from ..utils import dashed_to_camel
class CamelJSON(GenericScalar):
@classmethod
def serialize(cls, value):
return dashed_to_camel(value)
|
from django.conf.urls import url
from . import views
app_name = 'users'
urlpatterns = [
url(
regex=r'^~redirect/$',
view=views.UserRedirectView.as_view(),
name='redirect'
),
url(
regex=r'^$',
view=views.UserDetailView.as_view(),
name='detail'
),
url(... |
import torch
from PIL import Image
import torch.nn.functional as F
def load_image(filename, size=None, scale=None):
img = Image.open(filename).convert('RGB')
if size is not None:
img = img.resize((size, size), Image.ANTIALIAS)
elif scale is not None:
img = img.resize((int(img.size[0] / sca... |
class TrapException(RuntimeError):
pass
class Memory:
def __init__(self, comp):
self.storage = dict()
self.comp = comp
def __getitem__(self, key):
if not isinstance(key, int) or key < 0:
self.comp.trap("Invalid memory access key {}".format(key))
else:
... |
"""Dependency labeling Edge Probing task.
Task source paper: https://arxiv.org/pdf/1905.06316.pdf.
Task data prep directions: https://github.com/nyu-mll/jiant/blob/master/probing/data/README.md.
"""
from dataclasses import dataclass
from jiant.tasks.lib.templates.shared import labels_to_bimap
from jiant.tasks.lib.te... |
from pydigilent import *
import time
ad2 = AnalogDiscovery2()
v = 3.5
ad2.power.vplus.enable = 1
ad2.power.vplus.voltage = v
# after configuring power options, the master must be switched to enable
ad2.power.master.enable = 1
ad2.scope.channel1.vertical_division = 1.
while ad2.scope.channel1.voltage < v:
print... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import os
author = " * author:tlming16\n"
email = " * email:tlming16@fudan.edu.cn\n"
license = " * all wrong reserved\n"
text= "/* \n" + author + email+ license +"*/\n";
file_list =os.listdir("./test");
def write_file( f):
if not f.endswith(".cpp"):
return
conte... |
# 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... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.inferno
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Inferno os and all the related stuff.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, by... |
# Generated by Django 3.2.7 on 2021-11-23 16:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
... |
#!/user/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
from flask import render_template, request, redirect
from flask_login import current_user
from Web import right_url_prefix as url_prefix, create_blue
from Web import control
sys.path.append('..')
__author__ = 'Zhouheng'
html_dir = "/RIGHT"
develo... |
#!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 PanXu, Inc. All Rights Reserved
#
"""
flat pretrained vocabulary
Authors: PanXu
Date: 2021/02/24 10:36:00
"""
from easytext.data import PretrainedVocabulary, Vocabulary
class FlatPretrainedVocabulary(PretrainedVocabulary):
"""
Flat p... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import timedelta
import pytest
from indico.modules.events import Event
from indico.modules... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True, font_scale=1)
import itertools
# marker = itertools.cycle(("o", "^", "s"))
marker = itertools.cycle((None,))
markevery = 20
from tensorboard.backend.event_processing import event_accumulator
def plot_result_csv(folders... |
loglevel = 'info'
errorlog = "-"
accesslog = "-"
bind = '0.0.0.0:5000'
workers = 2
timeout = 60
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
# In[6]:
# In[16]:
# In[18]:
# In[21]:
from __future__ import division, print_function
# coding=utf-8
import streamlit as st
import h5py
from PIL import Image
import os
import numpy as np
import json
import predict3
from tensorflow.keras.models impor... |
#!/usr/bin/env python3
from mpl_toolkits.mplot3d import Axes3D
from rasterization import Rasterizer
from transformation import multiply
from transformation import TransformGenerator
import argparse
import DirectLinearTransform
import json
import math
import matplotlib
import matplotlib.image as mpimg
import matplotlib.... |
#!/usr/bin/env python3
import argparse
import gym
import gym-minigrid
from baselines import bench, logger
from baselines.common import set_global_seeds
from baselines.common.cmd_util import make_atari_env, atari_arg_parser
from baselines.a2c.a2c import learn
from baselines.ppo2.policies import MlpPolicy
from baselines... |
import os
import torch
from torch import tensor
from typing import Optional, Tuple
from dataclasses import dataclass
from schemes import EventDetectorOutput
from models import BaseComponent
from models.event_detection.src.models.SingleLabelSequenceClassification import SingleLabelSequenceClassification
from stores.onto... |
"""test2 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... |
import xarray as xr
import numpy as np
from xrspatial import hillshade
def _do_sparse_array(data_array):
import random
indx = list(zip(*np.where(data_array)))
pos = random.sample(range(data_array.size), data_array.size//2)
indx = np.asarray(indx)[pos]
r = indx[:, 0]
c = indx[:, 1]
data_ha... |
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Profile,Procedure
# Create your tests here.
class ProfileTestClass(TestCase):
def setUp(self):
self.new_user = User.objects.create_user(username='user',password='password')
self.new_profile = Profile(id... |
'''Create a segmentation by thresholding a predicted probability map'''
import os
import logging
from time import time as now
import numpy as np
import configargparse as argparse
import daisy
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# patch: suppre... |
import os
import time
import pandas as pd
import numpy as np
import xgboost as xgb
import lightgbm as lgb
import warnings
warnings.filterwarnings('ignore')
from sklearn.metrics import log_loss
from sklearn.model_selection import train_test_split, StratifiedKFold
def lgb_foldrun(X, y, params, name):
skf = Stratif... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Session'
db.create_table('django_session', (
('session_key', self.gf('django.db.... |
# ===============================================================================
# Copyright 2012 Jake Ross
#
# 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/licens... |
import unittest
from circleofgifts.dealer import Dealer
class DealerTestCase(unittest.TestCase):
def test_sorted_deal(self):
"""Test deal which uses sorted() as the sort method for both teams
and players. This makes the results predicable."""
players = [['Pierre', 'Paul'], ['Jeanne', 'Jul... |
from django.shortcuts import render
from django.http import HttpResponse
def explore(request):
return HttpResponse('This will list all chemicals.')
def my_chemicals(request):
return HttpResponse('This will list MY chemicals!')
|
import re
# Your puzzle input is 246540-787419.
## Part 1
pwords = []
for i in range(246540,787419):
if(int(str(i)[0]) <= int(str(i)[1]) <= int(str(i)[2]) <= int(str(i)[3]) <= int(str(i)[4]) <= int(str(i)[5])):
if((str(i)[0] == str(i)[1]) or (str(i)[1] == str(i)[2]) or (str(i)[2] == str(i)[3]) or (str(i)[... |
class Server(object):
def __init__(self, host, port):
self.host = host
self.port = port
def get_host(self):
return self.host
def get_port(self):
return self.port
class MailType(object):
def __init__(self):
pass |
from django import template
import base64
from socialDistribution.models.post import Post, InboxPost
from socialDistribution.utility import get_post_like_info, get_like_text
register = template.Library()
# Django Software Foundation, "Custom Template tags and Filters", 2021-10-10
# https://docs.djangoproject.com/en/3... |
"""
Setup of core python codebase
Author: Jeff Mahler
"""
import os
from setuptools import setup
requirements = [
"numpy",
"scipy",
"scikit-image",
"scikit-learn",
"ruamel.yaml",
"matplotlib",
"multiprocess",
"setproctitle",
"opencv-python",
"Pillow",
"joblib",
"colorlog... |
from collections.abc import Iterable
from itertools import chain, product
import pprint
import inspect
from .nodes import *
from .graph import *
class GraphGenerator():
def __init__(self, specifications):
"""
Parameters
----------
specifications: Iterable[Specification] -- TODO
... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Allocated Blocks Report
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# --------------------------------------------------------... |
from buildbot.config import BuilderConfig
from buildbot.changes.gitpoller import GitPoller
from buildbot.plugins import util, schedulers
from buildbot.process.factory import BuildFactory
from buildbot.process.properties import Interpolate
from buildbot.process import results
from buildbot.steps.source.git import Git
fr... |
import numpy as np
# from crf import Sample, CRF
from crf_bin import Sample, CRFBin
trainCorpus = "/home/laboratory/github/homeWork/machineTranslation/data/train.txt"
testCorpus = "/home/laboratory/github/homeWork/machineTranslation/data/test.txt"
labelTableverse = {}
print("cache label...")
with open("/home/laborat... |
# architecture.py ---
#
# Filename: architecture.py
# Description: defines the architecture of the 3DSmoothNet
# Author: Zan Gojcic, Caifa Zhou
#
# Project: 3DSmoothNet https://github.com/zgojcic/3DSmoothNet
# Created: 04.04.2019
# Version: 1.0
# Copyright (C)
# IGP @ ETHZ
# Code:
# Import python dependencies
import... |
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
""" Extension of User model """
user = models.OneToOneField(User,
on_delete=models.CASCADE,
primary_key=True)
# if vacation mode is set ... |
# -*- coding: utf-8 -*-
"""DigitRecognizer.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/149_-4guTkO2Vzex8bjA402nPcJ_Z7G7W
#***Digit Recognizer(MNIST) dataset using CNN***
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as... |
# See LICENSE file for full copyright and licensing details.
#from . import models
|
import numpy as np
import utils
# class Piece:
# def __init__(self,color = 0, pos=(-1,-1)):
# self.color = color
# self.pos = pos
class Player:
def __init__(self, collected_flag=np.zeros(9), collected_shape_dict={}, collected_num=0):
self.collected_flag = np.zeros((9,2)) # 收集过... |
"""Integration with nest devices."""
import json
import logging
import sys
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
from appengine import account, device, rest
@device.register('nest_thermostat')
class NestThermostat(device.Device):
"""Class represents a Nest thermostat."""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
def run_tests(**options):
import django
import sys
from django.conf import settings
from ginger.conf.settings import template_settings
defaults = dict(
MIDDLEWARE_CLASSES=(
'django.contrib.sessions.middleware.... |
from __future__ import print_function
import os
from os.path import dirname, join, abspath, isdir
import sys
import json
import requests
try:
from urlparse import urljoin
except:
from urllib.parse import urljoin # python 3.x
# http://python-redmine.readthedocs.org/
from redmine import Redmine
if __name... |
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
vertices = (
# ( x, y, z)
( 1, -1, -1), # A
( 1, 1, -1), # B
(-1, 1, -1), # C
(-1, -1, -1), # D
( 1, -1, 1), # E
( 1, 1, 1), # F
(-1, -1, 1), # G
(-1, 1, 1) # ... |
#!/usr/bin/env python
import argparse
import math
from collections import Counter
from spawningtool.parser import parse_replay
def map_replays(filenames, map_fn, results, update_fn, cache_dir=None, **kwargs):
for filename in filenames:
filename = filename.rstrip('\n')
replay = parse_replay(filena... |
import numpy as np
class Exploration_Noise:
def reset(self):
"""
Reset the noise generator.
"""
pass
def process_action(self, a):
"""
Add noise to the given action.
Args:
a: the action to be processed
Return:
the proces... |
from scrapy.http import Request
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
class HackernewsSpider(BaseSpider):
name = 'hackernews'
allowed_domains = []
start_urls = ['http://news.ycombinator.com']
def parse(self, response):
if 'news.ycombinator.com' in response.url:
... |
import sys
sys.path.insert(0, '/home/vagrant/Integration-Testing-Framework/sikuli/examples')
from sikuli import *
from test_helper import TestHelper
from flex_regions import *
from Regionplus import *
# Setup
helper = TestHelper("drag_column")
set_flex_helper(helper)
# Opening
#############
helper.Click("Lexicon.png... |
# Copyright 2018 Datawire. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: yandex/cloud/logging/v1/log_ingestion_service.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflect... |
"""
Tests of simple 2-layer PCBs
"""
from . import plotting_test_utils
import os
import mmap
import re
import logging
def expect_file_at(filename):
assert(os.path.isfile(filename))
def get_gerber_filename(board_name, layer_slug, ext='.gbr'):
return board_name + '-' + layer_slug + ext
def find_gerber_ap... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-01-09 07:00
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sass', '0003_auto_20190109_0659'),
]
operation... |
"""
Fetch ads.txt files from URLs
"""
from datetime import datetime
import logging
import os
import pandas as pd
import requests
logger = logging.getLogger(__name__)
HEADERS = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"Accept... |
##
# Copyright 2021 IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
##
import torch
from ...._utils import val_clamp
from ..node import _NodeActivation
from ....constants import Direction
from ...parameters.neuron import _NeuronParameters
"""
Dynamic activation function
"""
class _NeuronAct... |
from PIL import Image
import pytesseract
def extractWords():
img1 = Image.open("Solution\images\img1.jpg")
img2 = Image.open("Solution\images\img2.jpg")
engText = pytesseract.image_to_string(img1, lang='eng')
araText = pytesseract.image_to_string(img2, lang='ara')
print(engText)
print(araText)
... |
import lab12
def createSomePlanets():
aPlanet=lab12.Planet("Zorks",2000,30000,100000,5,['Steve','Lou','The Grinch'])
bPlanet=lab12.Planet("Zapps",1000,20000,200000,17,[])
print(aPlanet.getName() + " has a radius of " + str(aPlanet.getRadius()))
planetList=[aPlanet,bPlanet]
for planet in planetList:... |
from .__init__ import *
def home(request):
return Http_Response("", "这是视频API", "")
def url(request):
# 获取视频URL
query = request_query(request, "id", ["res", {"resolution": 1080}])
query["ids"] = '["{}"]'.format(query.pop("id"))
data = send(query).POST("weapi/cloudvideo/playurl")
return Http_R... |
#
# PySNMP MIB module BNET-ATM-TOPOLOGY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BNET-ATM-TOPOLOGY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:40:07 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
# -*- coding: utf-8 -*-
"""
Created on Mar 11, 2012
@author: moloch
Copyright 2012 Root the Box
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/licen... |
# License: BSD 3 clause
from datetime import datetime
from typing import Dict, Iterable
from os.path import join
from pyspark.sql import DataFrame
from pyspark.sql.functions import col, datediff, floor, lit, months_between
from scalpel.core.io import get_logger, read_data_frame
from scalpel.core import io
from scalp... |
"""Bagging classifier trained on balanced bootstrap samples."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Christos Aridas
# License: MIT
import numbers
import numpy as np
from sklearn.base import clone
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassi... |
# import theano.sandbox.cuda
# theano.sandbox.cuda.use('gpu0')
import numpy as np
import cPickle as cP
import theano as TH
import theano.tensor as T
import scipy.misc as sm
import nnet.lasagnenetsCFCNN as LN
import lasagne as L
import datetime
def unpickle(file):
import cPickle
fo = open(file, 'rb')
d... |
import tequila as tq
class QMBackend():
"""
A class that holds information about a backend and can be given as a parameter to an algorithm.
Attributes
----------
backend : str
The name of the used backend (simulator).
"""
def __init__(self, backend: str = None):
"""
Creates a QMBackend o... |
#!/usr/bin/env python3.7
"""
The copyrights of this software are owned by Duke University.
Please refer to the LICENSE and README.md files for licensing instructions.
The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent
"""
import os
import sys
sys.path.append(os.pat... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.smv
~~~~~~~~~~~~~~~~~~~
Lexers for the SMV languages.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, words
from pygments.token import Comment, Generic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.