content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Classical Heisenberg model Monte Carlo simulator
"""
import json
import os
import shutil
import time
import numpy as np
from kent_distribution.kent_distribution import kent2
from skdylib.spherical_coordinates import sph_urand, xyz2sph
from thermalspin.heisenberg_sy... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'employees.ui'
##
## Created by: Qt User Interface Compiler version 5.15.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################... |
import pygame, sys, noise, math
from pygame.locals import *
from random import randint, random
pygame.init()
try:
windowSize = int(input("Enter size of window in pixels (e.g. 400): "))
except:
# Give default size of 400px if invalid value entered
windowSize = 400
windowSurface = pygame.displa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created by Anand Sivaramakrishnan anand@stsci.edi 2018 12 28
This file is licensed under the Creative Commons Attribution-Share Alike
license versions 3.0 or higher, see
http://creativecommons.org/licenses/by-sa/3.0/
Python 3
matrixDFT.perform(): (also matrixDF... |
import os
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from .hooks import hookset
from .managers import PublishedPageManager
class Page(models.Model):
STATUS_CHOICES = (
(1, _("Draft")),
(2... |
#!/usr/bin/env python
"""
Bookizer
==========
Bookizer get's an almost uncertain number of CSV files and converts them into a big CSV/ODS/XLS/XLSX file
"""
import sys
from setuptools import setup
if sys.version_info.major < 3:
raise RuntimeError(
'Bookizer does not support Python 2.x anymo... |
#
# SDK-Blueprint module
# Code written by Cataldo Calò (cataldo.calo@mail.polimi.it) and Mirco Manzoni (mirco.manzoni@mail.polimi.it)
#
# Copyright 2018-19 Politecnico di Milano
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License... |
from office365.sharepoint.ui.applicationpages.client_people_picker import \
ClientPeoplePickerWebServiceInterface, ClientPeoplePickerQueryParameters
from tests import test_user_principal_name
from tests.sharepoint.sharepoint_case import SPTestCase
class TestSPPeoplePicker(SPTestCase):
@classmethod
def se... |
"""Build indexing using extracted features
"""
import numpy as np
import os, os.path
import pickle
import scipy.spatial
from scipy.spatial.distance import pdist, squareform
"""Build index
Given feature matrix feature_mat,
k is the number of nearest neighbors to choose
"""
def build_index(feature_mat, k):
sample_c... |
import sys
import os
import random
import math
import bpy
import numpy as np
from os import getenv
from os import remove
from os.path import join, dirname, realpath, exists
from mathutils import Matrix, Vector, Quaternion, Euler
from glob import glob
from random import choice
from pickle import load
from b... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 21 17:08:55 2020
@author: anon
"""
import subprocess
import numpy as np
import h5py
clear = np.zeros((100000, 2))
noisy = np.zeros((100000, 2))
for i in range(1, len(clear)):
clear[i] = clear[i-1] + np.array([1.,1.])
noisy[i] = clear[i] ... |
import sys
from pyramid.config import Configurator
from pyramid.i18n import get_localizer, TranslationStringFactory
from pyramid.threadlocal import get_current_request
def add_renderer_globals(event):
request = event.get('request')
if request is None:
request = get_current_request()
event['_'] ... |
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
class S... |
#!/usr/bin/env python3
# for now assuming the 'derived' repo is just checked out
import fire, yaml, git, os, shutil, sys, pathlib, subprocess, unidiff, time, logging
from neotermcolor import colored
def bold_yellow(text):
return colored(text, color='yellow', attrs='bold')
conf_file = ".differant.yml"
def dird... |
from __future__ import print_function
import os
from importlib import import_module
def split_path(path):
decomposed_path = []
while 1:
head, tail = os.path.split(path)
if head == path: # sentinel for absolute paths
decomposed_path.insert(0, head)
break
elif t... |
import pytest
from constructure.constructors import RDKitConstructor
from constructure.scaffolds import SCAFFOLDS
@pytest.mark.parametrize("scaffold", SCAFFOLDS.values())
def test_default_scaffolds(scaffold):
# Make sure the number of R groups in the `smiles` pattern matches the `r_groups`
# attributes.
... |
from capturewrap.builders import CaptureWrapBuilder
from capturewrap.models import CaptureResult |
import flask
from hacktech import auth_utils
from hacktech import app_year
import hacktech.modules.judging.helpers as judging_helpers
from hacktech.modules.applications.helpers import allowed_file
from werkzeug.utils import secure_filename
import os
import PyPDF2
def get_waiver_status(user_id, waiver_type):
query... |
from bflib import dice, units
from bflib.items import coins, listing
from bflib.items.ammunition.common import ShortbowArrow, LongbowArrow
from bflib.items.weapons.ranged.base import RangedWeapon
from bflib.rangeset import RangeSet
from bflib.sizes import Size
@listing.register_type
class Bow(RangedWeapon):
pass
... |
# Authors: Guillaume Favelier <guillaume.favelier@gmail.com>
#
# License: Simplified BSD
from ...fixes import nullcontext
from ._pyvista import _Renderer as _PyVistaRenderer
from ._pyvista import \
_close_all, _set_3d_view, _set_3d_title # noqa: F401 analysis:ignore
class _Renderer(_PyVistaRenderer):
def __... |
import matplotlib.pyplot as plt
import numpy as np
tolerance = 1e-1
radius = np.pi
# missile 1
x_m1, y_m1 = -np.pi, 0
v_m1 = 5
# missile 2
x_m2, y_m2 = 0, np.pi
v_m2 = v_m1
# missile 3
x_m3, y_m3 = np.pi, 0
v_m3 = v_m1
# missile 4
x_m4, y_m4 = 0, -np.pi
v_m4 = v_m1
plt.figure(figsize=(10, 10), dpi=80)
plt.title(" mi... |
import framebuf
gc.collect()
import time
gc.collect()
import machine
gc.collect()
import neopixel
gc.collect()
import network
gc.collect()
import urequests
gc.collect()
import utime
gc.collect()
from machine import RTC, I2C, Pin
#from ssd1306 import SSD1306_I2C
import sh1106 #Oled
gc.collect()
impor... |
# Import modules
import datetime
import spiceypy
import numpy as np
import pandas as pd
# Load the SPICE kernels via a meta file
spiceypy.furnsh('kernel_meta.txt')
# We want to compute miscellaneous positions w.r.t. the centre of
# the Sun for a certain time interval.
# First, we set an initial time in UTC.
INIT_TIME... |
r'''
Copyright 2014 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 required by applicable law or agreed to i... |
from __future__ import annotations
from typing import List
from dataclasses import dataclass
from ..model import Pos
@dataclass
class SingleCandidate:
pos: Pos
number: int
reason: str = 'unkown'
def __str__(self):
return f'{self.pos.idx}, {self.number}'
@dataclass
class MultiCandidate:
... |
"""
Gui for image_dialog
Author: Gerd Duscher
"""
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as Canvas
from matplotlib.figure import Figure
from pyTEMlib.microscope import microscope
class MySICanvas(Canvas):
def __init__... |
import os
import neuralbody.utils.geometry as geometry
import numpy as np
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
class SMPL(nn.Module):
def __init__(self, data_root, gender='neutral', spec='', beta=None):
super(SMPL, self).__init__()
file_path = os.path.join(
... |
# Problem Description:-https://leetcode.com/problems/longest-palindromic-substring/
class Solution:
def helper(self, s, left, right):
while left>=0 and right<len(s) and (s[left]==s[right]):
left-=1
right+=1
return s[left+1:right]
def longestPalindrome(self, s: str) -> s... |
from builtins import range
from .base import MLClassifierBase
import copy
import numpy as np
class RepeatClassifier(MLClassifierBase):
"""Simple classifier for handling cases where """
def __init__(self):
super(RepeatClassifier, self).__init__()
def fit(self, X, y):
self.value_to_repeat ... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
#from matplotlib import pyplot as plt
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files",".*"),("jpg files"... |
import numpy as np
from gym.spaces import Box
from gym.spaces import Discrete
import copy
from rlkit.envs.wrappers import ProxyEnv
class ParticleEnv(ProxyEnv):
def __init__(
self,
env,
):
ProxyEnv.__init__(self, env)
self.num_agent = self._wrapped_env.n
self.act... |
# ==================================================================
# Copyright (c) 2007,2008,2009 Metaweb Technologies, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistribut... |
import numpy as np
import deepdish as dd
from scipy.signal import welch
def interaction_band_pow(epochs, config):
"""Get the band power (psd) of the interaction forces/moments.
Parameters
----------
subject : string
subject ID e.g. 7707.
trial : string
trial e.g. HighFine, AdaptFi... |
'''
Priority Queue implementation using binary heaps
https://www.youtube.com/watch?v=eVq8CmoC1x8&list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu&index=17
This code is done without using reverse mapping - takes O(n) time for remove_elem(elem)
Can be improved by implementing it - https://www.youtube.com/watch?v=eVq8CmoC1x8&li... |
"""
hyperopt search spaces for each prediction method
"""
import numpy as np
from hyperopt import hp
from hyperopt.pyll.base import scope
from src.jobs.models import Job
from src.predictive_model.classification.models import CLASSIFICATION_RANDOM_FOREST, CLASSIFICATION_KNN, \
CLASSIFICATION_XGBOOST, CLASSIFICATIO... |
import logging
from datetime import date
from flask import request, render_template, jsonify, redirect, url_for
from weight import app
from weight.db import SessionScope
from weight.forms import WeightForm
from weight.db.queries import (
add_weight_data,
edit_weight_data,
delete_weight_data,
get_weight... |
## 旋转数组
# 方法一: 暴力法, 循环嵌套 时间:O(k*n) 空间:O(1)
# class Solution:
# def rotate(self, nums: List[int], k: int) -> None:
# n = len(nums) - 1
# j = 0
# while j < k:
# i = n
# temp = nums[n]
# while i > 0:
# nums[i] = nums[i-1]
# i... |
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_matrix(clf, X_test, y_test):
plt.clf()
plt.imshow(confusion_matrix(clf.predict(X_test), y_test),
interpolation='nearest', cmap=plt.cm.Blues)
plt.colorbar()
plt.xlabel("true label")
plt.ylabel("predi... |
import subprocess
class ShellCommandExecuter:
def __init__(self, current_working_directory, args):
self.current_working_directory = current_working_directory
self.args = args
def execute_for_output(self):
process = subprocess.run(self.args, stdout=subprocess.PIPE, cwd=self.curren... |
#Addition of a new dot.
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
#Initial state. Base dataset.
##def __init__ visualizer(self):
##Falta que lo clasifique.
def add_dot(sepal_width, sepal_length, color):
df = px.data.iris()
newDyc = {"sepal_width": sepal_width, "sepal... |
import codecs
import csv
import sys
import pickle
import os
try:
from . import config_wv
from . import pre_util
except:
sys.path.append("/Users/tdong/git/lg-flask/tasks/lgutil/pre_processing_wv/config_wv")
import config_wv
import pre_util
def get_all_lines(fname, encoding='utf8'):
with codecs... |
# Print out 2 to the 65536 power
# (try doing the same thing in the JS console and see what it outputs)
bignum = 2 ** 65536
print(bignum) |
from .cifar import CIFAR10NoisyLabels, CIFAR100NoisyLabels
__all__ = ('CIFAR10NoisyLabels', 'CIFAR100NoisyLabels')
|
dict1 = dict(One = 1, Two = 2, Three = 3, Four = 4, Five = 5)
print(dict1['Four'])
dict1['Three'] = 3.1
print(dict1)
del dict1['Two']
print(dict1) |
from __future__ import annotations
import pandas as pd
import numpy as np
from typing import List, Union, TYPE_CHECKING
from whyqd.base import BaseSchemaAction
if TYPE_CHECKING:
from ..models import ColumnModel, ModifierModel, FieldModel
class Action(BaseSchemaAction):
"""
Create a new field by iteratin... |
from zipfile import ZipFile
import os
class ExtractFiles:
def __init__(self):
self.ends_with = '.zip'
self._backup_dir = r"C:\dev\integratedSystem\all_images"
def handler_files(self, file_name):
if file_name.endswith(self.ends_with):
return self.extract_zips(file_name)
... |
import sys
import mechanics.colors as colors
from tcod import image_load
from tcod import console
from loader_functions.initialize_new_game import get_constants, get_game_variables
from loader_functions.data_loaders import load_game, save_game
from mechanics.menus import main_menu, messsage_box
from mechanics.game_stat... |
#!/usr/bin/python
# Classification (U)
"""Program: main.py
Description: Unit testing of main in daemon_rmq_2_isse.py.
Usage:
test/unit/daemon_rmq_2_isse/main.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unittest... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from azur... |
import myhdl
from myhdl import intbv
from rhea import Constants
from rhea.system import Bit, Byte
from rhea.system import ControlStatusBase
from ..misc import assign
class ControlStatus(ControlStatusBase):
def __init__(self):
""" The control-status object for the SPI controller
Attributes:
... |
from django.forms.widgets import Widget, Media
from django.utils.safestring import mark_safe
import django.utils.copycompat as copy
class MultiWidgetLayout(Widget):
"""
Django's built-in MultiWidget is a widget that is composed of multiple widgets.
MutliWidtetLayout implements the same concept but the ren... |
#!/usr/bin/env python2
# coding: utf-8
# Parses decompiled Java source and re-generates a Thrift interface file.
import re
import sys
import os
from os import path
thrift_type_names = [
None,
"void",
"bool",
"byte",
"double",
None,
"i16",
None,
"i32",
None,
"i64",
"str... |
from collections import namedtuple
class FilePath(
namedtuple('FilePath', [
'subject', 'filetype', 'load_path', 'save_path', 'bad_channel_path'
])):
__slots__ = ()
def __new__(cls,
subject,
filetype,
load_path,
save_p... |
"""
"A Simple Domain Shifting Network for Generating Low Quality Images" implementation
Step 2: Training simple convolutional regressor to mimic Cozmo camera.
"""
import torch
from torchvision import datasets
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
import os
from torch.ut... |
def digitize(num: int) -> list:
if num == 0:
return [0]
my_digitize = []
while num != 0:
l = num % 10
my_digitize.append(l)
num = (num - l) // 10
return list(reversed(my_digitize))
|
#================================Params.py=====================================#
# Created by Ciaran O'Hare 2019
# Description:
# This file just sets up some of the parameters that are used throughout the
# project. and some classes that link things together.
#=========================================================... |
num1 = 111
num2 = 222
num3 = 3333
num4 = 444444444444
num4 = 44444
num5 = 5555
|
"""empty message
Revision ID: 5c63a89ee7b7
Revises: 9afbd55082a0
Create Date: 2021-09-29 10:24:20.413807
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5c63a89ee7b7'
down_revision = '9afbd55082a0'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import unittest
from model.shsamodel import *
class SHSAModelTestCase(unittest.TestCase):
"""Tests SHSA model."""
def setUp(self):
self.__graph_dict = {
'a': ['d'],
'b': ['c'],
'c': ['b', 'c', 'd'],
'd': ['a', 'c'],
# unconnected nodes are n... |
# Copyright 2017 Starbot Discord Project
#
# 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... |
from minesweeper.logic import FLAG, OPEN, Square, MINE
def test_not_open():
value = FLAG | 1
s = Square.from_triple(0, 0, value)
assert not s.open
assert not s.value
def test_flag():
value = OPEN | 1
s = Square.from_triple(0, 0, value)
assert s.open
assert s.value == 1
def test_ope... |
# model settings
model = dict(
type='Recognizer2D',
backbone=dict(
type='Central_Model',
pretrained='checkpoints/up-g/mnb4-cls-bn.pth',
backbone_name='MTB4',
task_names=('gv_patch', 'gv_global'),
main_task_name='gv_global',
trans_type='crossconvhrnetlayer',
... |
from pathlib import Path
import argparse
import pandas as pd
import os
HERE = os.path.abspath(os.path.dirname(__file__))
DEFAULT_CONFIG_FILE = os.path.join(HERE, "config_templates",
"default_configs.txt")
DATASET_STATS = os.path.join(HERE, "dataset_stats", "dataset_stats.tsv")
def ... |
from abc import ABCMeta,abstractclassmethod
class PocInterface(metaclass=ABCMeta):
'''
POC 实现接口
'''
@abstractclassmethod
def validate(self,*args,**kwargs):
'''
漏洞验证接口方法
:param args: 自定义参数
:param kwargs: 自定义参数
:return: 自定义,建议存在返回True,否则返回False
'''
... |
from collections import OrderedDict
import requests
from civis import APIClient
from civis.base import EmptyResultError
def file_to_civis(buf, name, api_key=None, **kwargs):
"""Upload a file to Civis.
Parameters
----------
buf : file-like object
The file or other buffer that you wish to upl... |
# imports
import datetime as dt
import psycopg2
# db global variables
HOST = 'localhost'
USER = 'postgres'
PASSWORD = 'Master/99'
DATABASE = 'job_apps'
print('Initiating database connections.')
# db connection
conn = psycopg2.connect(host=HOST, database=DATABASE,
user=USER, password=PASSWORD... |
from . import blockcipher
from . import pkc
from . import keyexchange
from . import signature |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from datastruct.list.node import SNode
def reverse_order_output(head, res=None):
if head is None:
return []
if res is None:
res = []
res = reverse_order_output(head.next, res)
res.append(head.value)
return res
def find_intersectio... |
from core import analyzer, element
from ui import run
element_type = {
"Resistance": element.Resistance,
"CurrentSource": element.CurrentSource,
"VoltageSource": element.VoltageSource,
"CCCS": element.CCCS,
"VCCS": element.VCCS,
"CCVS": element.CCVS,
"VCVS": element.VCVS
}
def solve(data... |
__all__ = [
"ConjugateGradient",
"NelderMead",
"ParticleSwarm",
"SteepestDescent",
"TrustRegions",
]
from .conjugate_gradient import ConjugateGradient
from .nelder_mead import NelderMead
from .particle_swarm import ParticleSwarm
from .steepest_descent import SteepestDescent
from .trust_regions impo... |
# Generated by Django 3.0.1 on 2019-12-21 20:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('tacos', '0004_auto_20191... |
import ipaddress
import logging
import time
import uuid
import redis
from haipproxy.settings import (
REDIS_HOST,
REDIS_PORT,
REDIS_DB,
REDIS_PIPE_BATCH_SIZE,
LOCKER_PREFIX,
)
logger = logging.getLogger(__name__)
REDIS_POOL = None
#### redis ####
def get_redis_conn():
global REDIS_POOL
... |
f = open("latency", "w")
for x in range(0,100):
for y in range(0,100):
if(x == y):
f.write("0")
else:
f.write("100")
if(y != 99):
f.write(" ")
f.write('\n')
f.close()
|
from config.config import IMDB_BASE_URL
class MovieResponse:
# TODO: refactor this - use named parameters
def __init__(self, *vargs):
self.movie_id = vargs[0]
self.imdb_url = IMDB_BASE_URL + self.movie_id + "/"
self.title = vargs[1]
self.directors = vargs[2]
self.actors... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 10:11:05 2019
@author: alheritier
"""
from pykds import KDSForest
import numpy as np
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
dim = data.data.shape[1]
alpha_label= len(np.unique(data.target))
m = KDSForest(ntrees=1,se... |
import luigi
import json
import time
import re
import datetime
import subprocess
import base64
from urllib import urlopen
import uuid
from uuid import uuid4
from uuid import uuid5
from elasticsearch import Elasticsearch
#for hack to get around non self signed certificates
import ssl
import sys
# TODO
# * I think we wa... |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
import weakref
import numpy as np
import qmhub.helpmelib as pme
from .dobject import cache_update
class DependPME(pme.PMEInstanceD):
def __init__(self, cell_basis, alpha, order, nfft):
super().__init__()
self._name = "PME"
self._kwargs = {"alpha": alpha, "order": order, "nfft": nfft}
... |
import torch
import torch.nn as nn
class NeuralColumn(nn.Module):
def __init__(self, channels: int, output_dim: int) -> None:
""" channels is the number of output convolution channels for
each convolution layer of the network, except the last one.
"""
super(NeuralColumn, self).... |
"""D-Bus interface objects."""
from .systemd import Systemd
from .hostname import Hostname
from .rauc import Rauc
from ..coresys import CoreSysAttributes
class DBusManager(CoreSysAttributes):
"""A DBus Interface handler."""
def __init__(self, coresys):
"""Initialize D-Bus interface."""
self.... |
from enforce_typing import enforce_types
from engine import AgentBase
from agents.PublisherAgent import PublisherAgent
from agents.SpeculatorAgent import StakerspeculatorAgent
from agents.DataconsumerAgent import DataconsumerAgent
@enforce_types
class DataecosystemAgent(AgentBase.AgentBaseNoEvm):
"""Will operate... |
from django.core.management.commands.test import Command as TestCommand
from jsdir.core import JSDir
class Command(TestCommand):
def __init__(self):
JSDir.set_use_finders(True) # sets the value only for this thread
super(Command, self).__init__()
|
import matplotlib as mil
import tensorflow as tf
from matplotlib import pyplot
fig = pyplot.gcf()
fig.set_size_inches(4, 4)
sess = tf.InteractiveSession()
image_filename = "/home/ubuntu/Downloads/n02107142_16917.jpg"
filename_queue = tf.train.string_input_producer([image_filename]) # list of files to read
reader... |
#
# Copyright (C) 2014-2015 UAVCAN Development Team <uavcan.org>
#
# This software is distributed under the terms of the MIT License.
#
# Author: Ben Dyer <ben_dyer@mac.com>
# Pavel Kirienko <pavel.kirienko@zubax.com>
#
from __future__ import division, absolute_import, print_function, unicode_literals
import... |
from .binarytree import BinaryTree
class LinkedBinaryTree(BinaryTree):
""" Linked reperesentation of a binary tree structure. """
class _Node: # Ligtweight non-public class for storing a node
__slots__ = '_element', '_parent', '_left', '_right'
def __init__(self, element, parent=None, lef... |
import logging
from helper import is_welsh
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class CoursesBySubject:
def __init__(self, mapper, language):
self.mapper = mapper
self.language = language
def group(self, courses, limit, of... |
import copy
import numpy
def convert_to_binary(list_of_digits):
list_of_str_digits = [str(digit) for digit in list_of_digits]
return int("".join(list_of_str_digits), 2)
with open("data/day3.txt") as f:
# The entire input forms a matrix of integers, parse it as such.
matrix = [[int(num) for num in l... |
# Copyright 2018 The ops Developers
#
# 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... |
# -*- coding: utf-8 -*-
"""
KJ-65X9500G の輝度制限と階調特性の関係調査
=========================================
Description.
"""
# import standard libraries
import os
# import third-party libraries
import numpy as np
from colour import write_image
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
# impor... |
import pytest
from openpecha.utils import download_pecha
@pytest.mark.skip("Downloading github repo")
def test_download_pecha():
pecha_path = download_pecha("collections")
|
# Generated by Django 2.2 on 2020-08-11 11:55
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Iniciativa',
fields=[
('id', models.AutoField... |
from dsame.trees.BinaryTreeNode import BinaryTreeNode
def inOrder(root: BinaryTreeNode):
if root:
inOrder(root.left)
print(root.data)
inOrder(root.right)
a = BinaryTreeNode(2)
b = BinaryTreeNode(3)
c = BinaryTreeNode(1, a, b)
print(inOrder(c))
|
import os
from ast import literal_eval
from pathlib import Path
import numpy as np
def read_info(filename: os.PathLike) -> dict:
"""Read volume metadata.
Parameters
----------
filename : PathLike
Path to the file.
Returns
-------
dct : dict
Dictionary with the metadata.
... |
import time
from options.train_options import TrainOptions
opt = TrainOptions().parse() # set CUDA_VISIBLE_DEVICES before import torch
import pickle
from data.custom_transforms import ToLabelTensor
# with open("opt.obj",'wb') as f:
# pickle.dump(opt,f)
from data.segmentation import SegmentationDataset
from models... |
from ...attribute import models as attribute_models
from ...discount import models as discount_models
from ...product import models as product_models
from ...shipping import models as shipping_models
def resolve_translation(instance, _info, language_code):
"""Get translation object from instance based on language... |
# Generated by Django 3.0.13 on 2021-04-01 08:17
from django.db import migrations, models
import ensembl.production.djcore.models
class Migration(migrations.Migration):
dependencies = [
('ensembl_dbcopy', '0005_targethostgroup'),
]
operations = [
migrations.AlterField(
model... |
from __future__ import absolute_import
import logging
# App must be initialized before models or ADDONS_AVAILABLE are available
from website.app import init_app
init_app()
from osf.models import OSFUser, AbstractNode
from framework.database import paginated
from scripts.analytics.base import SnapshotAnalytics
from w... |
#!/usr/bin/env python3
#class dedicated to archival functions for dnmt data
import re
import sys
import subprocess,platform,os,time,datetime,zipfile
import difflib
import pickle
import collections
# import pysvn
# import git
#3rd party imports
#local subroutine import
from DNMT.procedure.subroutines import SubRou... |
# Django
from django.db import models
class UserAbstractModel(models.Model):
""" Modelo basico abstracto.
UserAbstractModel es una clase abstracta de la que heredan
todos los modelos de User de la API. Esta clase provee
los siguientes atributos:
+ created (DateTime): Almacena la fecha de creacio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.