content stringlengths 5 1.05M |
|---|
import os.path
import hashlib
from random import SystemRandom
from string import ascii_letters, digits
from datetime import datetime
class Error(Exception):
pass
class SizeError(Error): # Criação de Erro para o tamanho da senha
def __init__(self, message):
self.message = message
def salva_senha(s... |
from threading import Thread
import time
""" 多线程中使用全局变量 """
# 注意线程与进程不同的是,多线程间是可以共享全局变量的
g_num = 100
def work1():
global g_num
for i in range(3):
g_num += 1
print('--- in work1, g_num is %d ---' % g_num)
def work2():
global g_num
print('--- in work2, g_num is %d ---' % g_num)
print('-... |
print("dev_demo")
def test_main():
<<<<<<< HEAD
print("main 分支")
=======
print("dev 分支")
>>>>>>> dev
|
from ..mig.python import ReactBase
from ..mig.python.ReactConst import ReactConst
MAX_PAYLOAD = ReactConst.MAX_REACT_PAYLOAD
class Msg(ReactBase.Msg):
global __HLEN
__HLEN = ReactBase.Msg().offset_payload_start_byte()
def __init__(self, data=chr(0)*__HLEN,
addr=None, gid=None, base_offse... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = "core/index.html"
class AboutView(TemplateView):
template_name = "core/about.html"
class BlogView(TemplateView):
template_name = "core/blog.html"
... |
import json
from django.contrib import messages
from django.db.models import Q
from django.utils.crypto import get_random_string
from ..models import MediaCard, Settings, TorrentClient, TorrentTracker
from ..plugin_manager import dw_torrent_aio, dpt, get_m_cards_to_urls
def message_or_print(request, commands, text,... |
from google.cloud import texttospeech
#from google.cloud import exceptions
print("Hello")
###############################################################################
# Developer: Abdullah Najjar
# Description: Read 3 books from text files provided from an open source project,
# then, allows Google API to read th... |
#!/usr/bin/python3
with open('input.txt') as f:
input = f.read().splitlines()
def check_slope(x_inc, y_inc):
x = 0
y = 0
target = len(input)
trees = 0
while y < target:
if input[y][x] == '#':
trees += 1
x += x_inc
x %= len(input[0])
y += y_inc
return trees
m = 1
for x in range(1,... |
import pandas as pd
import numpy as np
from sklearn import model_selection,preprocessing
import RN_Perceptron as rn
datos = pd.read_csv('../Datos/Drug5.csv')
#-- ordinales a numericos ---
mapeo = {'Sex': {'F':1, 'M':0},
'BP':{'HIGH':2, 'NORMAL':1, 'LOW':0},
'Cholesterol':{'NORMAL':... |
""" Run part of speech tagger on a document collection and for every distinct word,
output the distribution of the part of speech tags """
import spacy
import plac
import logging
import numpy as np
import os
MAX_LENGTH = 100000
nlp = spacy.load('en_core_web_sm')
nlp.max_length = MAX_LENGTH
logging.basicConfig (format... |
import time, random
import numpy as np
from absl import app, flags, logging
from absl.flags import FLAGS
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from yolov3_tf2.models import (
YoloV3, YoloV3Tiny
)
from yolov3_tf2.dataset import transform_images
from yolov3_tf2.utils import draw_outputs, ... |
import os, sys, glob
testdir = sys.argv[1]
forcegen = len(sys.argv) > 2
testpatt = os.path.join(testdir, 'tests', '*.py')
testfiles = glob.glob(testpatt)
testfiles.sort()
for test in testfiles:
infile = os.path.basename(test).replace('.py', '.in')
inpath = os.path.join(testdir, 'inputs', infile)
outfile ... |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @File : run.py
# @Created : 2020/10/29 3:30 下午
# @Software : PyCharm
#
# @Author : Liu.Qi
# @Contact : liuqi_0725@aliyun.com
#
# @Desc : 启动类
# -------------------------------------------------------... |
import http
from flask import Blueprint
root_blueprint = Blueprint("root", __name__, url_prefix="/")
@root_blueprint.route("/", methods=["GET"])
@root_blueprint.route("/index", methods=["GET"])
def index():
return "Hello, World!", http.HTTPStatus.OK
|
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
import unittest
from . import *
if __name__ == "__main__":
unittest.main()
|
from .API import API |
x = 1
x = 'Hello Joe'
print(x + '!') # OK
print(x + 2) # During runtime, we get `TypeError: must be str, not int`.
|
from py_cron_expression.py_cron import CronJobExpression
__all__ = ["CronJobExpression"]
|
import re
from functools import partial
from typing import Any, Dict, Optional
from inspect import signature
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
f... |
# Script Name : dir_test.py
# Author : Craig Richards
# Created : 29th November 2011
# Last Modified :
# Version : 1.0
# Modifications :
# Description : Tests to see if the directory testdir exists, if not it will create the directory for you
from __future__ import print_function
from code1.color_print imp... |
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
import subprocess
from domain.persistable import User
# 表单
@csrf_exempt
def login_form(request):
return render_to_response('login.html')
# 接收请求的登录数据
@csrf_exempt
def login(request):
reques... |
import json
import os
import numpy as np
import scipy as sp
import pandas as pd
from pandas.tools.plotting import scatter_matrix
import seaborn as sns
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.inset_locator import inset_axes
import ast
import cPickle as pickle
for i in range(1,21):
temp = []
... |
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
#import pdb; pdb.set_trace()
def wordMultiply(word):
for count in range(4):
print word
if __name__ == "__main__":
wordMultiply("happy")
|
from chips.api.api import Stimulus, Response, Input, Output, Chip
from fpga_tx.build_tools import build_vivado
from fpga_tx.download_tools import vivado
import fpga_tx.flash_tools
build_tool = build_vivado
download_tool = vivado
flash_tool = fpga_tx.flash_tools.vivado
device = "XC7A15T-CPG236-1"
flash = "n25q32-3.3v-... |
import falcon
class CompaniesResource(object):
companies =[{"id":1,"name":"Company One"},{"id":2,"name":"Company Two"}]
def on_get(self,req,resp):
"""this is request -response cycle from browser to flask dev server"""
resp.body = json.dumps(self.companies)
api = falcon.API()
companies_endp... |
from tensorflow.keras.models import load_model
## Import custom functions and configuration
from loader import get_from_pickle, ConfigLoader
## Here import your model and functions for pre-processing
from model import compile_get_model
def main():
EVALUATE_CONFIG = 'config.json'
config = ConfigLoader(EVALUATE_C... |
import pathlib
import random
import discord
from discord.ext import commands
import yaml
from bot.bot import Bot
FORM_URL = "https://forms.gle/sb2jNbvVcTorNPTX6"
with pathlib.Path("bot/resources/fun/starters.yaml").open("r", encoding="utf8") as f:
STARTERS = yaml.load(f, Loader=yaml.FullLoader)
class Conversa... |
# Author: Karl Gemayel
# Created: 6/29/20, 3:41 PM
import logging
import os
from textwrap import wrap
import seaborn
import argparse
import numpy as np
import pandas as pd
from typing import *
from functools import reduce
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
# noinspection All
... |
import hashlib
from lxml import etree
import subprocess as sub
import numpy as np
def evaluate_population(pop, record_history=False):
seed = pop.seed
# clear old .vxd robot files from the data directory
sub.call("rm data{}/*.vxd".format(seed), shell=True)
# remove old sim output.xml if we are savin... |
# -*- coding: utf-8 -*-
"""
Model Map table csv_shp_output_fields
:author: Sergio Aparicio Vegas
:version: 0.1
:date: 28 sept. 2017
"""
__docformat__ = "restructuredtext"
class CsvShpOutputFields():
""" DB Entity csv_shp_output_fields to Python object CsvShpOutputFields """
def __init__(s... |
from .cell import Cell, CellType
from .pawn import Attacker, Defender, King
from enum import Enum
class GameStatus(Enum):
IN_PROGRESS = 1
DEFENDER_WON = 2
ATTACKER_WON = 3
DRAW = 4
class Game:
"""Class managing the logic of the game.
Constructed from 2 players with default size... |
#!/usr/bin/env python
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import azure.functions as func
from onefuzztypes.enums import ErrorCode
from onefuzztypes.models import Error
from onefuzztypes.requests import NodeGet, NodeSearch, NodeUpdate
from onefuzztypes.responses import BoolResult
... |
import os
import atexit
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from audcon import configuration
from gpm import logging
app = Flask(__name__)
app.config.from_object(configuration.cfg)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
log = logging.Log(script=os... |
#!/usr/bin/python
#
# Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... |
import requests
import common_data
from signature import Signature
import logging, sys
# set url
url = common_data.mycloud_url
# url = "http://127.0.0.1:8888"
path = "/d/oauth/authorize"
def get_device_authentication_token():
headers = dict()
headers = init_headers(headers)
body_content = dict()
ini... |
from flask import Flask
app = Flask(__name__)
def load_binary(file):
with open(file, 'rb') as file:
return file.read()
@app.route('/createt-shirt')
def generatet_shirt():
resp = Flask.make_response(app, load_binary("logo-eina.png"))
resp.headers['Content-Type'] = 'image/png'
return resp
if ... |
#!/usr/bin/python3
import numpy as np
import re
import sys
import multiprocessing as mp
# import threading
# import queue
from time import sleep
argvs = sys.argv
stop_reading = False
class SpikeData:
def __init__(self, no, pc, inst, mnemonic):
self.no = no
self.pc = pc
self.inst = inst
self.mnemon... |
from office365.runtime.client_object_collection import ClientObjectCollection
class BaseEntityCollection(ClientObjectCollection):
"""Represents a collection of View resources."""
def __init__(self, context, child_item_type=None, resource_path=None, parent=None):
"""
SharePoint entity set
... |
import jieba
from gensim.models import Word2Vec, KeyedVectors
import logging
import re
logging.basicConfig(level=logging.INFO)
def get_corpus(args):
data_dir = args['data_dir']
corpus = []
sentence_delimiters = re.compile(u'[。\.、::;;,,"(),“”?//><@]')
with open(data_dir, "r") as f:
for line in ... |
from django.shortcuts import render
from rest_framework.views import APIView, Response
from .serializers import *
from rest_framework import generics
class WarriorAPIView(APIView):
def get(self, request):
warriors = Warrior.objects.all()
serializer = WarriorSerializer(warriors, many=True)
... |
import numpy as np
def error_rate(model_ts, obs_ts, dg):
"""Calculate the error rate.
Error rate is calculated as the percentage of model
annual means that fall within the observed range.
:param model_ts (numpy.ndarray): a 2-D array of annual mean
time series for a given variable in... |
# Guess
# Import the random module.
# Store a random secret number in a variable
# called secret_number (use randrange or randint).
# The secret number should be from 1 to 20 (inclusive).
# Ask the user to keep guessing the number until they
# get it right. (You might want to print messages
# to tell the user if they g... |
import pkg_resources
from .dataframe import DataFrame
from .series import Series, ViewSeries
__version__ = pkg_resources.get_distribution('raccoon').version
__all__ = ['DataFrame', 'Series', 'ViewSeries']
|
import pymongo
import pytest
from moncoll import Moncoll
settings = {"user": "testuser", "password": "testpass", "dbname": "db_test"}
coll_name = "test_collection"
def test_insert_and_find():
coll = Moncoll(settings, coll_name)
coll.insert_one({"_id": 123})
coll.insert_one({"_id": 456})
res = coll.fi... |
"""Top-level package for docs_parser."""
__author__ = """Robert Kumar"""
__email__ = 'robert2398@gmail.com'
__version__ = '0.1.0'
|
from plexserver import PlexFrame
import tkinter as tk
from PIL import Image, ImageTk
def load_images():
d = {}
d['play'] = ImageTk.PhotoImage(Image.open("images/play.png").resize((24, 24), Image.ANTIALIAS))
d['forward'] = ImageTk.PhotoImage(Image.open("images/backward.png").resize((24, 24), Image.ANTIALIAS... |
#!/usr/bin/python
import sqlite3
import threading
connlock = threading.RLock()
conn = sqlite3.connect("reader.db")
cursor = conn.cursor()
def lock():
connlock.acquire()
def unlock():
connlock.release()
cursor.execute("select count(*) from sqlite_master where type='table' and name='configuration'")
conf_exis... |
"""
Automatically extract best config and epoch and retrain the model on both train + val sets
"""
import os
import subprocess
import re
import argparse
from hyperparam_checking import find_best_config_hyperparam_tune, find_best_perf
def retrain(hyperparam_tune_path, save_path, all_model_types=[], all_lambdas=[], sho... |
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponseRedirect
from sgcommapp.models import *
from django.template import RequestContext
from django.shortcuts import render
from django.views.generic import View... |
"""
Word Chain 2.0
Let's update our previous word-chain definition. In this 2.0 version, a word-chain is an array of words, where the next word is formed by either:
Changing exactly one letter from the previous word
Adding or subtracting one letter
Note: You can only do one (not both) for each word change.
Examples
i... |
import time
from machine import Pin, I2C
from servo import Servos
#i2c = I2C(sda=Pin(21), scl=Pin(22)) # moxing esp32
#i2c = I2C(sda=Pin('PB6'), scl=Pin('PB7')) # stm32f411eu on WeAct board,software i2c,does not work now!!!
i2c = I2C(1, freq=400000) # create hardware I2c object: I... |
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Nipype : Neuroimaging in Python pipelines and interfaces package.
Nipype intends to create python interfaces to other neuroimaging
packages and create an API for specifying a full ... |
class DetectionCollater:
def __init__(self):
pass
def next(self, data):
images = [s['image'] for s in data]
annots = [s['annots'] for s in data]
scales = [s['scale'] for s in data]
origin_hws = [s['origin_hw'] for s in data]
max_h = max(image.shape[0] ... |
# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from django.views import View
from explorer.models import Query
from explorer.views.auth import PermissionRequiredMixin
from explorer.views.export import _export
class StreamQueryView(PermissionRequiredMixin, View):
permission_required = 'vi... |
from problem_2.problem_2_SVM import problem_2_SVM
from problem_2.problem_2_DNN import problem_2_DNN
# Problem 2 SVM
problem_2_SVM()
# Problem 2 DNN
problem_2_DNN()
|
from dataclasses import dataclass
from typing import List
from encord.project_ontology.classification_attribute import ClassificationAttribute
@dataclass
class OntologyClassification:
"""
A dataclass which holds classifications of the :class:`.Ontology`.
"""
#: A unique (to the ontology) identifier ... |
# -*- coding:UTF-8 -*-
'''
Created on 2014年12月5日
@author: caifh
'''
import unittest
import creditutils.str_util as utils
import chardet
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testName(self):
pass
def test_escape():
a = '123我们'
... |
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata frita')
# cont = len(lanche)
# print(cont)
#Dessa forma é possível mostrar a posição
for cont in range(0, len(lanche)):
print('Eu vou comer {}.'.format(lanche[cont]))
print('Comi muito!') |
import config
import re
def get_subsystem_in_title_info(title):
subsystems = config.get_subsystems()
for subsystem in subsystems:
index = title.lower().find(subsystem.lower())
if index != -1:
opening = '<span class="text-info">'
closing = '</span>'
new_tit... |
from django.db import models
from swap_in.users.models import User
class Match(models.Model):
user_like = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=False,
related_name="user_likes"
)
user_clothe = models.ForeignKey(
User,
on_delete=models.CASCAD... |
# Copyright 2019 Google LLC
#
# 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, s... |
# -*- coding: utf-8 -*-
import numpy as np
import statsmodels as sm
from ThymeBoost.trend_models.trend_base_class import TrendBaseModel
from pmdarima.arima import auto_arima
class ArimaModel(TrendBaseModel):
"""ARIMA Model from Statsmodels"""
model = 'arima'
def __init__(self):
self.model_params =... |
import argparse
import copy
import json
import pickle
import pprint
import os
import sys
from tqdm import tqdm
from typing import *
from my_pybullet_envs import utils
import numpy as np
import torch
import my_pybullet_envs
import pybullet as p
import time
import inspect
from NLP_module import NLPmod
from my_pybullet... |
import vg
from .._common.shape import check_shape_any
def project_to_line(points, reference_points_of_lines, vectors_along_lines):
k = check_shape_any(points, (3,), (-1, 3), name="points")
check_shape_any(
reference_points_of_lines,
(3,),
(-1 if k is None else k, 3),
name="refe... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 21 16:18:07 2022
@author: amasilva
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import glob
class DuneEvolution:
def __init__(self, **kwargs):
self.filename =[]
self.parameter ='h'
... |
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
import sys
import miscTCGA
import tsvIO
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
NA_VALUE = -999999
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def updateDi... |
import logging
from django.core.management.base import LabelCommand
from corehq.apps.accounting.models import Currency
from corehq.messaging.smsbackends.twilio.models import TwilioBackend
from corehq.apps.sms.models import INCOMING
from corehq.apps.smsbillables.models import SmsGatewayFee, SmsGatewayFeeCriteria
logg... |
"""Teams view."""
import json
from auvsi_suas.models.mission_clock_event import MissionClockEvent
from auvsi_suas.models.uas_telemetry import UasTelemetry
from auvsi_suas.models.takeoff_or_landing_event import TakeoffOrLandingEvent
from auvsi_suas.views import logger
from auvsi_suas.views.decorators import require_supe... |
# -----------------------------------------------------------------------------
# Copyright (C) 2019-2020 The python-ndn authors
#
# This file is part of python-ndn.
#
# 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 ... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
gdalcalc.py
---------------------
Date : Janaury 2015
Copyright : (C) 2015 by Giovanni Manghi
Email : giovanni dot manghi at naturalgis dot pt
**********... |
import os
import stat
from shutil import rmtree
from subprocess import check_call
def resolve_path(rel_path):
return os.path.abspath(os.path.join(os.path.dirname(__file__), rel_path))
def rmtree_silent(root):
def remove_readonly_handler(fn, root, excinfo):
if fn is os.rmdir:
if os.path.isd... |
# coding: utf8
{
'Tamil': 'தமிழ்',
}
|
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets
def clear_layout(layout):
for i in reversed(range(layout.count())):
item = layout.itemAt(i)
if isinstance(item, QtWidgets.QSpacerItem):
layout.removeItem(item)
if isinstance(item, QtWidgets.QWidgetItem):
item.widget(... |
# Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
import unittest
import numpy as np
from numpy.testing import assert_equal
import graspologic.subgraph as sg
class TestEstimateSubgraph(unittest.TestCase):
def test_estimate_subgraph_coh(self):
ys = np.array([0, 1,... |
# SPDX-FileCopyrightText: 2021 easyDiffraction contributors <support@easydiffraction.org>
# SPDX-License-Identifier: BSD-3-Clause
# © 2021 Contributors to the easyDiffraction project <https://github.com/easyScience/easyDiffractionApp>
__author__ = "github.com/AndrewSazonov"
__version__ = '0.0.1'
import os, sys
import... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class GetAcc... |
# Copyright 2021 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://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
import shutil
import tempfile
import os
import artm
def test_func():
# constants
num_tokens = 15
parent_level_weight = 1
num_collection_passes = 15
num_document_passes = 10
num_topics_level0 = 15
num_topics_level1 = 50
regularizer_tau = 10 ** 5
vocab_size = 6906
num_docs = 3430... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import sys
from telemetry.core import util
from telemetry.page import block_page_measurement_results
from telemetry.page import bu... |
import glob
import os
import pika
from pymongo import MongoClient
from ConfigParser import ConfigParser
def make_coll(db_auth, db_user, db_pass, mongo_server_ip='127.0.0.1'):
"""
Function to establish a connection to a local MonoDB instance.
Parameters
----------
coll_name: String.
... |
from __future__ import print_function, division
import os
from ..hdf5 import dendro_import_hdf5
DATA = os.path.join(os.path.dirname(__file__), 'data')
def test_import_old():
# Check that we are backward-compatible
dendro_import_hdf5(os.path.join(DATA, 'dendro_old.hdf5'))
def test_import():
dendro_impo... |
# -*- coding: UTF-8 -*-
# File: concurrency.py
# Author: Yuxin Wu <ppwwyyxx@gmail.com>
# Credit belongs to Xinyu Zhou
import threading
import multiprocessing
import atexit
import bisect
from contextlib import contextmanager
import signal
import weakref
import six
if six.PY2:
import subprocess32 as subprocess
else:... |
class POI:
def __init__(self, google_places_id, name, latitude, longitude, weight_determining_type, weight = -1):
self.google_places_id = google_places_id
self.name = name
self.latitude = latitude
self.longitude = longitude
self.type = weight_determining_type
self.we... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# MEASURE - Master Equation Automatic Solver for Unimolecular REactions
#
# Copyright (c) 2010 by Joshua W. Allen (jwallen@mit.edu)
#
# Permission is hereby granted, free of charge, to... |
#
# Copyright (c) 2019 by Delphix. All rights reserved.
#
# flake8: noqa
from dlpx.virtualization.platform import Plugin
plugin = Plugin()
class ArbitraryError(Exception):
@property
def message(self):
return self.args[0]
def __init__(self, message):
super(ArbitraryError, self).__init__(m... |
# -*- coding: utf-8 -*-
# Functions for tracing the contour are provided in this file
import cv2
import numpy as np
# This is the search pattern of the neighbor points
neighbors = np.array([[-1, 0], [0, 1], [1, 0], [0, -1],
[-1, -1], [-1, 1], [1, -1], [1, 1]], dtype=np.int8)
# Check if the p... |
# Transposition Cipher Hacker
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import pyperclip
import detectEnglish
import transpositionDecrypt
def main():
# You might want to copy & paste this text from the source code at
# https://www.nostarch.com/crackingcodes/:
myMessage = """AaKoosoeDe5 b5s... |
# -*- coding: utf-8 -*-
# Copyright 2012 Loris Corazza, Sakis Christakidis
#
# 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
#
# U... |
from django.conf.urls import include, url
from django.contrib import admin
# from rest_framework.routers import DefaultRouter
# from snippod_starter_demo_app_server.views import api_root
# from rest_framework_nested import routers
#
# from authentication.views import AccountViewSet, LoginView, LogoutView
# from post... |
from iiits.config import templates |
# File Name : LFSR_Rand.py
# Description : implement a simple LFSR random number generator
# Author : Ganyuan Cao
def lfsr_gen(init, tap, n):
new_lfsr = init
tap_length = len(tap)
curr_sum = 0
exp_length = len(init) + 1
# iteratively fill the LFSR list
while exp_length <= n:
for i i... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPathos(PythonPackage):
"""Parallel graph management and execution in heterogeneous compu... |
from django.db import models
from django.utils.translation import gettext as _
# Create your models here.
class Article(models.Model):
title = models.CharField(_("Title"), max_length=150)
content = models.TextField(_("Content"))
def __str__(self):
return self.title
|
from __future__ import annotations
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel
from enum import Enum
class RoleEnum(str, Enum):
# super admin
SUPER = 'super'
# tester
TEST = 'test'
USER = 'user'
class RouteMeta(BaseModel):
# title
title: str
... |
class Solution:
def maxProfit(self, prices: List[int], fee: int) -> int:
profit=0 #initialize ans variable to 0 to avoid garbage value
holding=-prices[0]
for i in range(1,len(prices)): #iterate thrrough the array
profit=max(profit,holding+prices[i]-fee) #keep adding profit
... |
"""
Soft-Encoding Utils
+ Convert ab channels to categorical data as Zhang et al. paper
References:
+ https://github.com/foamliu/Colorful-Image-Colorization
"""
import numpy as np
import sklearn.neighbors as nn
class ColorizedSoftEncoding(object):
"""
Class Convert Channeld ab in Lab to Categorical Data as Zh... |
def valid_number(phonenumber):
if len(phonenumber)==12:
return True
return False
k = valid_number("919492331133")
print(k) |
# 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... |
num = [1,2,3]
num_sum = 0
count = 0
for x in num:
num_sum = num_sum + x
count = count + 1
if count == 2:
break
print (num_sum)
print (count) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.