content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.http import request
from odoo.osv import expression
from odoo.addons.account.controllers.portal import PortalAccount
class PortalAccount(PortalAccount):
def _invoice_get_page_view_values(self, invoice, ... |
from unittest.case import SkipTest
from batchy.runloop import coro_return, runloop_coroutine, use_gevent_local, use_threading_local
from batchy.batch_coroutine import batch_coroutine, class_batch_coroutine
try:
import gevent
from gevent.coros import Semaphore
import batchy.gevent as batchy_gevent
except ... |
import aiy.audio
import aiy.cloudspeech
import aiy.voicehat
from google_speech import Speech
from phue import Bridge
def main():
hue_bridge = Bridge('192.168.1.134')
hue_bridge.connect()
hue_bridge.get_api()
lights = hue_bridge.lights
light_names = hue_bridge.get_light_objects('name')
Speech('Jos... |
from train import *
def test():
X_A_full = T.tensor4('A')
X_B_full = T.tensor4('B')
X_A = pre_process(X_A_full)
X_B = pre_process(X_B_full)
X_A_ = nn.placeholder((bs, 3, image_size*4, image_size*4), name='A_plhd')
X_B_ = nn.placeholder((bs, 3, image_size*4, image_size*4), name='B_plhd')
... |
import network
import torch
import SimpleITK as sitk
import torch.optim as optim
from torch.utils import data
import numpy as np
import skimage.io as io
import os
from skimage.transform import resize
import time
from sklearn.model_selection import train_test_split
class VoxelMorph():
"""
VoxelMorph Class is a ... |
#!/usr/bin/env python
import os
import subprocess
help2md_exec='/root/help2md/help2md'
output_dir='/root/command_reference/'
def check_help2md():
if not os.path.exists(help2md_exec):
print 'Must have help2md installed.'
exit(1)
def check_anchore():
if os.system('anchore --version') != 0:
... |
import formencode
import inspect
from blazeutils.datastructures import LazyOrderedDict
from blazeform.element import form_elements, CancelElement, CheckboxElement, \
MultiSelectElement, LogicalGroupElement
from blazeform.exceptions import ElementInvalid, ProgrammingError
from blazeform.file_upload_translators impo... |
import re
import requests
from bs4 import BeautifulSoup as bs
from jfr_playoff.logger import PlayoffLogger
class RemoteUrl:
url_cache = {}
@classmethod
def fetch_raw(cls, url):
PlayoffLogger.get('remote').info(
'fetching content for: %s', url)
if url not in cls.url_cache:
... |
from tapis_cli.display import Verbosity
from tapis_cli.clients.services.mixins import FilesURI
from . import API_NAME, SERVICE_VERSION
from .models import PostIt, HTTP_METHODS, DEFAULT_LIFETIME, DEFAULT_MAX_USES
from .formatters import PostItsFormatOne
__all__ = ['PostItsCreate']
class PostItsCreate(PostItsFormatOn... |
for m in range(4):
for y in range(3):
print(f'({m},{y})')
|
for i in range(1,100):
if(i %2 !=0):
print"odd:",i
|
import sys, os, argparse
import json, urllib2
try:
argn = int(os.environ['ARGN'])
except KeyError:
sys.exit("No proof given")
if argn != 1:
sys.exit("No proof given")
try:
proof = os.environ['ARG0']
proof_url = "https://www.reddit.com/r/ethereumproofs/comments/" + proof + ".json"
request = url... |
"""Test module for the Markdown paragraphs."""
import re
import sys
import unittest
from books import Books
class TestParagraphs(unittest.TestCase):
"""Unit test of the Markdown lists."""
def setUp(self):
"""Setup: get all the paragraphs."""
self.paragraphs = []
books = Books()
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailimages.blocks
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0019_verbose_names_cle... |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField,SelectField
from wtforms.validators import Required,Email
class PostForm(FlaskForm):
'''
Class to create a wtf form for creating a post
'''
content = TextAreaField('YOUR POST')
submit = SubmitField('SUBMIT')
... |
import matplotlib
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
from astropy.io import fits
from matplotlib.colors import LinearSegmentedColormap as LSC
from matplotlib.patches import Ellipse
from matplotlib.ticker import MultipleLocator
# ran bettermoments with
# bettermoments 12CO.fit... |
import unittest
from double_preceding import double_preceding
class TestDoublePreceding(unittest.TestCase):
"""Tests for double_preceding."""
def test_double_preceding_none(self):
"""Test nothing."""
expected = []
L = []
double_preceding(L)
self.assertEqual(expected, ... |
import sys
import math
import json
class Vertex:
def __init__(self, x, y, neighbors = None, visited = None):
self.x = x
self.y = y
self.neighbors = neighbors if neighbors is not None else []
self.visited = visited if visited is not None else False
def addNeighbor(self, v):
self.neighbors.append(v)
for arg... |
"""
vclock
~~~~~~
Functions for manipulating vector clocks.
:copyright: (C) 2016 by Eeo Jun
:license: MIT, see LICENSE for details.
"""
import sys
import itertools
from functools import cmp_to_key
if sys.version_info[0] == 2:
zip = itertools.izip
map = itertools.imap
def from_size(n):
... |
#! /usr/bin/env python
import sys
import rospy
import os
#from mdp_plan_exec.prism_client import PrismClient
#from mdp_plan_exec.mdp import TopMapMdp, ProductMdp
from mdp_plan_exec.mdp import ProductMdp
from mdp_plan_exec.prism_mdp_manager import PrismMdpManager
from strands_executive_msgs.srv import AddMdpModel, G... |
#! /usr/bin/env python
"""
Several helper functions related to working with patches on drupal.org"""
import subprocess
import os
import sys
def download_patch(url):
"""Download a patch file from Drupal.org. Returns the patch filename."""
patch_filename = os.path.basename(url)
p = subprocess.Popen(
... |
import logging
import zmq
from threading import Thread, Event, Condition
from psdaq.control.ControlDef import ControlDef, front_pub_port, front_rep_port, create_msg
import time
class TimedRun:
def __init__(self, control, *, daqState, args):
self.control = control
self.name = 'mydaq'
self.co... |
import shutil
from sys import exit
import vigo.config as config
from vigo import git
from vigo.common import git_is_available
def init():
print("Initialize the vigo configuration")
config.vigo_dir.mkdir(parents=True)
print("Cloning openstack/governance")
if not git.clone(config.governance_url, str(co... |
import requests
from django.db import models
from django.contrib.postgres.fields import JSONField
from django.conf import settings
from django.urls import reverse
class Movie(models.Model):
title = models.CharField(max_length=255)
data = JSONField(null=True)
movie_added_on_datetime = models.DateTimeField... |
from flask_sqlalchemy import get_debug_queries, SQLAlchemy, Pagination
from flask import Flask
from flask_bcrypt import Bcrypt
import os
app = Flask(__name__)
app.config.from_object("config.BaseConfig")
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
from views import *
def sql_debug(response):
queries = list(ge... |
from bottle import route, run, template
@route('/')
def index():
return ('<h1>Hello</h1>')
@route('/hello/<name>')
def index(name):
return template('<b>Hello {{name}}</b>!', name=name)
#run(host='localhost', port=8080, debug = True)
run(host='0.0.0.0', port=8080, debug = True, reloader = True)
|
# Copyright 2017 AT&T Intellectual Property. All other 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... |
from django.apps import AppConfig
class DogbreedConfig(AppConfig):
name = 'dogbreed'
|
KEYWORDS = {
"print": "keyword",
}
OPERATORS = {
"+": "PLUS",
"-": "MINUS",
"*": "MUL",
"/": "DIV",
}
TYPES = {
"string" : "STRING",
"int" : "INT",
"float" : "FLOAT",
}
DIGITS = "0123456789"
EMPTY = [" ", "\t"]
SYMBOLS = {
"(": "left-bracket",
")": "right-bracket",
",": "comma"
}
|
#considere um laço que conte de 1 a 10,
# mas apresente apenas os números ímpares desse intervalo
# a instrução continue diz a Python para ignorar o restante do laço e voltar ao início
numero_atual = 0
while numero_atual < 10:
numero_atual += 1
if numero_atual % 2 == 0:
continue
print(numero_atua... |
from pytz import utc
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
jobstores = {
'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors... |
#!/bin/env python
# -*- coding: utf-8 -*-
#
# Created on 13.11.20
#
# Created for py_bacy
#
# @author: Tobias Sebastian Finn, [email protected]
#
# Copyright (C) {2020} {Tobias Sebastian Finn}
#
# System modules
import logging
import os
# External modules
import matplotlib as mpl
mpl.use('agg')... |
# coding=utf-8
def shift_command():
# return 225
return 0
def command_command():
# return 227
return 0
def control_command():
# return 224
return 0
def alt_command():
# return 226
return 0
def escape_command():
return 41
def function_command():
return 0
def singlequ... |
"""
Games __init__.
"""
try:
from spikey.games.gym_wrapper import gym_wrapper
from spikey.games.CartPole import CartPole
from spikey.games.Logic import Logic
except ImportError as e:
raise ImportError(f"games/__init__.py failed: {e}")
|
import click
import pprint
import os
import configparser
from .core import NetDefine
if os.path.exists('netdefine.cfg'):
config = configparser.ConfigParser()
config.read('netdefine.cfg')
root = config['DEFAULT']['root']
netdefine = NetDefine(root=root)
else:
# if no config file exists, assume the c... |
import sys
import socket
import os
import struct
import random
def readuntil( s, u ):
z = ''
while z.endswith( u ) == False:
z += s.recv(1)
return z
def readline( s ):
return readuntil( s, '\n')
def eatprompt(s):
return readuntil( s, '>>> ')
def main( argv ):
if len(argv) == 3:
... |
from typing import List
from py_client.aidm.aidm_base_classes import _HasID, _HasCode, _HasDebugString
from py_client.aidm.aidm_train_path_node_classes import AlgorithmTrainPathNode
class AlgorithmNodeTrack(_HasID, _HasCode, _HasDebugString):
def __init__(self, id: int, code: str, debug_string: str):
... |
# password validation using a regular expression.
import re
def password_validation():
i = 0
while i == 0:
try:
pattern = re.compile(r"[a-zA-Z\d!@#$%^&*]{8,}")
first_password = input("\nEnter a new password \nValid characters are A-Z, a-z, 0-9, $%*!@&#^ : ")
second... |
import CalculoCripto
print("************************")
print("Opções de Calculos Crito")
print("************************")
print("DIGITE:")
print("(1) para calcular o PREÇO baseado em SUPLY e MARKETCAP")
print("(2) para calcular o MARKETCAP baseado em PREÇO e SUPLY")
calculo = int(input("Digite o calulo Pretendido:"))... |
import tensorflow as tf
import numpy as np
from core.PPO.models import pi_model, v_model, pi_gaussian_model
from core.PPO.policy_base import PolicyBase
import tensorflow.keras.losses as kls
from utils.logger import log
class Policy_PPO_Continuous(PolicyBase):
def __init__(self,
policy_params=dic... |
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from blog.models.users import Details
class Nav(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=20, unique=True)
link = models.SlugField(max_... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='S.EX.', version='2.0', description='S.EX.', author='huku',
author_email='[email protected]', url='https://github.com/huku-/sex',
scripts=['bin/sex'], packages=['sex'])
|
import operator
import inspect
try:
from collections.abc import Mapping, Iterable
except ImportError:
from collections import Mapping, Iterable
import enum
import six
from .exceptions import format_trace
from .reporting import Absent, fmt, NATIVE_TYPES, callable_name
def is_regex(obj):
"""Cannot do typ... |
from .base_renderer import *
import os
import re
import docutils.writers.html4css1
from docutils.core import publish_parts
from docutils.writers.html4css1 import Writer, HTMLTranslator
docutils_dir = os.path.dirname(docutils.writers.html4css1.__file__)
class GitHubHTMLTranslator(HTMLTranslator):
def visit_litera... |
from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ('username', 'email', 'first_name', 'last_name','last_login')
serach_fields = ('username', 'email')
list_filter=('is_superuser',)
ordering = ('username',)
filter_horizontal = ("groups... |
from datetime import datetime
from flask import Flask, request, render_template, send_from_directory, url_for, redirect, session, Response, jsonify
from flask_login import current_user, login_required, LoginManager, login_user, logout_user
from flask_wtf import FlaskForm
from flask_wtf.csrf import CSRFProtect, CSRFErro... |
"""
Passed a filename that contains lines output by [TSPRegistry sharedRegistry] in lldb/Xcode:
182 -> 0x10f536100 KN.CommandSlideResetMasterBackgroundObjectsArchive
181 -> 0x10f5362e0 KN.ActionGhostSelectionTransformerArchive
...
...this script will print a sorted JSON object definition of that mapping from ... |
"""
Simple spider to demonstrate how to use the XLSX exporter.
This spider produces the following output:
+-----+----+-----+
| foo | 42 | bar |
+-----+----+-----+
"""
from scrapy import Spider
from scrapy_xlsx import XlsxItemExporter
from ..items import ExampleItem
class CustomExporter(XlsxItemExporter):
def _... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'c:\Users\Kula\Petrobras\OpenPulse\data\user_input\ui\Model\Info\getGroupInformationPerforatedPlate.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. ... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import moto
import pytest
from pipeline_control.entrypoints import lambda_entry_points
class TestNotifyUserHandler:
def test_1_notify_users(
self,
entrypoint_fake_notify_user_handler,
):... |
"""IBM Middleware product installation. Supports for Installation manager, Packaging utility and other products.
"""
import logging
import sys
import os
import stat
from lib import *
import diomreader
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message... |
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Callable, Iterable, List, Mapping, NamedTuple, Optional, Tuple, Union
import ciso8601
from typing_extensions import TypeAlias, TypedDict
from aioinfluxdb import constants
from aioinfluxdb.flux_t... |
from unittest import TestCase
from webassets.filter import register_filter
from webassets.test import TempEnvironmentHelper
from webassets_webpack import Webpack
register_filter(Webpack)
class WebpackFilterTestCase(TempEnvironmentHelper, TestCase):
default_files = {
'main.js': """var odds = evens.map(v... |
# Copyright 2021 The WAX-ML 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
from enum import Enum
class ColorSpace(Enum):
BGR = 1
RGB = 2
HSV = 3 |
import streamlit as st
from WebScraping.raiffeisen import get_raiffaisen_balance
from WebScraping.flatex import get_flatex_balance
from WebScraping.bitpanda import get_bitpanda_balance
from WebScraping.bank99 import get_bank99_balance
from WebScraping.dvag import get_dvag_balance
from mystreamlitapp import render_web_d... |
import sys
import re
import string
import os
import numpy as np
import codecs
from collections import defaultdict
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import KFold
from typing import Sequence
import time
# From scikit learn that got words from:
# http://ir.dcs.gla.ac.uk/resources/li... |
from setuptools import setup
execfile('respite/version.py')
setup(
name = 'django-respite',
version = __version__,
description = "Respite conforms Django to Representational State Transfer (REST)",
long_description = open('README.rst').read(),
author = "Johannes Gorset",
author_email = "jgorse... |
"""
Copyright (c) 2020 COTOBA DESIGN, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distri... |
from enum import Enum
from typing import Any, List
import h5py
import numpy as np
H5File = h5py.File
Group = h5py.Group
Dataset = h5py.Dataset
Array = np.ndarray
class InputChannel(Enum):
time = 'time'
perp = 'perp'
par = 'par'
ref = 'ref'
class DeltaAChannel(Enum):
time = 'time'
perp = '... |
module_id = 'gl'
report_name = 'tb_bf_maj'
table_name = 'gl_totals'
report_type = 'bf_cf'
groups = []
groups.append([
'code', # dim
['code_maj', []], # grp_name, filter
])
include_zeros = True
# allow_select_loc_fun = True
expand_subledg = True
columns = [
['op_date', 'op_date', 'Op date', 'DTE', 8... |
#!/usr/bin/env python
from distutils.core import setup
setup(name="Systori", packages=["systori"])
|
# Copyright MelisaDev 2022 - Present
# Full MIT License can be found in `LICENSE.txt` at the project root.
from __future__ import annotations
from typing import Type, TypeVar, Any
def remove_none(obj):
if isinstance(obj, list):
return [i for i in obj if i is not None]
elif isinstance(obj, tuple):
... |
# To build out the data you'll need to jump into the Django shell
#
# $ python manage.py shell
#
# and run the build script with
#
# $ from data.v2.build import build_all
# $ build_all()
#
# Each time the build script is run it will iterate over each table in the database,
# wipe it and rewrite each row... |
# coding: utf-8
sfx_names = [
'DexFanfare5079',
'Item',
'CaughtMon',
'PokeballsPlacedOnTable',
'Potion',
'FullHeal',
'Menu',
'ReadText',
'ReadText2',
'DexFanfare2049',
'DexFanfare80109',
'Poison',
'GotSafariBalls',
'BootPc',
'ShutDownPc',
'ChoosePcOption',
'EscapeRope',
'PushButton',
'SecondPartOfIt... |
import os
import numpy as np
import argparse
from ensemble_utils import *
from CNN import *
import argparse
import keras
import pickle
from tensorflow.python.client import device_lib
import os
import tensorflow as tf
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "4"
gpus = tf.co... |
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % self.empCount)
def displayEmployee(self):
... |
import pytest
from tests.common import data_file
from inputs import format_kml
@pytest.fixture
def kml_file():
return data_file("kml/kml-with-extended-data.kml")
def test_open(kml_file):
data_source = format_kml.open(kml_file)
assert data_source
def test_get_nonspatial_field_names(kml_file):
data_... |
import os, slackclient
import glob
# delay in seconds before checking for new events
SocketDelay= 1
# slackbot environment variables
SlackToken = ''
Slack = slackclient.SlackClient(SlackToken)
try:
f = open("images_uploaded.txt", "rt")
ax = f.readlines()
for line in ax:
print (line.... |
import requests
from django.conf import settings
from django.shortcuts import render
from django.http import HttpResponse
def error404(request):
if '/play/' in request.path:
return render(request, 'play_404.html', {'play_404': True}, status=404)
else:
return render(request, '404.html', statu... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
from ...ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules
from ...utils import common_utils, loss_utils
from .roi_head_template import RoIHeadTemplate
from .target_assigner.center_target_layer_mtasks import C... |
import torch
import torch.nn.functional as F
from modules import nn_utils, losses, pretrained_models, baseline_utils
from nnlib.nnlib import utils
from methods import BaseClassifier
class StandardClassifier(BaseClassifier):
""" Standard classifier trained with cross-entropy loss.
Has an option to work on pre... |
import time
import requests
from hookee.conf import Config
from hookee import HookeeManager
from tests.testcase import HookeeTestCase
__author__ = "Alex Laird"
__copyright__ = "Copyright 2020, Alex Laird"
__version__ = "1.2.0"
class TestHookeeManagerEdges(HookeeTestCase):
def test_not_click_logging(self):
... |
#!/ufs/cluster/yao/bin/python
import re, os
import string
import sys
import array
import random
import shutil
from os import walk
def genTrace(input_filename):
print "Parsing " + input_filename
# output filename
output_filename = input_filename.split('.')[0] + "_total_misses.trc"
# open input file
... |
# -*- coding: utf-8 -*-
#
# Copyright © 2021–2022 martin f. krafft <[email protected]>
# Released under the MIT Licence
#
GAME_NAMES_BY_DRAW_SIZE = {
6: {
"401": ("Championship Final", "Final"),
"402": ("Plate Final", "Plate"),
},
8: {
"301": ("Championship Final", "Final"),... |
"""
各行程旅游网站买票订酒店的订单数据
create by judy 2018/10/18
"""
from commonbaby.helpers import helper_crypto
from datacontract.idowndataset import Task
from datacontract.outputdata import EStandardDataType
from .feedbackbase import FeedDataBase, InnerDataBase, OrderData
class ITRAVELORDER_ONE(InnerDataBase, OrderData):
"""... |
import numpy as np
from sklearn.preprocessing import MinMaxScaler
class Processor:
def __init__(self, data):
self.data = [list(item) for item in data]
self.attr_count = len(self.data[0])
# # Used to map strings in numbers
# def apply_nominal_conversation(self):
# for i in range(0, self.attr_count):
# ... |
# Generated by Django 2.1.1 on 2019-02-09 10:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('log', '0002_auto_20190209_0933'),
]
operations = [
migrations.RemoveField(
model_name='log',
name='obj',
),
... |
#!/usr/bin/python
########################################################################################
#
# |B|I|G| |F|A|C|E| |R|O|B|O|T|I|C|S|
#
# HSV Colour selector for object detection using OpenCV
#
#
# Author : Peter Neal
#
# Date : 17 March 2015
# Last Update : 17 March 2015
#
###############################... |
# -*- coding: utf-8 -*-
from functools import partial
import dask.bag as db
from kartothek.core import naming
from kartothek.core.factory import _ensure_factory
from kartothek.core.utils import _check_callable
from kartothek.core.uuid import gen_uuid
from kartothek.io.eager import read_dataset_as_metapartitions
from ... |
from dialect import *
from xdsl.pattern_rewriter import RewritePattern, GreedyRewritePatternApplier, op_type_rewrite_pattern, PatternRewriter, PatternRewriteWalker
from xdsl.ir import MLContext, Operation, SSAValue, Region, Block, Attribute
from dataclasses import dataclass
import xdsl.dialects.memref as memref
impor... |
import numpy as np
import cv2
import tensorflow as tf
def get_clean_name(string):
if "depth" in string.lower() and "kernel" in string.lower():
return string.split('/')[0] + '/' + 'Kernel'
elif "depth" in string.lower() and "bias" in string.lower():
return string.split('/')[0] + '/' + 'Bias'
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... |
#!/usr/bin/env python
# coding=utf-8
import os
import logging
import datetime
from keras.utils.visualize_util import plot
from model_io import read_model
module_dir = os.path.dirname(os.path.abspath(__file__))
module_name = os.path.basename(__file__).split('.')[0]
log_path = os.path.join(module_dir, os.path.pardir... |
from multiprocessing import Process,Pool
def f(x):
return x*x
if __name__ == "__main__":
try:
p = Pool(5)
result = p.map(f,[1,2,3,4,5])
print(result)
except Exception as e:
print("The Actual Error is:",e) |
import os
import json
import copy
import logging
import collections
import datetime
from abc import ABCMeta, abstractmethod
import six
import openpype
from .constants import (
GLOBAL_SETTINGS_KEY,
SYSTEM_SETTINGS_KEY,
PROJECT_SETTINGS_KEY,
PROJECT_ANATOMY_KEY,
LOCAL_SETTING_KEY,
M_OVERRIDEN_KEY
... |
from qpsolvers import *
from operators import *
import numpy as np
def w_init(w0, Sinv):
"""
Initialize w0, the vectorized upper triangular coefficients of the adjacency matrix
"""
if type(w0) is str:
if (w0 == "qp"):
R = vecLmat(Sinv.shape[1])
qp = 0
assert False,"idk"
#quadprog::s... |
from sklearn.datasets import make_blobs
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from LogisticRegression import LogisticRegression
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, ... |
import os.path
def sdss_band_name(b):
if b in ['u','g','r','i','z']:
return b
if b in [0,1,2,3,4]:
return 'ugriz'[b]
raise Exception('Invalid SDSS band: "' + str(b) + '"')
def sdss_band_index(b):
if b in ['u','g','r','i','z']:
return 'ugriz'.index(b)
if b in [0,1,2,3,4]:
return b
raise Exception('Invali... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 27 00:30:31 2019
dogName1 = "One"
dogName2 = "Two"
dogName3 = "Three"
dogName4 = "Four"
dogName5 = "Five"
dogName6 = "Six"
@author: Gunardi Saputra
"""
print("Enter the name of dog 1: ")
dogName1 = input()
print("Enter the name of dog 2: ")
dogName2 = input()
print("E... |
/*
sum_(k=1)^t (2^k - 1) (n + 1 - (k + 1) a) (n + 1 - (k + 1) b) = 1/6 (a (b (-2 t^3 + 3 (2^(t + 2) - 3) t^2 - 13 t + 24 (2^t - 1)) + 3 (n + 1) t (t - 2^(t + 2) + 3)) + 3 (n + 1) (b t^2 - t (b (2^(t + 2) - 3) + 2) + n (-2 t + 2^(t + 2) - 4) + 4 (2^t - 1)))
vertical and horizontal : warasumm(1, 0, n, n-1, p)
cross ... |
"""This module provides the XML code for some basic example networks."""
NET_ELECTRICAL_PIECEWISE = """<network>
<edges>
<edge from="s" to="v">
<cost>
<piecewisequadratic>
<functionpart a=".5" b="0" c="0" tau="-inf"/>
<functionpart a="2.5" b="-12" c="18" tau="3"/>
</pie... |
#!/usr/bin/python
#
# A script to convert blob from the MS spec to array of byte to use in unitary tests
#
# 00000000 c7 01 00 01 20 54 e2
# 00000008 c7 01 00 01 20 54 e2
# taken from the spec, will give:
# 0xc7, 0x01, 0x00, 0x01, 0x20, 0x54, 0xe2,
# 0xc7, 0x01, 0x00, 0x01, 0x20, 0x54, 0xe2,... |
#!/bin/python
from setuptools import setup
extensions=[]
setup(
name='gmt-extensions',
packages=['gmt_extensions'],
# requires=['numpy (>=1.8)', 'scipy (>=0.14)',
# 'pythonigraph (>=0.7)'],
provides=['gmt_extensions'],
scripts=[],
license='BSD',
)
|
"""
Harness for running sql commands against a spatialite db from python.
This is work in progress towards a schema translation task.
From the project directory run:
./manage.py runscript spatialite_test --settings=hot_exports.settings -v2
Depends on django-extensions.
"""
import os
from string im... |
#!/usr/bin/env python3
# coding: utf-8
import torch
import torch.nn as nn
import torch.utils.data as data
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
import time, os
import numpy as np
import matplotlib.pyplot as plt
os.environ['CUDA_VISIBLE_DEVICES']='1'
#from benchmark_aflw1998 ... |
import RPi.GPIO as GPIO
import time
PWMFrequency = 50
InitialDutyCycle = 7.5
class OutputClock:
pin = None
frequency = None
pwm = None
name = None
def stop(self):
self.pwm.stop()
def __init__(self, pin, name, frequency):
print("Initializing clock on pin " + str(pin) + " with output frequency of " + str(fr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2019-07-02 01:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bims', '0148_auto_20190630_1300'),
]
operations = [
migrations.AlterField(... |
import requests
class HttpSession(requests.Session):
def __init__(self, *args, **kwargs):
self.timeout = kwargs.pop("timeout", None)
super().__init__(*args, **kwargs)
def request(self, *args, **kwargs):
kwargs.setdefault("timeout", self.timeout)
return super().request(*args, *... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.