content stringlengths 5 1.05M |
|---|
start = int(input('enter lower limit of the range='))
end = int(input('enter upper limit of the range='))
for i in range(start, end+1):
if i>1:
for j in range(2,i):
if(i % j==0):
break
else:
print(i)
|
# plot a histogram of scores for cse 473 project 1
# author: nicholas ruhland
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
import sys
import os
import seaborn as sns
sns.set()
if len(sys.argv) != 2:
print 'Usage: python plot_scores.py <student code output directory>'
exit()
... |
from flask import Flask, jsonify, request
app = Flask(__name__) # Gives a unique name
stores = [
{
'name': 'MyStore',
'items': [
{
'name': 'My Item',
'price': 15.99
}
]
}
]
"""
@app.route('/') # Route of the endpoint 'http://www.google.com/'
def home():
return "Hello, world!... |
import unittest
import test_setup
from core.test_block import TestBlock
from core.test_transaction import TestTransaction
from core.test_blockchain import TestBlockchain
import yadacoin.core.config
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)
|
import copy
from unittest import TestCase
from theano.compile.pfunc import pfunc
from theano import gradient
from theano import tensor
from theano.tests import unittest_tools
import numpy
# Skip test if cuda_ndarray is not available.
from nose.plugins.skip import SkipTest
import theano.sandbox.cuda as cuda_ndarray
i... |
import numpy as np
from time import sleep
from os import SEEK_END
from multiprocessing import Value
from .utils import align_to_page
import ctypes
class MemoryAllocator():
def __init__(self, fname, offset_start, page_size):
self.fname = fname
self.offset = align_to_page(offset_start, page_size)
... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
#
# Copyright (c) 2014 unfoldingWord
# http://creativecommons.org/licenses/MIT/
# See LICENSE file for details.
#
# Contributors:
# Jesse Griffin <jesse@distantshores.org>
#
'''
Writes a JSON catalog of in progress OBS translations based on door43.org.
'''
import os
i... |
import os, random
def _ifacePath(ifname):
return "/sys/class/net/%s" % ifname
def _brifPath(brname):
return os.path.join(_ifacePath(brname), "brif")
def ifaceExists(ifname):
return os.path.exists(_ifacePath(ifname))
def ifaceList():
return os.listdir(_ifacePath(""))
def bridgeExists(brname):
return os.path.ex... |
from deap import base, creator, gp, tools
from deap import algorithms as algo
import numpy as np
import networkx as nx
from sklearn import preprocessing
from scipy.stats.stats import spearmanr
import ctypes as ctypes
import itertools as itertool
import copy
import pickle
from random import random, randint, sa... |
"""
Tests for financialaid models
"""
from django.db.models.signals import post_save
from factory.django import mute_signals
from rest_framework.exceptions import ValidationError
from financialaid.constants import FinancialAidStatus
from financialaid.factories import (
TierFactory,
FinancialAidFactory
)
from f... |
from twisted.internet.defer import inlineCallbacks
import hathor
from hathor.version_resource import VersionResource
from tests import unittest
from tests.resources.base_resource import StubSite, _BaseResourceTest
class BaseVersionTest(_BaseResourceTest._ResourceTest):
__test__ = False
def setUp(self):
... |
import time
import os
import numpy as np
from nibabel import trackvis as tv
from dipy.viz import fos
from dipy.io import pickles as pkl
from dipy.core import track_learning as tl
from dipy.core import track_performance as pf
from dipy.core import track_metrics as tm
fname='/home/eg01/Data/PBC/pbc2009icdm/brain1/bra... |
from sympy import symbols, Dij, LeviCivita
x, y = symbols('x,y')
def test_Dij():
assert Dij(1, 1) == 1
assert Dij(1, 2) == 0
assert Dij(x, x) == 1
assert Dij(x**2-y**2, x**2-y**2) == 1
def test_levicivita():
assert LeviCivita(1, 2, 3) == 1
assert LeviCivita(1, 3, 2) == -1
assert LeviCivit... |
import ast
import types
import signal
import ctypes
import ctypes.util
import threading
c_off_t = ctypes.c_int64
from ebml.exceptions import UnexpectedEndOfData
# Imports for compatibility purposes, in case some modules still expect these
# functions to still be here.
from .vint import (detectVintSize, getVintSize,... |
""" Helper module to run HVE scheme
"""
from searchableencryption.hve import util
def run_hve_multiple(hve_quadruple: tuple,
indices: list,
queries: list,
groupParam: dict):
""" Run HVE with multiple indices and queries
:param tuple hve_quadruple... |
import intake
import intake.config
from intake.source.cache import CacheMetadata
import os
import subprocess
from intake.source.tests.util import temp_cache
cpath = os.path.abspath(
os.path.join(os.path.dirname(__file__),
'../../../catalog/tests/catalog_caching.yml'))
def test_help(tmpdir):
o... |
import os
import sys
import colorama
import logging
import urllib.request
logger = logging.getLogger('main')
def start_fix():
import zipfile
import platform
print(f'Copying sqlite3.dll to the current directory: {os.getcwd()} ... ', end='')
work_dir = os.path.dirname(os.path.abspath(__file__))
... |
class Node(object):
__slots__ = ['obj', 'next']
def __init__(self, obj):
self.obj = obj
self.next = None
class LinkedList(object):
__slots__ = ['head', 'tail', 'length']
def __init__(self, *init_list):
self.head = None
self.tail = None
self.length = 0
for obj in init_list:
self.push(obj)
def push(... |
from __future__ import absolute_import, unicode_literals
import datetime
import random
import string
today = datetime.date.today()
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def random_number_generator(size=6, ch... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-26 12:22
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0008_alter_user_username_max_le... |
import sys
import time
import datetime
import argparse
import struct
import math
import serial
import pygame
from pygame.locals import *
sys.path.append('../lib')
import hdlc
SCR_WIDTH = 800
SCR_HEIGHT = 600
black = (0,0,0)
light_gray = (224,224,224)
white = (255,255,255)
red = (255,0,0)
FIX_DIV = 65536.0
VAL_SQR... |
''' mbinary
#########################################################################
# File : rotate.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-05-19 21:54
# Description: three methods of rotating a list
1. 利用 ba=(br)^T(ar)^T... |
from . import register
from django.utils.safestring import mark_safe
from django.conf import settings
from django.template import loader
@register.inclusion_tag("banner.html")
def cookie_banner():
return {}
def render_gtm_template(template_filename, gtm_container_id):
t = loader.get_template(template_filena... |
from behave import given, when, then
@given(u'we have irisvmpy installed')
def step_impl(context):
raise NotImplementedError(u'STEP: Given we have irisvmpy installed')
@when(u'we run program')
def step_impl(context):
raise NotImplementedError(u'STEP: When we run program')
@then(u'<species> will be ... |
"""
Lambda responsible for handling API requests to show the list of batches, or to
show a particular batch.
"""
import json
import botocore
from shared import db
from shared.api_helpers import input_batch_to_human_readable
from shared.constants import BatchMetadataType, BatchStatus
from shared.log import log_request... |
import serial
import time
class WifiInterface():
__debug = True
__serial_interface_port = "/dev/ttyAMA0"
__last_cmd = ''
__wifi_serial = None
# AP
__ap_name = "PiCopter-Wifi"
__ap_password = ""
__ap_channel = 2
__ap_sec = 0
def __init__(self, baud, wifi_mode, server_ip, server_por... |
"""
AxographRawIO
=============
RawIO class for reading AxoGraph files (.axgd, .axgx)
Original author: Jeffrey Gill
Documentation of the AxoGraph file format provided by the developer is
incomplete and in some cases incorrect. The primary sources of official
documentation are found in two out-of-date documents:
... |
import os
import sys
import imageio
import numpy as np
import utils
class VideoRecorder(object):
def __init__(self, view, root_dir, height=256, width=256, fps=60):
self.view = view
self.save_dir = utils.make_dir(root_dir, 'video') if root_dir else None
self.height = height
self.w... |
import ifcb
from ifcb.io.client import Client
from ifcb.io.path import Filesystem
from ifcb.io.stitching import stitch, find_pairs, StitchedBin
import os
import sys
def test_bin(pid):
#client = Client()
client = Filesystem(['../exampleData'])
catch = False
dir = os.path.join('stitch',ifcb.lid(pid))
... |
from plumbum import local
import benchbuild as bb
from benchbuild.environments.domain.declarative import ContainerImage
from benchbuild.source import HTTP
from benchbuild.utils.cmd import cat, make, mkdir, mv, unzip
class Crafty(bb.Project):
""" crafty benchmark """
NAME = 'crafty'
DOMAIN = 'scientific'... |
from Tkinter import *
import tkMessageBox
def doNothing():
print "OK OK I won't"
root = Tk()
canvas = Canvas(root, width = 200, height = 100)
canvas.pack()
blackLine = canvas.create_line(0,0,200,50)
redLine = canvas.create_line(0,100,200,50, fill = 'red')
greenBox = canvas.create_rectangle(25, 25, 130, 60, fill =... |
from flask_restx import Namespace, Resource
from flask import request
from .view import TradeView
trade = Namespace('trade', path='/trades')
view = TradeView()
@trade.route('')
class TradeList(Resource):
@trade.doc('get trade list')
def get(self):
'''List all trades'''
return v... |
# ref: https://github.com/xianchen2/Text_Retrieval_BM25/blob/master/document_retrieval.ipynb
import pickle
import re
from nltk.stem import PorterStemmer
import os
from .documentParser import DocumentParser
class LocalBM25:
b = 0.75
k = 1.2
def __init__(self):
# some prepartion
self.refDoc... |
# Imports here
from torchvision import transforms, models
import torch
from PIL import Image
import json
import argparse
def load_model(model_path , checkpoint = False):
load_point = torch.load(model_path)
if checkpoint == True: # Loading the checkpoint
if load_point['name'] == 'vgg19':
... |
import requests
import json
se = requests.session()
def register_test():
register_info = json.dumps({'phone_number': '18798318100', 'username': 'skil', 'password': '123456'})
r = requests.post('http://127.0.0.1:5000/register', data=register_info)
print(r.text)
def login_test():
login_info = json.dump... |
import json
import pytest
from podle.views import NewsletterWebhook
pytestmark = pytest.mark.django_db()
class TestNewsletterWebhook:
def test_post_works(self, newsletter, request_builder):
# GIVEN
assert not newsletter.audio_url
filename = "tests/fixtures/webhook.json"
with open... |
#!/usr/bin/env python3
import json
import time
import os
import shutil
import numpy as np
from coco_helper import (load_preprocessed_batch, image_filenames, original_w_h,
class_labels, num_classes, bg_class_offset, class_map,
MODEL_DATA_LAYOUT, MODEL_COLOURS_BGR, MODEL_INPUT_DATA_TYPE, MODEL_DATA_TYPE, MODEL_... |
import string
def MOS_ASYMPTOTE(
states,
bandgap=None,
title="Title",
draw_band=False,
draw_occupation=False,
draw_energy=False
):
"""
:states: TODO
:returns: TODO
"""
energies = "{"
spins = "{"
occupations = "{"
bands ... |
"""
@author: Badita Marin-Georgian
@email: geo.badita@gmail.com
@date: 29.03.2020 20:58
"""
import numpy as np
from env_interpretation.state_utils import get_state_from_observation
from env_interpretation.utils import n_from_prod
def test_env_3(env3_robots):
env_data = env3_robots.get_env_metadata... |
from knowledgerepr import fieldnetwork
from ontomatch import glove_api
from nltk.corpus import stopwords
import numpy as np
import pickle
import itertools
import operator
from ontomatch import javarandom
from dataanalysis import nlp_utils as nlp
from nltk.corpus import stopwords
# minhash variables
k = 512
mersenne_pr... |
import pytest
from tabulation import SNIa, Lifetimes, IMF
from scipy import integrate
imf = IMF("Kroupa", 0.1, 50)
lifetimes = Lifetimes("Raiteri_96")
number_sn_ia = 1.6E-3
@pytest.fixture
def sn_ia_old():
return SNIa("old ART", "Nomoto_18", lifetimes, imf,
exploding_fraction=0.015, min_mass=3, ... |
from output.models.ms_data.regex.bopomofo_xsd.bopomofo import Doc
__all__ = [
"Doc",
]
|
#!usr/bin/env/ python
# -*- coding: utf-8 -*-
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField, \
HiddenField, RadioField, FileField, SubmitField, IntegerField
from wtforms.validators import DataRequired, Length, Email, Regexp
from . import models
class... |
import six
import django
from django.db import models
from django.db.models import F, Max, Min
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext, ugettext_lazy as _
try:
from django.db.transaction import atomic
except ImportError:
from django.db.transacti... |
import json
import os
import sys
import unittest
from bs4 import BeautifulSoup
from bs4.element import NavigableString
from hocr_parser import parser
if sys.version_info < (3, 0):
from io import open
class BaseTestClass(unittest.TestCase):
"""Super class for all test cases"""
@classmethod
def setup_... |
from django.apps import AppConfig
class WallpaperConfig(AppConfig):
name = 'wallpaper'
|
class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
return
self.m=m=matrix
self.maxi=len(m)
self.maxj=len(m[0])
self.BIT=[[0 for _ in range(s... |
# Copyright 2015 Intel Corp.
#
# 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... |
import pygplates
import numpy as np
import geopandas as gpd
from shapely.geometry import LineString, Polygon
from .sphere import healpix_mesh
import os, tempfile
def create_gpml_crustal_thickness(longitude_array,latitude_array,thickness,filename=None):
multi_point = pygplates.MultiPointOnSphere(zip(latitude_arra... |
from django.urls import path
from homework.views import presentation_views as views
urlpatterns = [
path("", views.get_presentations, name="presentations"),
path("add/", views.add_presentation, name="presentation-add"),
path("upload/", views.upload_image, name="image-upload"),
path("<str:pk>/update/",... |
import torch
from torch.utils._pytree import tree_map
from functools import partial
from torch.fx.operator_schemas import normalize_function
from torch.utils._mode_utils import no_dispatch
from torch._subclasses.meta_utils import MetaConverter
from typing import Union
from torch._ops import OpOverload
from torch.utils... |
# Generated from grammar/Java8Parser.g4 by ANTLR 4.7.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .Java8Parser import Java8Parser
else:
from gras.file_dependency.java.grammar_v8.Java8Parser import Java8Parser
# This class defines a complete generic visitor for a parse tree produce... |
#
# Created on Mon Jun 14 2021
#
# The MIT License (MIT)
# Copyright (c) 2021 Vishnu Suresh
#
# 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... |
import requests
from . import config
URL_OPEN_STREET_MAPS = 'https://nominatim.openstreetmap.org'
URL_TELIZE = 'https://www.telize.com'
URL_FORECAST = 'https://api.forecast.io/forecast/{}/{},{}?units=si'
def fetch_city_coords(city):
url = '{}{}'.format(URL_OPEN_STREET_MAPS, '/search')
r = requests.get(url,... |
from typing import Optional, Any, TypeVar, Type, BinaryIO
from types import GeneratorType
from remerkleable.tree import Node, RootNode, Root, subtree_fill_to_contents, get_depth, to_gindex, \
subtree_fill_to_length, Gindex, PairNode
from remerkleable.core import View, ViewHook, zero_node, FixedByteLengthViewHelper,... |
from format_input_string import main as format_input_string
def test_input_output_pair(input_str, output_str):
assert format_input_string(input_str) == output_str
print(f"Check OK: formatted '{input_str}' = '{output_str}'")
def main(input_output_pairs):
assert type(input_output_pairs) == list, f"Input s... |
from __future__ import division
from datetime import datetime
def timestamp_from_dt(dt, epoch=datetime(1970, 1, 1)):
"""
Convert a datetime to a timestamp.
https://stackoverflow.com/a/8778548/141395
"""
delta = dt - epoch
# return delta.total_seconds()
return delta.seconds + delta.days * 8... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from flask import Flask
import confusionflow
from confusionflow.server.blueprints import api, web
from confusionflow.utils import check_folderpath, get_logdir_from_env
def create_app(logdir=None):... |
from djongo import models
from inventory_item.models import Item, ItemFields
from audit_template.models import AuditTemplate
USER_MODEL = 'user_account.CustomUser'
PENDING = 'Pending'
COMPLETE = 'Complete'
class Audit(models.Model):
audit_id = models.AutoField(primary_key=True)
organization = models.Foreign... |
# -*- coding: utf-8 -*-
import numpy as np
import cv2
# 1、整个条形码的算法流程如下:
# 2、计算x方向和y方向上的Scharr梯度幅值表示
# 3、将x-gradient减去y-gradient来显示条形码区域
# 4、模糊并二值化图像
# 5、对二值化图像应用闭运算内核
# 6、进行系列的腐蚀、膨胀
# 7、找到图像中的最大轮廓,大概便是条形码
# 注:该方法做了关于图像梯度表示的假设,因此只对水平条形码有效。
def detect_bar(image):
# 读入图片并灰度化
gray = cv2.cvtColor(image, cv2.COLOR_... |
print("GUESSING GAME")
#terminal based number guessing game having 1/6 of wining probability. This one is the hard level.
while(True):
x= str(input("Shall we start the game: \n"))
y=x.lower()
import random
n= random.randint(1,30)
if y=="yes":
name = str(input("Enter your name:"))
pr... |
"""Project loader for reading BUILD and BUILD.conf files."""
import importlib
import sys
import traceback
import cobble.env
def load(root, build_dir):
"""Loads a Project, given the paths to the project root and build output
directory."""
# Create a key registry initialized with keys defined internally t... |
import json, shutil
def run(json_path, train_json_path, test_json_path):
with open("/home/jitesh/jg/openimages-personcar-localize_and_classify/trainval/annotations/bbox-annotations_val.json", 'rt', encoding='UTF-8') as annotations:
data = json.load(annotations)
count = 0
for image in data["im... |
import re
from livestreamer.compat import urlparse
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import RTMPStream
AJAX_HEADERS = {
"Referer": "http://www.filmon.com",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0"
}
C... |
""" OpenMDAO class definition for ParamComp"""
import collections
from six import string_types
from openmdao.core.component import Component
class ParamComp(Component):
"""A Component that provides an output to connect to a parameter."""
def __init__(self, name, val=None, **kwargs):
super(ParamComp... |
from werkzeug.exceptions import HTTPException
from flask_script import Manager, Server
from app import create_app
from app.common.libs.error import APIException
from app.common.libs.error_code import ServerError
from app.common.libs.response_code import Const
app = create_app()
manager = Manager(app)
ma... |
""" ./examples/label/suite/custom_suite.rst """
from hamcrest import assert_that
from allure_commons_test.report import has_test_case
from allure_commons_test.label import has_suite, has_parent_suite, has_sub_suite
def test_custom_suite(executed_docstring_path):
assert_that(executed_docstring_path.allure_report,... |
import os
import shutil
root_folder = "audio"
all_audio_files = os.listdir(root_folder)
def subject_wise(all_files):
for f in all_files:
sub_id = f.split("_")[0]
sub_folder = f"vadtestsubject_{sub_id}"
audio_fpath = os.path.join(root_folder, f)
if not os.path.exists(sub_folder): o... |
#!/usr/bin/env python3
"""Socket Perf Test.
"""
import argparse
import sys
from pathlib import Path
sys.path.append(str(Path(".").parent.absolute().joinpath("tacview_client")))
from tacview_client import serve_file # type: ignore
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argum... |
from .kd import KDDistiller
from .hint import *
from .attention import AttentionDistiller
from .nst import NSTDistiller
from .sp import SPDistiller
from .rkd import RKDDistiller
from .pkt import PKTDistiller
from .svd import SVDDistiller
from .cc import *
from .vid import *
from . import data_free |
import sys
import itertools
from math import sqrt
from operator import add
from os.path import join, isfile, dirname
import numpy as np
from pyspark import SparkConf, SparkContext
from pyspark.mllib.recommendation import ALS
from pyspark.mllib.clustering import KMeans, KMeansModel
def parseRating(line):
"""
P... |
"""Create managedojects_schemas table
Revision ID: e83c5549560c
Revises: 0b7905a9ba5b
Create Date: 2018-02-03 23:20:13.704000
"""
from alembic import op
import sqlalchemy as sa
import datetime
# revision identifiers, used by Alembic.
revision = 'e83c5549560c'
down_revision = '0b7905a9ba5b'
branch_labels = None
depen... |
import importlib
import numpy as np
from supersuit import dtype_v0
# TODO: We will eventually want to provide visualization support for the MPE, but not needed yet
def petting_zoo_mpe(env_config, spec_only=False):
env_config = env_config.copy()
env_name = env_config.pop("scenario")
# Load appropriate Pet... |
from flask import session, abort, flash, url_for, make_response, request, \
render_template, redirect, g, jsonify
from sqlalchemy.exc import IntegrityError
from flask.ext.login import login_user, logout_user, login_required, \
current_user
import uuid
import json
from models import Hunt, Participant, Item, Ad... |
# Undergraduate Student: Arturo Burgos
# Professor: João Rodrigo Andrade
# Federal University of Uberlândia - UFU, Fluid Mechanics Laboratory - MFLab, Block 5P, Uberlândia, MG, Brazil
# Fourth exercise: Solving a Linear System --> ax = b
# Here I first set conditions
import numpy as np
from numpy import linalg as L... |
n1 = float(input("Quantos reais você tem? R$"))
print("R$",n1,"reais")
d = n1*5.15
print("{} reais dá para comprar {:.2f} dolares".format(n1, d)) |
# Generated by Django 2.2 on 2019-04-24 20:41
from django.db import migrations
def create_initial_products(apps, schema_editor):
Product = apps.get_model('catalog', 'Product')
Product(name='Salame', description='Salame Toscano', price=12).save()
Product(name='Olio Balsamico',
description='Oli... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-09-07 11:35
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('markets', '0019_auto_20160907_1129'),
]
operations = [
migrations.AlterField... |
from discord import ButtonStyle, Interaction, SelectOption, ui
from utils import BlooContext
class Select(ui.Select):
def __init__(self, versions):
super().__init__(custom_id="Some identifier", placeholder="Select a version...", min_values=1, max_values=1,
options=[SelectOption(la... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 10 12:41:42 2019
@author: Chaobo
"""
import tensorflow as tf
import numpy as np
import os
import cv2
import yolo.config as cfg
import time
import pickle as cPickle
import skimage.draw
from yolo.yolo3_net_pos import YOLONet
from utils.voc_eval_mask import ... |
# *args and **kwargs tutorial
# *vars and **kvars tutorial
def function_1(name, age, rollno):
print("This name of the student is ", name,
"and age is ", age, "and rollno is ", rollno)
function_1("Mahi", 22, 4532)
def argsfunction(*args):
if (len(args)==2):
print("This name of the student is ", a... |
class AsupContentType(basestring):
"""
Type of AutoSupport content
Possible values:
<ul>
<li> "basic" - ASUP will contain minimal set of
data for this subsystem,
<li> "troubleshooting" - ASUP will contain detailed
collection of data for this subsystem
</ul>
"""
... |
from cryptography import fernet
from cryptography.fernet import Fernet
message = input("Enter text to be encrpyted: ")
key = Fernet.generate_key()
fernet = Fernet(key)
enrpt_message = fernet.encrypt(message.encode())
print(enrpt_message)
decrpt_message = fernet.decrypt(enrpt_message).decode()
print(decrpt_message... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2016-11-29 10:11:27
# @Author : Arms (526923945@qq.com)
# @Link : https://armszhou.github.io
# @Version : $Id$
import os
# 标识符与关键字
# 引导字符 + 后续字符
# 引导字符:字母、下划线(_)或大多数非英文语言字母
# 后续字符:任意非空字符
# 标识符是大小写敏感的
# 整型
# 二进制 0b 或者 0B
# 八进制 0o 或者 0O
# 十六进制 0x 或者 ... |
import argparse
import numpy as np
import pickle
from gen_mem import gen_mem
# train code from http://iamtrask.github.io/2015/07/12/basic-python-network/
# sigmoid function
def sigmoid(x,deriv=False):
if(deriv==True):
return x*(1-x)
return 1/(1+np.exp(-x))
def relu(X):
map_func = np.vectorize(lam... |
import argparse
import pathlib
import json
def parse_args():
"""Argument parsing function
:return: namespace containing user provided arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(
description="Setup a directory from a template."
)
parser.add_argument(d... |
from dataclasses import dataclass
import glob
import os
import re
from pele_platform.Utilities.Parameters import parameters
from pele_platform.Utilities.Helpers import helpers
from pele_platform.Adaptive import simulation
from pele_platform.analysis import analysis
from frag_pele.Covalent import pdb_corrector
@data... |
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import collections
import os
import platform
import sys # noqa
from concurrent.futures import ProcessPoolExecutor
from decimal import Decimal
from textwrap import dedent
import pytest
from path import Path
from pytablewriter import dumps_tableda... |
#!/usr/bin/env python
import rospy, cv2, cv_bridge, numpy
from tf.transformations import decompose_matrix, euler_from_quaternion
from sensor_msgs.msg import Image
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from ros_numpy import numpify
import numpy as np
from kobuki_msgs.msg import Led
from ... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
# List of contributors:
# Jordi Esteve <jesteve@zikzakmedia.com>
# Ignacio Ibeas <ignacio@acysos.com>
# Dpto. Consultoría Grupo Opentia <consultoria@opentia.es>
# Pedro M. Baeza <pedro.baeza@tecnativa.com>
# Carlos Liéba... |
from typing import List, Optional
from pydantic import *
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from app.schemas.reservation import (
HospReservationCreate,
ShopReservationCreate,
ShopReservationUpdate,
)
from app.models.reservation import HospReservation, ShopReser... |
print("I'm spam")
def hello(name):
print('Hello %s' % name)
|
import random
import time
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
# Create your views here.
from app.models import UserModel
from userauth.models import UserLogin
def login(request):
if r... |
from asyncio import sleep
from typing import List
from cozmo.objects import EvtObjectTapped
from cozmo.objects import LightCubeIDs
from .cube import NoteCubes
from .cube_mat import CubeMat
from .song_robot import SongRobot
from .sound_effects import play_collect_point_sound
class OptionPrompter:
"""A class to h... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-08-12 19:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('history', '0002_auto_20160811_1946'),
]
operations = [
migrations.AlterField... |
"""
__name__ = accuracy.py
__author__ = Yash Patel
__description__ = Visualizes the output dumps provided by gem5, specifically
focusing on the differences in accuracy resulting from running the various
branch predictors, i.e. accuracy relative to the same input programs. Also
highlights the latency/time in prediction
... |
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
# 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... |
import os
import numpy as np
import tensorflow as tf
from PIL import Image, ImageDraw
from sklearn.neighbors import NearestNeighbors
from settings import FILES_DIR, VGG_19_CHECKPOINT_FILENAME, VGG_19_CODE_LAYER, IMAGE_DATASET_PATH, IMAGE_SIZE
from vgg import vgg_19
from prepare import rescale_image
def get_images_c... |
import random
import re
from datetime import datetime
import types
import enum
from inspect import signature
from .scenario import *
def _if_dict(new_answer, nosleep=False):
if not 'message' in new_answer:
new_answer['message'] = ''
if not 'sleep' in new_answer:
if nosleep:
new_ans... |
from eggdriver.news.app import *
from eggdriver.news.config import *
from eggdriver.news.news import * |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.