content stringlengths 5 1.05M |
|---|
__author__ = "Kiriti Nagesh Gowda"
__copyright__ = "Copyright 2018, AMD NeuralNet Model Profiler"
__license__ = "MIT"
__version__ = "0.9.0"
__maintainer__ = "Kiriti Nagesh Gowda"
__email__ = "Kiriti.NageshGowda@amd.com"
__status__ = "Alpha"
import os
import getopt
import sys
import subproces... |
from setuptools import setup
setup(name='gym_pigchase_topdown',
version='0.1',
url="",
author="Federico Rossetto",
license="MIT",
packages=["gym_pigchase_topdown", "gym_pigchase_topdown.envs"],
install_requires=['gym', 'numpy', 'pygame', 'random']
) |
import random
xings_str = "李,王,张,刘,陈,杨,黄,赵,周,吴,徐,孙,朱,马,胡,郭,林,何,高,梁,郑,罗,宋,谢,唐,韩,曹,许,邓,萧,冯,曾,程,蔡,彭,潘,袁,于,董,余,苏,叶,吕,魏,蒋,田,杜,丁,沈,姜,范,江,傅,钟,卢,汪,戴,崔,任,陆,廖,姚,方,金,邱,夏,谭,韦,贾,邹,石,熊,孟,秦,阎,薛,侯,雷,白,龙,段,郝,孔,邵,史,毛,常,万,顾,赖,武,康,贺,严,尹,钱,施,牛,洪,龚"
mings_str = "大,二,三,四,五,六,七,八,九"
add_score_things = "点赞,赞美,打电话,帮助,送礼物"
reduce_score_things = ... |
from abc import ABC, abstractmethod
from collections import deque
from enum import Enum, IntEnum
from random import shuffle
from secrets import choice
from typing import Deque, List, NamedTuple
class Suit(IntEnum):
SPADE = 0
DIAMOND = 13
HEART = 26
CLUB = 39
def __repr__(self) -> str:
ret... |
import logging
import os
import socket
import sys
import uuid
from leapp.dialogs import RawMessageDialog
from leapp.exceptions import CommandError, MultipleConfigActorsError, WorkflowConfigNotAvailable
from leapp.messaging.answerstore import AnswerStore
from leapp.messaging.inprocess import InProcessMessaging
from lea... |
import libnum
import os
import requests
plugin_name = "rsa自动解题"
plugin_version = "v1.1"
plugin_author = "1me"
plugin_time = "20200505"
plugin_test_in='''
n=920139713
e=19
c=704796792
'''
plugin_test_out="None"
plugin_info = '''输入n,e,d,p,q,c,m等自动解题
需要 os,libnum,requests三个包
目前实现了几个简单计算
比如通过pq计算n
通过pqe计算d
n查factordb.com等等... |
#alist = [1,2,3,4,5,]
#def func(a):
# a = a**2
# return a
#blist = map(func,alist)
#res = [i for i in blist if i >= 16]
#print(res)
#print(list(i for i in blist if i >= 16))
import random
import time
def dec(fun):
def obj(*args,**kwargs):
star = time.time()
fun()
end = time.time()
tim = end ... |
#!/usr/local/bin/python
import requests
import traceback
import re
import time
import datetime
import getpass
import os
from PIL import Image
from json import loads,load,dump
from bs4 import BeautifulSoup
from http import cookiejar
from urllib import parse
from urllib.parse import quote, unquote
from requests.package... |
import os
import csv
import pandas as pd
from typing import List
from stork_a import StorkA, Classifier, Metadata, BlastocystScore, BlastocystGrade, Morphokinetics, InputImage, Result
def main():
stork_a = StorkA()
path = os.path.dirname(os.path.realpath(__file__))
classifier_base_path = os.path.join(path... |
# -*- coding: utf-8 -*-
import unittest
from driftconfig.util import get_drift_config
from drift.core.extensions.apikeyrules import get_api_key_rule
from drift.tests import DriftTestCase
from drift.systesthelper import setup_tenant
class ApiKeyRulesTest(DriftTestCase):
@classmethod
def setUpClass(cls):
... |
from objects.seismic.waves import OWT
import numpy as np
from objects.seismic.boundaries.refl_boundary_up import PDownPUpReflection, PDownPUpWaterReflection
from objects.seismic.boundaries.trans_boundary_down import PDownPDownTransmission, PDownPDownWaterTransmission
from objects.seismic.boundaries.trans_boundary_up im... |
import os
from lib import status
from src import video
from src import extract
import threading
import time
#limit max threads
max_threads = 5
#function to register a thread
#wait until a new thread is avaible, then start a new thread
def thread_get(FILE, PATH):
while True:
if threading.active_count() <= m... |
from typing import Tuple
import scipy.spatial
import numpy as np
def compute_distance_matrix(embeddings: np.array) -> np.array:
condensed = scipy.spatial.distance.pdist(embeddings, "euclidean")
matrix = scipy.spatial.distance.squareform(condensed)
return matrix
def compute_knn_confusions(distance_matri... |
#Importing libraries
import cv2
import pytesseract
import numpy as np
import os
import sys
sys.path.append(os.path.join(".."))
import argparse
def main(inpath):
# Loading image using OpenCV
img = cv2.imread(inpath)
# Creating the blue rectangle box of the region of interest, which contains the ... |
# standard library
from datetime import datetime
# third party
import requests
from cmath import nan
# this package
from health.data_models import BodyCompData
from health.exceptions import UnknownBehavior
class WeightGurus:
def __init__(self, username, password):
self.login_data = {"email": username, "... |
# -*- coding: utf-8 -*-
import redis
import os
import telebot
# import some_api_lib
# import ...
# Example of your code beginning
# Config vars
token = os.environ['TELEGRAM_TOKEN']
# some_api_token = os.environ['SOME_API_TOKEN']
# ...
# If you use redis, install this add-on https://elements.hero... |
#encoding:utf-8
import cv2
import numpy as np
#读取图片
src = cv2.imread('scenery.png')
rows, cols = src.shape[:2]
print rows, cols
#图像缩放
result = cv2.resize(src, None, fx=0.3, fy=0.3)
#显示图像
cv2.imshow("src", src)
cv2.imshow("result", result)
#等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
|
#!/usr/bin/env python
'''
This module creates archive_users_%projectid.cfg. It maker
sure the few users that is essential for the project is imported
even if they have not created any session that will be imported later.
'''
import os
from leginon import projectdata, leginondata
import sinedon
def checkSinedon():
i... |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
import uuid
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from tinymce.models import HTMLField
class BaseProfile(models.Model):
user = models.OneToOneF... |
class BuildableProductRunnable(object):
def __init__(self, entry_item):
self.contents = entry_item; |
# Copyright (c) 2012, Adam J. Rossi. All rights reserved. See README for licensing details.
import Chain, Common, FeatureExtraction
import os, math
class Surf(Chain.StageBase):
def __init__(self,
inputStages=None,
hessianThreshold=500,
numOctaves=3,
... |
import os
import torch
import argparse
import datetime
import numpy as np
from tqdm import tqdm
import torch.nn as nn
from math import floor
from apex import amp
import librosa
from contextlib import redirect_stdout
from configs import cfg
from dataset.util import *
import torch.optim as optim
from models.y_net import ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 12:16:33 2020
@author: danie
"""
import numpy as np
np.set_printoptions(legacy='1.13')
n, m = map(int,input().split())
print(np.eye(n, m)) |
from unittest import TestCase
from unittest.mock import MagicMock, patch
from app import create_app
from tests.request import check_status_code, solve_get_request, solve_post_request
class SolveGetTest(TestCase):
def setUp(self):
self.client = create_app(test=True).test_client()
@patch('view.solve.... |
__author__ = 'Igor Nikolaev'
from pytest_bdd import given, when, then
from model.contact import Contact
import random
import time
# Add new contact
@given('a contact list', target_fixture='contact_list')
def contact_list(db):
return db.get_contact_list()
@given('a contact with <firstname>, <lastname> and <midd... |
from Crypto.Util.number import getPrime
def int_to_bytes(n):
"""Converts the given int n to bytes and returns them."""
return n.to_bytes((n.bit_length() + 7) // 8, 'big')
def gcd(a, b):
"""Computes the greatest common divisor between a and b using the Euclidean algorithm."""
while b != 0:
a,... |
"""
--- Ångström ---
Tests reading xyz trajectory.
"""
from angstrom import Trajectory, Molecule
import numpy as np
import os
benzene_xyz = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'benzene.xyz')
def test_trajectory_from_molecule():
"""Tests converting Molecule to Trajectory object"""
benzen... |
from http import ClickatellClient, ClickatellException
|
import hypernetx as hnx
import math
import matplotlib.pyplot as plt
import matplotlib
from scipy.io import loadmat
import numpy as np
from matplotlib.collections import RegularPolyCollection
def init():
"""
134 126 246 123 346 345 456 256
:return:
"""
# 7
edges1 = [['1', '2', '4'], ['2', '3', ... |
#--- Exercicio 2 - Variávies e impressão com interpolacão de string
#--- Crie um menu para um sistema de cadastro de funcionários
#--- O menu deve ser impresso com a função format() para concatenar os números da opções, que devem ser números inteiros
#--- Alem das opções o menu deve conter um cabeçalho e um rodapé
#--... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... |
from django.db import models
from django.urls import reverse
# Create your models here.
class User(models.Model):
"""docstring for Farmer"""
auto_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
email = models.EmailField(max_length=30,unique=True)
pwd = models.CharField(max_length=1... |
from typing import Any, Dict, List, Optional, Union, cast
from rich.console import Console, ConsoleOptions, RenderResult
from rich.tree import Tree as RichTree
from .protocol import TrioNursery, TrioTask
""" Generate Identical Fake data for developing & test
Provide a simpler interface for constructing trio task tre... |
from .erd_remote_status import ErdRemoteStatus
from .remote_status import RemoteStatus
REMOTE_STATUS_MAP = {
ErdRemoteStatus.DISABLE: RemoteStatus.STATUS_DISABLE,
ErdRemoteStatus.ENABLED: RemoteStatus.STATUS_ENABLED,
ErdRemoteStatus.NOT_SUPPORTED: RemoteStatus.STATUS_NOT_SUPPORTED
}
|
"""
Usage:
merge_gradient_by_day.py <grad_no> <day> <sub_dir> <grad_dir> <merged_dir>
Arguments:
<grad_no> Gradient number
<day> Day
<sub_dir> Directory of all subjects' directories
<grad_dir> Directory of day1 and day2 gradients in dscalar.nii format
<merged_dir> director... |
"""MXNet and NNVM model zoo."""
from __future__ import absolute_import
from . import mlp, resnet, vgg, dqn, dcgan, squeezenet
import nnvm.testing
__all__ = ['mx_mlp', 'nnvm_mlp', 'mx_resnet', 'nnvm_resnet', 'mx_vgg', 'nnvm_vgg',
'mx_squeezenet', 'nnvm_squeezenet']
_num_class = 1000
# mlp fc
mx_mlp = mlp.g... |
from PDSUtilities.plotly import ColorblindSafeColormaps
def test_get_count():
colormaps = ColorblindSafeColormaps()
assert isinstance(colormaps.get_count(), int)
assert colormaps.get_count() > 0
def test_get_names():
colormaps = ColorblindSafeColormaps()
assert isinstance(colormaps.get_names(), li... |
import numpy as np;
import matplotlib.pyplot as plt;
license="""
Copyright (C) 2014 James Annis
This program is free software; you can redistribute it and/or modify it
under the terms of version 3 of the GNU General Public License as
published by the Free Software Foundation.
More to the points- thi... |
from installed_clients.specialClient import special as special
import json
import os
import shutil
def wdl(callback_url, token, params):
sr = special(callback_url, token=token)
src = '/kb/module/workflow.wdl'
wdl_file = 'workflow.wdl'
shutil.copy(src, '/kb/module/work/tmp/' + wdl_file)
input_file ... |
# Copyright 2022 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
"""
author: ouyangtianxiong
date: 2019/12/23
des: this algorithm package implements my personal innovation for my master thesis
"""
__author__ = 'ouyangtianxiong.bupt.edu.cn'
import sys
sys.path.append('../') |
import logging
logger = logging.getLogger("bogi")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
|
# flake8: noqa F401
# modules in this package are expected to implement a function `prepare` which
# takes the arguments workdir and component. this function prepares a directory
# in workdir for a terraform command and returns the version of terraform that
# should be used to run that command
from . import (
null,... |
from tapiriik.payments import *
from .totp import *
from tapiriik.database import db
from tapiriik.sync import Sync
from tapiriik.services import ServiceRecord
from tapiriik.settings import DIAG_AUTH_TOTP_SECRET, DIAG_AUTH_PASSWORD
from datetime import datetime, timedelta
from pymongo.read_preferences import Rea... |
# -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland
#
# 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.apac... |
#!/usr/bin/env python3
import requests
import structlog
import pkg_resources
from requests.auth import HTTPBasicAuth
from datetime import datetime
# Calls all wrappers and updates their health_check and capacities in the database.
def filename(name):
""" Obtain filepath for the resource.
:param name: Path ... |
"""
**pyavia.aero** provides functions relating to aerodynamics, thermodynamics
and fluid dynamics in general.
"""
# All sub-modules define __all__.
from ._atmosphere import *
from ._foil import *
from ._gasflow import *
|
import tkinter as tk
root=tk.Tk()
f1 = tk.Frame(width=200, height=200, background="red")
f2 = tk.Frame(width=100, height=100, background="blue")
f1.pack(fill="both", expand=True, padx=20, pady=20)
f2.place(in_=f1, anchor="c", relx=.5, rely=.5)
root.mainloop()
|
# https://en.wikipedia.org/wiki/High-dynamic-range_imaging
import cv2
import numpy as np
from glob import glob
#* 1. Loading exposure images into a list
images = glob("./images/hdr*")
images = [cv2.imread(image) for image in images]
exposure_times = np.array([15.0, 2.5, 0.25, 0.0333], dtype=np.float32)
#* 2. Mer... |
# # Image Clustering via KMeans
# # Author: Abhishek Gadiraju (abhishek.gadiraju@gmail.com)
# import numpy as np
# import random
# import sys
# #from PIL import Image
# class KMeans:
# def __init__(self, K):
# self.K = K
# self.centroids = [] # list of centroids
# self.clusters = {} # dictionary of... |
from datetime import datetime
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from pydantic import BaseModel
from ..utils import ynab_style_json_dumps
from .entities import AccountEntity, FileMetaDataEntity, PayeeEntity, TransactionEntity
class DiffFile(BaseModel):
startVersion: str #... |
from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key = True)
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 30, null= True)
address = models.TextField()
city = models.CharField(max_length = 30)
stat... |
# -*- coding: utf-8 -*-
import os
from O365 import Account, Connection, FileSystemTokenBackend
from datetime import datetime as dt
from datetime import timedelta
from conf.conf import CONFIG as conf
from fritzhome import FritzBox
import logging
class Core:
@staticmethod
def get_credentials():
return... |
from pymongo import MongoClient
import numpy as np
client = MongoClient("mongodb://localhost:27017")
db = client['test']
cursor = db.inflacao.find()
for document in cursor:
print(document)
def mmq(x, y):
x = np.insert(x, 0, 1, axis=1)
x_t = np.transpose(x)
xt_x = np.dot(x_t, x)
inverse_xt_x = np.lin... |
import strongr.core.gateways as gateways
from sqlalchemy import Column, ForeignKey, Integer, String, Enum, DateTime, func
from sqlalchemy.orm import relationship, synonym
from strongr.schedulerdomain.model.vmstate import VmState
Base = gateways.Gateways.sqlalchemy_base()
class Vm(Base):
__tablename__ = 'vms'
... |
"""
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value
appears at least twice in the array, and it should return false if every element is distinct.
"""
__author__ = 'Daniel'
from collections import Counter
class Solution:
def containsDuplicate(sel... |
from dials.algorithms.shoebox.masker import *
from dials_algorithms_shoebox_ext import *
|
# -*- coding: utf-8 -*-
"""
Test script for pyvi/volterra/tools.py
Notes
-----
Developed for Python 3.6
@author: Damien Bouvier (Damien.Bouvier@ircam.fr)
"""
#==============================================================================
# Importations
#================================================================... |
from graph import Graph
_SUCCESS = 0
_ERROR = 1
class Analyzer:
"""
Analyzer syntactic for operator grammar
"""
def __init__(self):
"""Init"""
self.graph = Graph()
self.rules = []
self.init = None
self.f={}
self.g={}
def add_rule(self, array):
... |
from __future__ import print_function
import boto3
import json
def lambda_handler(event, context):
dynamo = boto3.resource('dynamodb').Table(event['tableName'])
column = event['column']
request = dynamo.scan(AttributesToGet=[column])
# Undefined for no values
if request['Count'] is 0:
... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'mainunJTzN.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
###############... |
from logging import getLogger
from functools import lru_cache
from .funcs import list_to_str, try_draw
from .html import Div
class Boot:
defaults = {}
_class = ""
def __init__(self, *args, **kwargs) -> None:
self.logger = getLogger(self.__class__.__name__)
self.args = args
... |
# -*- coding: UTF-8 -*-
# Stock data fetch from website.
from qcinfo import xueqiu as XQ
from qcinfo import qcrepo, gtimg
from qcinfo.log import qcinfo_log
logger = qcinfo_log()
async def company_info_async(code):
'''
上市公司基本信息
:param code: Stock code
:return:
'''
return await XQ.company_info_a... |
# -*- coding: utf-8 -*-
"""Delayed evaluation.
Inspired by Racket's promises and `macropy.quick_lambda.lazy`.
See:
https://docs.racket-lang.org/reference/Delayed_Evaluation.html
https://macropy3.readthedocs.io/en/latest/lazy.html
"""
__all__ = ["delay", "force"]
from mcpyrate.multiphase import macros, phase... |
# Generated by Django 2.2.6 on 2020-03-18 13:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tasks", "0004_task_reference"),
]
operations = [
migrations.RemoveField(model_name="task", name="estimated_duration",),
migrations.A... |
import pickle
import numpy as np
import os
#Count # of pts in every detected object
fname_detected="./detected.txt"
fname_undetected="./undetected.txt"
#a,b=os.path.splitext(filename)
with open(fname_detected , 'rb') as f:
detected = f.readlines()
with open(fname_undetected , 'rb') as f:
undetected = f.readli... |
class Reader:
def __init__(self, stream, sep=None, buf_size=1024 * 4):
self.stream = stream
self.sep = sep
self.buf_size = buf_size
self.__buffer = None
self.__eof = False
def __iter__(self):
return self
def __next__(self):
if not self.__buffer:
... |
# main.py
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
USERNAME = "ACCOUNT_USER"
PASSWORD = "ACCOUNT_PASS"
URL = "https://www.netflix.com/browse/my-list"
REGEX = r"https://www.netflix.com/watch/(.*?)\?tctx"
def login(browser):
print(browser.current_url)
try:
... |
file = open('file_example.txt', 'r')
contents = file.read()
file.close()
print(contents)
|
# 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
# distributed unde... |
# coding=utf-8
from __future__ import unicode_literals
from .consumer import OAuth1ConsumerBlueprint, OAuth2ConsumerBlueprint
__version__ = "0.13.0"
|
import paho.mqtt.publish as publish
publish.single("yuyao/server", "payload", hostname="0.0.0.0")
|
from graphics import *
import random
import pyautogui
mouseX, mouseY = pyautogui.position()
def scene(x,y):
win = GraphWin("Scene", x, y)
win.setBackground('skyblue')
#layer 1
sun = Circle(Point(win.getWidth()*0.8,win.getHeight()*0.2), win.getHeight()*0.1)
sun.setFill('yellow')
s... |
"""
This file is the entry point for the maggport package
Example:
maggport --host <host> --port <port> --db <db> --collection <collection> --pipeline_path <pipeline_path> --out <out>
"""
import ast
import json
import time
from typing import Any
import click
import pymongo
from maggport import exports, logger, v... |
import numpy as np
import multiprocessing as mp
from abc import ABCMeta, abstractmethod
from warnings import warn
from .. import Bandstructure
from .. import Parameters
class System(metaclass=ABCMeta):
"""Abstract class for the implementation of a specific model system. Child classes need to
implement ``tunn... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=2 tabstop=2 expandtab textwidth=79:
import asyncio
import cgi
import logging
import os
import random
import re
import string
import time
import urllib
import urllib.parse
from collections import namedtuple
import aiohttp
import async_timeout
import reques... |
from django import forms
from django.utils.translation import gettext_lazy
from dfirtrack_main.models import Analysisstatus, Case, Company, Domain, Dnsname, Location, Os, Reason, Serviceprovider, System, Systemstatus, Systemtype, Tag
class SystemImporterFileCsvConfigbasedForm(forms.Form):
# file upload field (var... |
import pytest
from pytest_mock import MockerFixture
from pystratis.api.notifications import Notifications
from pystratis.core.networks import StraxMain, CirrusMain
def test_all_strax_endpoints_implemented(strax_swagger_json):
paths = [key.lower() for key in strax_swagger_json['paths']]
for endpoint in paths:
... |
"""
detail
~~~~~~
Parse an OSM XML file, validating the data, and producing a stream of rich
data objects. Designed for debugging and understanding the data. Practical
applications should use one of the faster, more streamlined processing modules.
"""
from .utils import saxgen as _saxgen
import datetime as _datetim... |
from django.conf import settings
__all__ = ['lazy_register']
def lazy_register(register):
if "compressor" in settings.INSTALLED_APPS:
@register.tag
def compress(parser, token):
from compressor.templatetags.compress import compress
return compress(parser, token)
else:
try:
@reg... |
from ....graph import (
Graph,
Edge,
)
class MSTPrim():
def __call__(
self,
g: Graph,
) -> Graph:
import heapq
n = g.size
new_g = Graph.from_size(n)
visited = [False] * n
inf = 1 << 60
weight = [inf] * n
hq = [(0, -1, 0)]
while hq:
wu, pre, u = heapq.heappop(hq)
... |
import numpy as np
import sklearn as sk
import csv
# default values for options
options = {}
options['train_log_dir'] = 'logs'
options['output_dir'] = 'output'
options['training_file'] = '../data/uniform.pickle'
options['noise_dims'] = 62
options['latent_dims'] = 2
options['batch_size'] = 128
options['gen_lr'] = 1e-3
... |
#14) Longest Collatz sequence
#The following iterative sequence is defined for the set of positive integers:
#n → n/2 (n is even)
#n → 3n + 1 (n is odd)
#Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
#It can be seen that this sequence (starting... |
__all__ = []
from . import decorators
__all__.extend(decorators.__all__)
from .decorators import *
from . import readers
__all__.extend(readers.__all__)
from .readers import *
from . import menu
__all__.extend(menu.__all__)
from .menu import *
|
# ------- 3rd party imports -------
import flask
from flask import Blueprint, render_template, request
your_short_url_blueprint = Blueprint('your_short_url_blueprint', __name__, template_folder='templates')
@your_short_url_blueprint.route('/your_short_url')
def your_short_url():
original_url = request.args['orig... |
# coding: utf-8
import os
import sys
import sqlite3
import cfg
from src import logging
def db_init():
try:
if not os.path.isfile(cfg.get_path_to_db()):
logging.Logger('info').info('Database has just been created and is empty')
db_con = sqlite3.connect(cfg.get_path_to_db())
db... |
# Copyright 2013-2021 Sebastian Ramacher <sebastian+dev@ramacher.at>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, c... |
from distutils.core import setup
setup(
name='cvpro',
packages=['cvpro'],
version='1.1.0',
license='MIT',
description='CVPRO - Computer Vision PROfessional - HELPING LIBRARY',
long_description="README.md",
long_description_type="text/markdown",
author='MOHAK BAJAJ',
autho... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.http import HttpResponse
admin.autodiscover()
urlpatterns = [
url(r'^api/v2/', include('fiber.rest_api.urls')),
url(r'^admin/fiber/', include('fib... |
# Copyright 2013-2019 Donald Stufft and individual contributors
#
# 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 applicabl... |
Age = 20
print Age
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: sync_ldap_dimission_user_state_to_cmdb.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _m... |
"""empty message
Revision ID: 59608aa9414e
Revises: 91c2bd4689a
Create Date: 2015-09-28 12:36:05.708632
"""
# revision identifiers, used by Alembic.
revision = '59608aa9414e'
down_revision = '91c2bd4689a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - pl... |
"""Properties used to create the Gaphor data models.
The logic for creating and destroying connections between elements is
implemented in Python property classes. These classes are simply instantiated
like this:
class Class(Element): pass
class Comment(Element): pass
Class.comment = association('comment', ... |
import asyncio
import collections.abc
import functools
import inspect
from typing import (
Any,
Awaitable,
Callable,
Dict,
Hashable,
Iterator,
Optional,
Set,
Tuple,
Union,
)
import uuid
from aiohttp import web
import aiohttp_session
__version__ = "1.1.1"
DEFAULT_ID_FACTORY = l... |
import unittest
__author__ = "Bilal El Uneis"
__since__ = "August 2020"
__email__ = "bilaleluneis@gmail.com"
class A:
def __init__(self) -> None:
pass
@property
def id(self) -> int:
return id(self)
class RefrenceTypeTests(unittest.TestCase):
def test_refrence(self) -> None:
... |
#!/usr/bin/env python
# Test driver for basic test
from __future__ import print_function
import sys
import unittest
import time
import os
import math
import rospy
import rospy.client
import rospkg
from sensor_msgs.msg import Image, CompressedImage
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
... |
from google_images_search import GoogleImagesSearch
import os
import requests
with open(r".\APIKEY.txt" , 'r') as f:
f_con = f.readlines()
APIKEY, api2 = f_con[0],f_con[1]
gis = GoogleImagesSearch(APIKEY, api2)
class searcher:
def __init__(self,word,imgName):
self.word = word
s... |
from django.urls import reverse
from aether.utils.cache import expire_page
def invalidate_cache(sender, instance, created, **kwargs):
expire_page(reverse('gallery:index'))
|
from __future__ import unicode_literals
import vmraid
from vmraid import _
session = vmraid.session
def authenticate(user, raise_err = True):
if session.user == 'Guest':
if not vmraid.db.exists('Chat Token', user):
if raise_err:
vmraid.throw(_("Sorry, you're not authorized."))
else:
return False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.