content stringlengths 5 1.05M |
|---|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from django.shortcuts import render
def Startpage(request):
return render(request,'starter.html')
|
import webapp2
import os
import jinja2
import json
import datetime
import time
from google.appengine.api import users
from google.appengine.ext import ndb
from database import seed_data
from users import User
from content_manager import populate_feed, logout_url, login_url
from data import Course, Teacher, User, Post, ... |
# -*- coding:utf-8 -*-
from kamo import TemplateManager
import os.path
import logging
logging.basicConfig(level=logging.DEBUG)
m = TemplateManager(directories=[os.path.dirname(__file__)])
template = m.lookup("template.kamo")
print(template.render())
|
import cv2
from imutils.paths import list_images
import imutils
import re
import datetime
def get_frame_number(impath):
return int(re.search(r"image data (\d+)", impath).group(1))
def get_timestamp(impath):
"assuming that the timestamp is a part of the image name"
date_str = impath.split(".")[0]
date_... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the birthday function below.
def birthday(s, d, m):
totalCount = 0
l = len(s)
# print("{} {} {}".format(s, d, m))
for i in range(l):
sv = 0
for j in range(i, i+m):
if(l == j):
... |
import tensorflow as tf
import numpy as np
from src.tftools.custom_constraint import MinMaxConstraint
shear_multi = 0.01
class ShearLayer(tf.keras.layers.Layer):
def __init__(self, trainable=True, **kwargs):
"""
:param visible: one dimension of visible image (for this dimension [x,y] will be com... |
#!/usr/bin/env python3.7
import os
BLOCK_SIZE = 256
P = [
(0, [1, 7]),
(1, [0, 8]),
(0, [5, 3]),
(1, [8, 6]),
(0, [3, 9]),
(1, [4, 0]),
(0, [9, 1]),
(1, [6, 2]),
(0, [7, 5]),
(1, [2, 4]),
]
def n2B(b,length=BLOCK_SIZE):
return list(map(int, bin(b)[2:].rjust(BLOCK_SIZE, '0'... |
"""
'''
Description: Problem 912 (Sort an Array) - Solution 1
Version: 1.0.0.20220322
Author: Arvin Zhao
Date: 2022-03-19 12:58:01
Last Editors: Arvin Zhao
LastEditTime: 2022-03-22 19:38:21
'''
"""
from typing import List
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
"""Built-in stab... |
# Copyright 2020 Google LLC. 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 a... |
import random
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QVBoxLayout
from gui import *
windowHeight = 600
windowWidth = 800
background_color = "#111111"
def change... |
def optfunc(arg1, arg2, arg3):
'''
函数语法定义
:param arg1:
:param arg2:
:param arg3:
:return:
'''
# return 'hello world'
return "hello world", True, False |
import unittest
from typing import Dict, Optional
import sqlalchemy.engine
from magma.db_service.config import TestConfig
from magma.db_service.models import Base
from magma.db_service.session_manager import Session
from sqlalchemy import MetaData, create_engine
class DBTestCaseBlueprint(unittest.TestCase):
meta... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import importlib
def add_logging_arguments(parser, default=logging.WARNING):
"""
Add options to configure logging level
:param parser:
:p... |
# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0
import pytest
from utils import assertTest
pytest_plugins = ["pytester"]
common_code = """
import os
import time
import logging
import pytest
"""
def test_success_plugin(pytester, otel_service):
"""test a success test"""
pytester.... |
import numpy as np
import pandas as pd
from pycytominer.operations import sparse_random_projection
data_df = pd.DataFrame(
{
"Metadata_plate": ["a", "a", "a", "a", "b", "b", "b", "b"],
"Metadata_treatment": [
"drug",
"drug",
"control",
"control",
... |
import sys
import versioneer
from setuptools import setup
from broomer import (__version__ as version,
__description__ as description)
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except ImportError as e:
long_description = open('README.md').read()
exc... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2019-07-12 07:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trend', '0010_auto_20190711_1434'),
]
operations = [
migrations.AddField(
... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
# vase feed api:
from django.conf import Settings
from profilesproject import settings
class UserProfileManager(BaseUserMana... |
# -*- coding: utf-8 -*-
from typing import Any, Optional, Tuple
from .neg_cycle import negCycleFinder
Cut = Tuple[Any, float]
class network_oracle:
"""Oracle for Parametric Network Problem:
find x, u
s.t. u[j] − u[i] ≤ h(e, x)
∀ e(i, j) ∈ E
"""
def __init__(... |
import gym
class Engine:
def __init__(self, env_name, max_total_steps = 20000,
max_episodes = 3000,
max_steps_per_episode = 200):
self.env = gym.make(env_name)
self.max_total_steps = max_total_steps
self.max_episodes = max_episodes
self.max_steps_per_episode = max_steps_per_episode
se... |
import unittest
class TestServer(unittest.TestCase):
def test_server(self: unittest.TestCase) -> None:
pass
if __name__ == '__main__':
unittest.main()
|
"""Basic tools for dense recursive polynomials in ``K[x]`` or ``K[X]``. """
from sympy import oo
from sympy.core import igcd
from sympy.polys.monomials import monomial_min, monomial_div
from sympy.polys.orderings import monomial_key
import random
def poly_LC(f, K):
"""
Return leading coefficient of ``f``.
... |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2020 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
from pathlib import Path
import sys
from tqdm import tqdm
if len(sys.argv) < 2 or (sys.argv[1] != '0' and sys.argv[1] != '1'):
print('usage: python create_symlinks.py (0 | 1)')
sys.exit()
if sys.argv[1] == '0':
path = '../CodeInquisitor/PATTERN_ANALYSIS/blackbox_time_series'
else:
path = '../CodeInquisitor/PA... |
#!/usr/bin/env python
import os
import sys
import globalvar
sys.path.append("./")
os.chdir(globalvar.Runloc)
def monitor(appName):
pid = os.fork()
if 0 == pid: # child process
os.system(appName)
sys.exit(0)
else: # parent process
os.wait()
if __name__ == '__main__' :
while... |
muster = open("muster.txt", "r")
output = open("output.txt", "r")
mustervals = []
outputvals = []
for line in muster:
a,b,val = line.split(" ")
mustervals.append(int(val))
for line in output:
outputvals.append(int(line))
print len(mustervals)
print len(outputvals)
length = min(len(mustervals), len... |
#!/usr/bin/env python3
"""Command-line wrapper for simpleLabels.cli_labelComands."""
import loadPath # Adds the project path.
import linkograph.simpleLabels
linkograph.simpleLabels.cli_labelCommands()
|
"""
setup.py - setuptools configuration for esc
"""
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="lblsolve",
version="0.1.0",
author="Soren I. Bjornstad",
author_email="[email protected]",
description="solitaire solver for ... |
#
#
#
##
from __future__ import print_function, unicode_literals
import inspect
import os
import socket
import pprint as pp
import time
import pickle
from workflow import *
from manager import *
DEBUG = 0
class Pipeline( object ):
""" The main pipeline class that the user will interact with """
def __... |
# NOTE dataloader needs to be implemented
# Please use special/kinetics_video_unimodal.py for now
import os
import sys
import torch
sys.path.append(os.getcwd())
from unimodals.common_models import ResNetLSTMEnc, MLP
from datasets.kinetics.get_data import get_dataloader
from training_structures.unimodal import train... |
"""Utility methods for schedule parsing."""
from datetime import time
from typing import List
from .scheduletypes import ScheduleEntry, ScheduleEvent
def sort_schedule_events(events: List[ScheduleEvent]) -> List[ScheduleEvent]:
"""Sort events into time order."""
return sorted(events, key=lambda e: e[0])
d... |
"""Test connection of containment relationship."""
from gaphor import UML
from gaphor.core.modeling import Diagram
from gaphor.diagram.tests.fixtures import allow, connect, disconnect
from gaphor.UML.classes import ClassItem, PackageItem
from gaphor.UML.classes.containment import ContainmentItem
def test_containment... |
import json
import requests
import settings
from geotext import GeoText
with open("txt/tom.txt", "r") as f1:
tom = f1.read()
with open("txt/huck.txt", "r") as f2:
huck = f2.read()
with open("txt/life-on-the-mississippi.txt", "r") as f3:
life = f3.read()
with open("txt/roughing-it.txt", "r") as f4:
r... |
import tensorflow as tf
from .basic_ops import *
"""This script defines 3D different multi-head attention layers.
"""
def multihead_attention_3d(inputs, total_key_filters, total_value_filters,
output_filters, num_heads, training, layer_type='SAME',
name=None):
"""3d Multihead scaled-dot-product atten... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtWidgets import QTableWidgetItem, QHeaderView
from views.py.askLepWidgetQt import Ui_askLepWidgetFrame
class AskLepWidget(Ui_askLepWidgetFrame):
def __init__(self, master, view, expression):
self.view = view
... |
#!/usr/bin/env python
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
if __name__=='__main__':
q=Queue()
q.enqueue(3)
q.en... |
import numpy as np
import mindspore
from mindspore import context, ops, Tensor, nn
from mindspore.common.parameter import Parameter, ParameterTuple
import copy
context.set_context(mode=context.PYNATIVE_MODE, device_target="CPU")
_update_op = ops.MultitypeFuncGraph("update_op")
@_update_op.register("Tensor", "Tens... |
from django.db import models
from ckeditor.fields import RichTextField
# Create your models here.
class MainPageStatisticNumber(models.Model):
number = models.IntegerField(null=True, blank=True)
description = models.TextField(null=True, blank=True)
class Meta:
verbose_name_plural = "Физический фа... |
#!/usr/bin/python
# part of https://github.com/WolfgangFahl/play-chess-with-a-webcam
from pathlib import Path
import os
import getpass
import socket
class Environment:
""" Runtime Environment """
debugImagePath="/tmp/pcwawc/"
def __init__(self):
""" get the directory in which the testMedia resides... |
import pytest
import magma as m
def test_array_partial_unwired():
class Foo(m.Circuit):
io = m.IO(A=m.Out(m.Bits[2]))
io.A[0] @= 1
with pytest.raises(Exception) as e:
m.compile("build/Foo", Foo)
assert str(e.value) == """\
Found unconnected port: Foo.A
Foo.A
Foo.A[0]: Connect... |
/home/runner/.cache/pip/pool/b8/3c/25/da29a843bef53d2645fcb22fa7cb6ae50c3b7d5408fea6d1078ceefdf5 |
import warnings
from pathlib import Path
from typing import Any, Dict, List, Optional
from gobbli.augment.base import BaseAugment
from gobbli.docker import maybe_mount, run_container
from gobbli.model.base import BaseModel
from gobbli.model.context import ContainerTaskContext
from gobbli.util import assert_type, escap... |
# Approximation using a Greedy Algorithm
import math
def distance(point1, point2):
dx = point2[0] - point1[0]
dy = point2[1] - point1[1]
return math.hypot(dx, dy)
unvisited = set()
total_dist = 0
current_index = 0
points = []
n = int(input())
for i in range(n):
point = tuple(map(int, input().split(... |
# Programa que lê nome, sexo e idade de várias pessoas, guardando os dado de cada pessoa em um
# dicionário e todos os dicionários em uma lista. No final, mostra:
# Quantas pessoas foram cadastradas; A média de idade; Uma lista com as mulheres; Uma lista de pessoas com idade acima
# da média.
cadastro = []
pessoa = {}... |
'''
13-loc and iloc [1]
With loc and iloc you can do practically any data selection operation on DataFrames
you can think of. loc is label-based, which means that you have to specify rows and
columns based on their row and column labels. iloc is integer index based, so you have to specify rows and columns by their int... |
import lucs_tools
from time import sleep
class skyscanner(lucs_tools.internet.internet_base_util):
BASE_LINK = 'https://www.skyscanner.com/transport/flights-from/FROM_AIRPORT/DEPART_DATE/RETURN_DATE/?adults=1&children=0&adultsv2=1&childrenv2=&infants=0&cabinclass=economy&rtn=1&preferdirects=false&outboundalt... |
__title__ = 'DNS Explorer/Tracker'
__version__ = '1.0.0'
__author__ = "Jan Wendling <[email protected]>"
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2021 - Jan Wendling'
import dns.reversename, dns.resolver
import model.host
def run_application(target: str):
'''
IP or Domain to start
''... |
# Solution Reference:
# http://stackoverflow.com/questions/16427073/signed-integer-to-twos-complement-hexadecimal
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
#### works with positive num but fails with negative num
#
# d =... |
from parsl.config import Config
from parsl.executors import HighThroughputExecutor
from parsl.launchers import JsrunLauncher
from parsl.providers import LSFProvider
from parsl.addresses import address_by_interface
config = Config(
executors=[
HighThroughputExecutor(
label='Summit_HTEX',
... |
import click
import functools
def commet_logger_args(func):
@functools.wraps(func)
@click.option("--comet-project-name")
@click.option("--comet-offline", is_flag=True)
@click.option("--comet-offline-dir", type=click.Path(exists=True), default=".")
@click.option("--comet-auto-metric-logging", is_fl... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 30th 22:21:07 2016
Simple driver for GrainHill model, based on example by Charlie Shobe for
his Brake model.
"""
import os
print('grain_hill_dakota_friendly_driver here. cwd = ' + os.getcwd())
import grain_hill_as_class
from landlab import load_params
import numpy as np... |
# tests.test_utils.test_types
# Tests for type checking utilities and validation
#
# Author: Benjamin Bengfort <[email protected]>
# Created: Fri May 19 10:58:32 2017 -0700
#
# ID: test_types.py [79cd8cf] [email protected] $
"""
Tests for type checking utilities and validation.
Generally if there ... |
import torch
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import torchvision.transforms as T
import os
os.environ['TORCH_HOME'] = 'Cache'
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
from utils import *
from utils import COCO_INSTANCE_CATEG... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on ...
@author: ...
"""
|
from django.contrib import admin
from elections_app.models import Person, Info, Election
def import_data(modeladmin, request, queryset):
print("hello")
admin.site.add_action(import_data)
admin.site.register(Person)
admin.site.register(Info)
admin.site.register(Election)
|
import json
from base64 import b64encode, b64decode
from collections import namedtuple
from connexion.exceptions import ProblemException
from itertools import product
from skyfield.api import Loader, Topos, EarthSatellite
from home.leaf import LeafPassFile
from flask import request, Response
from home.models import G... |
from django.db import models
from account.models import Profile
from django.contrib.auth.models import User
STATUS_CHOICES = [
("created", "created"),
("accepted", "accepted"),
("done", "done"), # done jest po zamknieciu przez boomera
("finished", "finished") # fnished jest po zamknieciu przez boomera ... |
import requests #import Library after cmd pip install requests
print("////////////")
#이미지가 있는 url 주소
url="http://search1.kakaocdn.net/argon/600x0_65_wr/ImZk3b2X1w8"
#해당 url로 서버에게 요청
img_response=requests.get(url)
#요청에 성공했다면,
if img_response.status_code==200:
#print(img_response.content)
print("=========... |
import requests
from bs4 import BeautifulSoup
results = []
class Sale:
#Данный по ктороым он будет искать
Sale = 'https://www.amway.ua/nashi-marky/holiday-promotions'
haders = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/53... |
from datetime import datetime
from typing import Optional
from uuid import uuid1
import pytest
import pytz
from snuba.consumer import KafkaMessageMetadata
from snuba.consumers.snapshot_worker import SnapshotProcessor
from snuba.datasets.cdc.types import InsertEvent
from snuba.datasets.storages import StorageKey
from ... |
from django.urls import include, path
from rest_framework import routers
from credit_integration import views
app_name = "credit_integration"
router = routers.DefaultRouter()
urlpatterns = [
path("", include(router.urls)),
path(
"get_credit_decisions/",
views.get_credit_decisions,
n... |
import asyncio
import os
from unittest import mock
import pytest
from async_asgi_testclient import TestClient
from django.http import HttpResponse
from django.urls.conf import path
from django_simple_task import defer
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"
@pytest.fixture
async def get_app():
... |
# -*- coding: utf-8 -*-
'''
Handles PDF form filling
'''
from collections import OrderedDict
from PyPDF2 import PdfFileWriter, PdfFileReader
def _getFields(obj, tree=None, retval=None, fileobj=None):
"""
Extracts field data if this PDF contains interactive form fields.
The *tree* and *retval* parameters ... |
from shorty.services import constants
from shorty.services.bitly.bitly_serv import BitlyService
from shorty.services.tinyurl.tinyurl_serv import TinyUrlService
import validators
from shorty.services import error_handler
DEFAULT_SERVICE = "tinyurl"
ACCEPTED_SERVICES = ["tinyurl", "bitly"]
class Services:
""" thi... |
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import o... |
# J'écris en notation PEP 8
# Vous avez le droit de ne pas mettre d'espace
#par exemple
# 1er exercice
# Introduction sur les séquences
# Boucles, if, comparaison
#
# J'ai une liste de nombres entiers: [5, 4, 8, 2]
# Le but est de trier la liste en ordre croissant
#
# A l'issue de l'exercice on doit obtenir [2, 4, 5,... |
import requests, json, time, currency, exchange, pools
class Miner:
def cost(alg):
#returns lowest cost of alg in H/s/BTC/Day
pass
def order(alg, cost):
#opens a new order with alg algorithm costing cost btc
pass
def getOrders():
#returns dictionary of order dictionarys
pass
def getOrder(alg):
#re... |
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from member.models import SocialUserData
User = get_user_model()
class Backend(ModelBackend):
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotE... |
### Required Libraries ###
import os
# General Data Manipulation Libraries
import numpy as np
import pandas as pd
# Log and Pickle Libraries
import logging
import pickle
# Model & Helper Libraries
import xgboost
from sklearn.metrics import roc_auc_score
from sklearn.metrics import confusion_matrix
logging.basicCon... |
#!/usr/bin/python3
VOWELS = ['a', 'e', 'i', 'o', 'u']
def words():
with open('word_list.txt') as f:
for line in f:
yield line.strip()
def get_vowels(word):
vowel_only = []
for letter in word:
if letter in VOWELS:
vowel_only.append(letter)
return vowel_only
def... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 1 09:02:36 2017
@author: Paris
"""
import autograd.numpy as np
import matplotlib.pyplot as plt
from pyDOE import lhs
from gaussian_process import GP
np.random.seed(1234)
def f(x):
return x * np.sin(4.0*np.pi*x)
def Normalize(X, X_m, X_s):
... |
"""This module defines the lambda_handler
"""
import json
from scrapy.utils.project import get_project_settings
from scrapy.crawler import CrawlerRunner
from twisted.internet import reactor
from custom_process import CustomProcess
def spider_process(spider, settings=None):
"""Runs a scrapy CrawlerRunner"""
... |
from __future__ import annotations
import asyncio
from subprocess import PIPE, CalledProcessError
from typing import IO, Tuple, Union
from typing_extensions import Protocol
from .effect import Effect, Try, add_repr, depend, from_callable
from .either import Left, Right
from .functions import curry
from .immutable im... |
#!/usr/bin/env python
#
# Copyright 2011 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 req... |
import time
import numpy as np
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from sklearn.gaussian_process import GaussianProcess
from sklearn.linear_model import Ridge, Lasso
from sklearn.svm import NuSVR, SVR
import scipy
from util import Logger, get_rmse
class Linear():
def __init_... |
# Copyright (c) Facebook, Inc. and its affiliates.
# -*- coding: utf-8 -*-
import typing
import fvcore
from fvcore.nn import activation_count, flop_count, parameter_count, parameter_count_table
from torch import nn
from ..export import TracingAdapter
__all__ = [
"activation_count_operators",
"flop_count_oper... |
#!/usr/bin/env python
"""
scp tests
"""
import unittest
import mock
from cirrus.scp import SCP, put
class ScpTests(unittest.TestCase):
@mock.patch('cirrus.scp.local')
def test_scp(self, mock_local):
s = SCP(
target_host="HOST",
target_path="/PATH",
source="somefil... |
from bs4 import BeautifulSoup
import re
__author__ = 'fcanas'
class IzProperties(dict):
"""
Responsible for parsing and containing any properties used by IzPack's installation spec files.
"""
def __init__(self, path):
"""
Initialize paths to properties and begin parsing.
"""
... |
import glob
# from multiprocessing import Pool
import multiprocessing
import multiprocessing as mp
import os.path
from pathlib import Path
from typing import List, Tuple
import numpy as np
import torchvision.transforms as standard_transforms
import tqdm
from PIL import Image
from numpy import ndarray
from utils impor... |
import numpy as np
import pywt
import pickle
from sklearn.model_selection import train_test_split
import argparse
from scipy import stats
import supervised_learning
import random
NR_THREADS = 14
#WAVELETS = ['bior6.8', 'cgau8', 'cmor', 'coif17', 'db38', 'dmey', 'fbsp', 'gaus8', 'haar', 'mexh', 'morl', 'rbio6.8', 'sha... |
import pytest
import numpy as np
import numpy.testing as npt
from apl.posterior_approximation import LogLikelihood
@pytest.mark.parametrize(
"D,f_x,expected",
[
(
np.asarray([[0, 1], [2, 0], [2, 3]]),
np.asarray([1.5, 0.7, 2.1, 1.2], dtype=np.float32),
np.asarray([0... |
import os
import random
import sys
import warnings
import numpy
from bokeh.io import curdoc
from bokeh.models.widgets import Panel, Tabs
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
file_path = os.path.realpath(__file__)
root_path = os.path.dirname(os.path.dirname(os.path.dirname(o... |
# coding: utf-8
# # Dataset preparation and Mask R-CNN feature vector extraction
# Change path to Mask RCNN directory:
import os
# Root directory of the project
ROOT_DIR = os.path.abspath("./")
# import os
import sys
import json
import random
import math
import numpy as np
import skimage.io
import matplotlib
mat... |
""" Simulation Dataset Catalog
"""
import fcntl
import glob
import logging
import os
import shutil
from pathlib import Path
from PIL import Image
from pyquaternion import Quaternion
from datasetinsights.datasets.unity_perception import (
AnnotationDefinitions,
Captures,
)
from datasetinsights.datasets.unity_... |
import os
import numpy as np
def exp_func(x, a, b, c):
#y = a * np.exp(-b * x) + c
y = (a - c) * np.exp(-b * x) + c
return y
def time_resolved_anisotropy_decay_func(t, r0, r_inf, transfer_rate):
r_t = (r0-r_inf) * np.exp(-2 * transfer_rate * t) + r_inf
return r_t
def two_phase_exp_decay_func(x, ... |
# -*- coding: utf-8 -*-
#Import packages
import numpy as np
import pandas as pd
import imageio
import matplotlib.pyplot as plt
#Set Random Seed
np.random.seed(438672590)
#List of contestants in order of purchase
Contestants = ["Mary Q",
"Will N",
"Will C",
"David D",
"Sarah H",
"Rachel P",
"... |
#!/usr/bin/python
# Copyright (c) 2014, 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 imp
import os
import re
import shutil
import shlex
import subprocess
import sys
... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Test the discrete_domain utilities.
Caveat assumes that the MNI template image is available at
in ~/.nipy/tests/data
In those tests, we often access some ROI directly by a fixed index
instead of using... |
import os
CONFIG = {'local_data_dir': 'themis_data/',
'remote_data_dir': 'http://themis.ssl.berkeley.edu/data/themis/'}
# override local data directory with environment variables
if os.environ.get('SPEDAS_DATA_DIR'):
CONFIG['local_data_dir'] = os.sep.join([os.environ['SPEDAS_DATA_DIR'],
... |
# Copyright 2020 Konstruktor, 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 required by applicable la... |
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from cros.factory.probe.functions import sysfs
from cros.factory.probe.lib import cached_probe_function
REQUIRED_FIELDS = ['vendor']
OPTIONAL_FIELDS = [... |
# This file will read results.txt after it is created by the simulator finishing a run.
def read_file(res_location="results.txt"):
# bring in results.txt as a list of strings for each line
# open file in read mode.
file1 = open(res_location, "r+")
results = file1.readlines()
file1.close()
# che... |
import unittest
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune
from torchvision.models.squeezenet import SqueezeNet
import simplify
from simplify.utils import set_seed
from tests.benchmark_models import models
class SimplificationTest(unittest.TestCase):
def setUp(self):
set_see... |
# 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 writing, software
# d... |
from . import atomic
from . import processtweet
from . import standardize
from . import tweet
from .preprocess import preprocess
# from .preprocess import get_preprocess_func
|
import os
from datetime import datetime
from logging import getLogger
from time import time
import chess
import re
from supervised_learning_chess.agent.player_chess import ChessPlayer
from supervised_learning_chess.config import Config
from supervised_learning_chess.env.chess_env import ChessEnv, Winner
from supervised... |
# Copyright (c) 2017 Polytechnique Montreal <www.neuro.polymtl.ca>
#
# About the license: see the file LICENSE.TXT
""" Qt widgets for manual labeling of images """
from __future__ import absolute_import, division
import logging
from time import time
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg ... |
# -*- coding: utf-8 -*-
#================================================================
# Copyright (C) 2020 * Ltd. All rights reserved.
# Time : 2020/3/15 18:01
# Author : Xuguosheng
# contact: [email protected]
# File : character_5.py
# Software: PyCharm
# Description :图像分类 fashsion_minist
#=============================... |
import re
import sublime
import sublime_plugin
def plugin_loaded():
global g_settings
g_settings = sublime.load_settings('sxs_settings.sublime-settings')
g_settings.clear_on_change('sxs_settings')
update_settings()
g_settings.add_on_change('sxs_settings', update_settings)
def update_settings(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.