content stringlengths 5 1.05M |
|---|
'''
Check-for-balanced-parentheses
Problem Statement : Given an expression string x. Examine whether
the pairs and the orders of
“{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return
'true' for exp = “[()]{}{[(... |
from pleasehold.core import hold, transfer
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vispy: gallery 60
"""
Points revolving around circles (revolving in a circle) to create a torus.
"""
import numpy as np
from vispy import gloo
from vispy import app
from vispy.gloo import gl
from vispy.util.transforms import perspective, translate, rotate
# points and... |
from .base_model import BaseModel, db
class Admin(BaseModel):
__tablename__ = 'admins'
email = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(255), nullable=False)
first_name = db.Column(db.String(100), nullable=False)
last_name = db.Column(db.String(100), nullable=False)... |
import boto3
client = boto3.client('cloudwatch')
def lambda_handler(event, context):
t = event["reading_time"]
v = float(event["reading_value"])
print "New temperature reading: Time: %s, Temp: %.2f" % (t, v)
client.put_metric_data(
Namespace = 'Temperature Monitoring Database App',
MetricData ... |
"""Introspection and validation for osbuild
This module contains utilities that help to introspect parts
that constitute the inner parts of osbuild, i.e. its stages,
assemblers and sources. Additionally, it provides classes and
functions to do schema validation of OSBuild manifests and
module options.
A central `Inde... |
# Generated by Django 3.0.4 on 2020-03-23 01:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
... |
import json
import os
import sys
import time
import shutil
import uuid
import mock
import botocore.session
import pytest
import requests
import websocket
from chalice.cli.factory import CLIFactory
from chalice.utils import OSUtils, UI
from chalice.deploy.deployer import ChaliceDeploymentError
from chalice.config impo... |
# FUNCTIONS
# populate - populate square grid with the same number in it in all positions except for those already filled in the puzzle
def populate(num, puzz):
ones = []
for i in range(9):
ones.append([])
for j in range(9):
if puzz[i][j] == 0:
ones[i].append(num)
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 10:17:05 2019
@author: lansf
"""
import os
from jl_spectra_2_structure.plotting_tools import set_figure_settings
from jl_spectra_2_structure.cross_validation import LOAD_CROSS_VALIDATION
set_figure_settings('paper')
#Folder where figures are to be saved
Downloads_fold... |
from django import template
from reversion.models import Version
register = template.Library()
@register.inclusion_tag("includes/last_modified.html")
def last_modified(obj):
"""Get all versions for specific object, display:
"Created on ASD by DSA."
"Last modified on ASD by DSA."
"""
versions = V... |
import os
LOGIN_URL = '/'
LOGIN_REDIRECT_URL = '/'
# URL_PATH = ''
# SOCIAL_AUTH_STRATEGY = 'social.strategies.django_strategy.DjangoStrategy'
# SOCIAL_AUTH_STORAGE = 'social.apps.django_app.default.models.DjangoStorage'
# SOCIAL_AUTH_EMAIL_FORM_URL = '/signup-email'
# SOCIAL_AUTH_EMAIL_FORM_HTML = 'email_signup.html'... |
class UnexpectedTypeError(TypeError):
"""
Inappropriate argument type.
"""
def __init__(self, expected, actual, message = ""):
if isinstance(expected, (tuple, list)):
super(UnexpectedTypeError, self).__init__(
"Invalid argument type; expected any of " + ', '.join(
... |
'''
__author__ = 'Ranjith'
This script actually crawls through the website to fetch actual data and message to the user
Make sure to configure Config.txt before using
'''
import ConfigParser
import os
import logging
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from spirit_pages... |
import sys, os, time
from tqdm import tqdm
import numpy as np
import matlab.engine
import ott_plotting
ott_plotting.update_base_plotting_directory(\
'/home/cblakemore/plots/ott_farfield/movies')
base_data_path = '../raw_data/movies/zsweep_test'
### Pack up all the simulation parameters into a dictionary... |
"""Class to represent a conference. Consists only of conf dict and methods for queries."""
__author__ = "Lars Meister"
from dateutil import parser as dateparser
class Conference:
"""Provides methods for querying a conference."""
paper_attributes = ["paper_title", "paper_link", "paper_authors", "paper_type",... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy
from scipy import stats
def calc_m(data):
""" Create the A matrix for the overdetermined system of equations Ax=0
in this matrix, each entry is weighted by the variance of m
... |
from fastai.vision import *
from fastai.data_block import _maybe_squeeze
from . import Im2MOS
"""
# %%
from fastiqa.all import *; Im2Tags(FLIVE640).data
# %%
"""
class NanLabelImageList(ImageList):
def label_from_df(self, cols:IntsOrStrs=1, label_cls:Callable=None, **kwargs):
"Label `self.items` from the ... |
from dataclasses import dataclass, field
from typing import List
@dataclass
class CsProjConfig:
root_namespace: str = ""
assembly_name: str = ""
output_type: str = ""
output_paths: List[str] = field(default_factory=lambda: [])
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
setup(
name='olintut',
version='0.1',
description='Source code for tech talk: https://docs.google.com/presentation/d/1lDDqROrpEvDYb1TcDBQBwKLQjWyTT0gs4vN1-2sraMg/edit#slide=id.g4e2f016a03_1_5',
author='Chris Lee',
author_em... |
from collections import Counter
import pydotplus as pydot
import numpy as np
from sklearn.cluster import KMeans
class FeatureTree:
def __init__(self, max_level, db_features_list, k):
self.max_level = max_level
self.db_features_dict = {}
self.db_features_ids = []
self.graph = pydot... |
from __future__ import absolute_import, division, print_function
import datetime
import pandas as pd
from config import *
def generate_analysis_connections_store_key(rssi_cutoff, table_name):
"""
Generates a path to a connections table created using a specific rssi_cutoff
:param rssi_cutoff:
:param t... |
from typing import Any, Union
from boa3.builtin.interop.stdlib import memory_compare
def main(mem1: Union[bytes, str], mem2: Union[bytes, str], arg: Any) -> int:
return memory_compare(mem1, mem2, arg)
|
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# This file is part of the Proxmox Virtual Environment for Check_MK
# It defines metric information used in the plugin.
# Author: Chris Pedro
# Date: 2020-07-01
# .--Checks--------------------------------------------------------------.
# | ... |
"""The docker_shell command takes the path to a single tool file and returns
a new command to launch a new shell into the corresponding Docker container
for that tool.
Galaxy will treat the identifier in the tool XML file as a published Docker
image - during development such the image an image may not yet exist or may... |
class CommandWarning(Exception):
pass
class CommandError(Exception):
pass
|
#!/usr/bin/env python3
#
# This module requires HatSploit: https://hatsploit.netlify.app
# Current source: https://github.com/EntySec/HatSploit
#
from hatsploit.lib.module import Module
from hatsploit.utils.session import SessionTools
class HatSploitModule(Module, SessionTools):
details = {
'Name': "Win... |
class QuranRequest:
_url = 'http://api.alquran.cloud/surah/{}/{}?offset={}&limit={}'
def __init__(self, req, edition):
# language not specified, assume english
if edition.find('.') == -1 and edition.find('-') == -1:
edition = 'en.' + edition
self.edition = edition
r... |
import os
import errno
from bento.compat.api \
import \
relpath
from bento.installed_package_description \
import \
InstalledSection
from bento.commands.errors \
import \
CommandExecutionFailure
def toyext_to_distext(e):
"""Convert a bento Extension instance to a distutils
... |
import json
import os
import sys
import time
import random
import numpy as np
import math
import operator
from MTokenizer import MTokenizer
def takingSamples(alist, portion=0):
seed = int(round(time.time() * 1000)) % 100000000
random.seed(seed)
length_of_list = len(alist)
listPicked = []
listNotPic... |
from __future__ import unicode_literals
from django.utils import six
from easy_thumbnails.conf import settings
class ThumbnailOptions(dict):
def __init__(self, *args, **kwargs):
self._prepared_options = None
super(ThumbnailOptions, self).__init__(*args, **kwargs)
if settings.THUMBNAIL_DE... |
from __future__ import print_function, division, absolute_import
import pandas as pd
def must_run(REGION_YEAR_TECH_GENERATION_ARR, TECH_MUSTRUN_LS, AVAIL_GEN_ARR):
df_hd = pd.DataFrame(columns = ['REGION_ID', 'YEAR', 'TECHNOLOGY', 'TIMESLICE', 'VALUE'])
for i in range(len(REGION_YEAR_TECH_GENERATI... |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
return self.hashmap(nums, target)
def naive(self, nums, target):
for i in range(0, len(nums) - 1):
for j in range(i + 1, ... |
import ismore.invasive.bmi_ismoretasks as bmi_ismoretasks
import ismore.invasive.patient_display as patient_display
import ismore.invasive.bmitasks_w_display as bmitasks_w_display
from riglib import experiment
from features.hdf_features import SaveHDF
import tables
import multiprocessing as mp
import numpy as np
import... |
import sys
import os.path
import time
def main(argv):
pathToHTML = argv[0]
pathOutput = argv[1]
number = argv[2]
htmlF = open(pathToHTML, "r")
all_content = htmlF.read()
all_content = all_content.replace("$N_TESTS", str(number))
htmlOutput = open(pathOutput, "w")
htmlOutput.write(all... |
from shutil import copyfile
import pandas as pd
import os
import argparse
def copy_data(source_dir, video_name, save_dir):
"""Copy video data from the source_dir to save_dir
Parameters:
source_dir (str): path to the video source
video_name (str): name of the video to copy
save_dir (str): path to the directo... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('latest_tweets', '0013_hashtags'),
]
operations = [
migrations.AlterField(
model_name='tweet',
name='name',
field=models.CharField(max_length=50),
... |
"""
benchmark runners
"""
from .aws import AWSBenchmark
from .docker import DockerBenchmark, DockerBenchmarkAPI
from .singularity import SingularityBenchmark
__all__ = [
"DockerBenchmark",
"SingularityBenchmark",
"AWSBenchmark",
"DockerBenchmarkAPI",
]
|
import random
import unittest
def HasElement(vector, element):
# It seems that binary search is not hard to write correctly anymore with Python
vector.sort()
def _BinarySearch(begin, end, element):
if begin == end:
return False
elif end - begin == 1:
return vector[... |
print("Please enter an integer: ")
user_input = int(input())
abs_value = user_input
if(not user_input >= 0):
abs_value = user_input * -1
print("|", user_input, "| = ", abs_value, sep="")
|
# -*- coding: utf-8 -*-
"""
Optimization utilities.
"""
from __future__ import print_function, division, absolute_import
from pykit.ir import Op
def update_context(dst_env, src_env, valuemap):
"""
Update our typing context with the types from the original operations
and context.
"""
context = ds... |
from app.eventhandlers.eventhandler import EventHandler
from app.eventhandlers.eventhandler_factory import build_eventhandlers
|
import os
from fpdf import FPDF
from datetime import datetime, timedelta
from authsys_common.dates import add_month
import calendar
MAX_X = 210
MAX_Y = 297
def get_next_monday():
today = datetime.now().replace(hour=0, minute=0, second=0)
while today.weekday() != 0:
today += timedelta(days=1)
retu... |
# coding=utf-8
# Copyright 2021 The Google Research 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 by applicab... |
from pathlib import Path
here = Path(__file__).parent
import sys
sys.path.insert(0, str(here.parent) + "/topopt") |
from utils.registry import Registry, build_from_cfg
INTERNODE = Registry('internode')
def build_internode(cfg, **default_args):
# print(INTERNODE.module_dict.keys())
# exit()
if 'one_way' in cfg.keys():
if cfg['one_way'] == 'forward':
tmp_cfg = dict(
type='ForwardOnly'... |
a,b,c,d=int(input()),int(input()),int(input()),int(input())
print(pow(a,b)+pow(c,d))
|
import os
import sys
# os.environ['KIVY_HOME'] = os.path.dirname(os.path.abspath(__file__))+'/../kivy'
from gltrader.gltrader import GLTraderApp
if __name__ == '__main__':
GLTraderApp().run()
|
from flask import Flask,render_template,request,redirect,session,url_for
import pymysql
connection = pymysql.connect(host='localhost',
user='root',
passwd='',
db='grocerymania',
port = 3306
... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
from emojislib.__version__ import version
setuptools.setup(
name="emojislib",
version=version,
author="Tacey Wong",
author_email="xinyong.wang@qq.com",
description="Emojis for Python 😄 🐍 😋",
long_descripti... |
"""
Python Template for docstring
-----------------------------
python.docstring is a package cotaining TEMPLATE for docstring in python.
usage:
>>> from python import docstring
>>> help(docstring)
>>> print(docstring.module_.__doc__)
>>> print(docstring.class_.__doc__)
>>> print(docstrin... |
# coding: utf-8
"""
Openmoney API
Openmoney API # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class NamespacesRequest(object):
"""NOTE: This class is auto generated by the s... |
from batch_geocoder import __version__
from setuptools import setup
long_description = ''
with open('./README.md') as f:
long_description = f.read()
setup(name='batch_geocoder',
version=__version__,
description='Python package of helpers, wrappers, and custom modules for geocoding location data.',
lon... |
from flask import Blueprint, render_template, request, redirect, jsonify, url_for, g
from flask import current_app as app
from flask_login import login_required, current_user
from rq import push_connection, pop_connection, Queue
import redis
from app import tasks
api_bp = Blueprint('api', __name__, url_prefix='/api')... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the Google Drive database plugin."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import gdrive as _ # pylint: disable=unused-import
from plaso.lib import definitions
from plaso.parsers.sqlite_plugins import gdrive
from tes... |
import re
import cjson
class ShardMap(object):
def __init__(self, fname=None):
if fname is None:
fname = "/etc/lounge/shards.conf"
self.load_config(fname)
self.get_db_shard = re.compile(r'^(.*\D)(\d+)$')
def load_config(self, fname):
self.config = cjson.decode(file(fname).read())
self.shardmap = self.... |
from flask import Flask, render_template, redirect, make_response, jsonify, request, send_from_directory
import flask
import requests
import argparse
import os
app = Flask(__name__)
method_requests_mapping = {
'GET': requests.get,
'HEAD': requests.head,
'POST': requests.post,
'PUT': requests.put,
... |
import torch
def regress2d(x, y):
'''
Input:
x - torch Tensor of shape (d, n), d different sets of n x-points.
y - torch Tensor of shape (d, n), corresponding y-values.
Output:
w - torch Tensor of shape (d, 1), linearly least square
weights to map x to y.
b - t... |
import os
EMAIL = os.environ['EMAIL']
PASSWORD = os.environ['PASSWORD']
DISCORD_TOKEN = os.environ['DISCORD_TOKEN']
SERVER_STATUS_CHANNEL = 403752425036709888
PATCH_NOTES_CHANNEL = 625176460059213824
ADMIN_LOGS_CHANNEL = 403734549491744769
LV4_CHAT_CHANNEL = 557420699191476227
KNOWN_BUGS_CHANNEL = 403741506407497728... |
class Config(object):
"""
Represents configuration of network training
"""
pass
|
from dataclasses import dataclass
from typing import Tuple
from image_marker.utils import contain
@dataclass
class Rectangle:
x: int = 0
y: int = 0
w: int = 0
h: int = 0
def to_strings(self) -> Tuple[str, ...]:
return tuple(map(str, (self.x, self.y, self.w, self.h)))
@classmethod
... |
#
# Copyright (c) 2019, 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 ... |
"""
The foto blueprint allows for searching and displaying
EDH foto data.
"""
from flask import Blueprint
bp_foto = Blueprint('foto', __name__, template_folder='templates')
from . import routes
|
#!/usr/bin/python3
import argparse as ap
parser=ap.ArgumentParser(description="Convert xml file to ccUnittestinput")
parser.add_argument("-x","--xmlfile",type=ap.FileType('r'),required=True, help="xmlfiletoread")
parser.add_argument('-s',"--streamname",type=str, help="streamname to output to")
args=parser.parse_arg... |
"""
@Time : 2018/7/23 19:34
@Author : 郭家兴
@Email : 302802003@qq.com
@File : app.py
@Desc : 入口文件
"""
from flask_socketio import emit
from werkzeug.exceptions import HTTPException
from app import create_app
from app.libs.error import APIException
socket_io,app = create_app()
@app.errorhandler(Exception)
d... |
# Generated by Django 2.2.7 on 2019-11-23 04:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('student_portal', '0005_student_semester'),
]
operations = [
migrations.RenameField(
model_name='student',
old_name='semester... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Basic configuration for the application.
"""
from django.apps import AppConfig
class CalAccessScrapedConfig(AppConfig):
"""
Application configuration.
"""
name = 'calaccess_scraped'
verbose_name = "CAL-ACCESS scraped data"
default_auto_field = ... |
import numpy as np
import cv2
"""
@file : Util.py.
@Author : Charan Karthikeyan P V, Nischal NJ, Sai Manish V.
@copyright : MIT license.
@date : 11/08/2020.
@brief : The class file to declare and define the Augumented Reality Class.
"""
class AR():
"""
@brief:Construcor fot the class AR
@param None
@re... |
"""
Python gRPC prediction server
https://grpc.io/docs/languages/python/quickstart/
To generate proto use:
cd prediction_server
$ python -m grpc_tools.protoc -I protos --python_out=. --grpc_python_out=. protos/prediction_server.proto
"""
import sys
import os
import inspect
currentdir = os.path.dirname(os.path.abspat... |
# -*- coding:utf-8 -*-
"""
author comger@gmail.com
适合于Tornado 的角色权限模块
主要功能清单
1. 权限的自动分组收集
2. 角色
a. 支持默认超管角色
b. 支持代码级的角色管理
c. 支持数据存储级的角色管理
"""
import os
import traceback
import tornado
from tornado.web import RequestHandler
from tornado.httpclient import HTTPError
from inspec... |
from checkov.common.models.enums import CheckCategories
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
from typing import Any, List
class APIGatewayDomainNameTLS(BaseResourceValueCheck):
def __init__(self):
name = "Ensure API Gateway Domain uses a modern sec... |
# Spreadsheets often use this alphabetical encoding for its columns: "A", "B",
# "C", ..., "AA", "AB", ..., "ZZ", "AAA", "AAB", ....
# Given a column number, return its alphabetical column id. For example, given
# 1, return "A". Given 27, return "AA".
def convert26to10(alpha):
num = 0
for a in alpha... |
from deck import *
import unittest
class DeckTests(unittest.TestCase):
def setUp(self):
self.deck = Deck()
self.deck2 = Deck()
def test52DifferentCards(self):
self.assertEquals(self.deck.cardsLeft(), 52)
removed = []
i = 0
while self.deck.cardsLeft() > 0 and i... |
from feast.infra.offline_stores.contrib.postgres_offline_store.tests.data_source import (
PostgreSQLDataSourceCreator,
)
from tests.integration.feature_repos.integration_test_repo_config import (
IntegrationTestRepoConfig,
)
FULL_REPO_CONFIGS = [
IntegrationTestRepoConfig(
provider="local",
... |
__author__ = 'varun'
from django.conf.urls import url
from .views import HomePageView
urlpatterns = [
url(r'^\Z', HomePageView.as_view()),
]
|
import pytest
@pytest.mark.django_db
def test_reverse_models(client):
from wagtail_graphql.registry import registry
# force loading the api
client.post('/graphql', {"query": "{ format }"})
models = registry.models
assert {v: k for k, v in models.items()} == registry.rmodels
@pytest.mark.django... |
#!/usr/bin/env python3
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn import naive_bayes
from sklearn import metrics
def plant_classification():
# Download the Iris dataset
data = load_iris()
X, y = data.data, data.target
# Get the training a... |
import os
def is_leaf(folder):
"""Determine whether folder does not contain any subfolders.
Parameters
----------
folder : str
Folder to be checked for being a leaf.
Returns
-------
bool
True if folder is leaf (does not contain any subfolders),
False otherwise.
... |
#! /usr/bin/env python
import threading
import rospy
import actionlib
from nextfood_tasks.msg import *
from datetime import datetime
def str_to_sec(time_str):
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + int(s)
def pretty_print_sec(seconds):
m, s = divmod(seconds, 60)
h, m = divmod... |
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def reverse(start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
... |
import socket
import threading
sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sckt.bind(('127.0.0.1', 9090))
sckt.listen(10)
users = set()
def connect_users():
while True:
clientsocket, addr = sckt.accept()
users.add(clientsocket)
print('connected:' + str(addr))
threadin... |
import rospy
import ros_numpy
import numpy as np
import copy
import json
import os
import sys
import torch
import time
from std_msgs.msg import Header
import sensor_msgs.point_cloud2 as pc2
from sensor_msgs.msg import PointCloud2, PointField
from jsk_recognition_msgs.msg import BoundingBox, BoundingBoxArray
from pyq... |
import functools
import os
from invoke import task
#from fabric.api import env, lcd, local, task
# Local path configuration (can be absolute or relative to fabfile)
env = {"input_path" : 'content'
, "deploy_path" : 'output'
}
@task
def build(c):
c.run('pelican {input_path} -o {deploy_path} -s pelicancon... |
from time import perf_counter
from random import randint, seed
seed(100)
def counting_sort(T, k):
C = [0]*k
B = [0]*len(T)
for i in range(len(T)):
C[T[i]] += 1
for i in range(1, k):
C[i] += C[i-1]
for i in range(len(T)-1, -1, -1):
C[T[i]] -= 1
B[C[T[i]]] = T[i]
... |
import os
import numpy as np
import cv2
import xml.etree.ElementTree as ET
import re
from torchvision.datasets import VisionDataset
intrinsic_camera_matrix_filenames = ['intr_CVLab1.xml', 'intr_CVLab2.xml', 'intr_CVLab3.xml', 'intr_CVLab4.xml',
'intr_IDIAP1.xml', 'intr_IDIAP2.xml',... |
# Creating node accounts for the Messidge python library
# (c) 2017 David Preece, this work is in the public domain
from messidge import KeyPair
from messidge.broker.identity import Identity
identity = Identity()
try:
keys = KeyPair.new()
identity.register_node(keys.public.decode(), '{}')
skeys = KeyPair("... |
#
# Original implementation:
#
# Copyright 2015 Google 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 applicabl... |
def first():
print('FIRST')
for i in range(2,1200,7):
if(i%5!=0):
print(i+2000,end=',')
def second():
print(end='\n')
print('SECOND')
first_name=str(input('enter your first name'))
second_name=str(input('enter your second name'))
print(first_name[::-1]+' '... |
# Testing the basic intent for ipv6 functionality of ONOS
class FUNCipv6Intent:
def __init__( self ):
self.default = ''
def CASE1( self, main ):
import time
import imp
import re
"""
- Construct tests variables
- GIT ( optional )
- Checkout ... |
#!/usr/bin/env python3
import math
def printPrimeNumber(stop):
n = 16000000000000000000
stop += n
while n<stop:
n += 1
if isPrime(n):
print(n)
def isPrime(n):
for x in range(2,n):
if n % x == 0:
return False
return True
printPrimeNumber(1000) |
from django.shortcuts import render
# Create your views here.
def persona_list(request):
persona = Persona.objects.all
return render(request, 'scmt/persona_list.html', {'personas': persona}) |
ged_data = []
def initialize_file():
global ged_data
ged_data = []
def add_line(hierarchy,type,value=None):
global ged_data
if value:
ged_data.append(str(hierarchy) + ' ' + str(type) + ' ' + str(value))
else:
ged_data.append(str(hierarchy) + ' ' + str(type))
def append_record(pare... |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import threading
import subprocess
import ftplib
import os
import time
import datetime
from PIL import Image
class Uploader(threading.Thread):
def __init__(self, shoottime, timelapse):
threading.Thread.__init__(self)
self.Shoottime = shoottime*1000
... |
import pint
from . import util
def time_create_registry(args):
pint.UnitRegistry(*args)
time_create_registry.params = [[(None,), tuple(), (util.get_tiny_def(),)]]
|
import functools, operator, os, sys, subprocess
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def die(msg, errno=1):
eprint(f'error: {msg}')
exit(errno)
def a_an(s):
if not s:
return s
prefix = 'an' if s[0] in 'aeiou' else 'a'
return f'{prefix} {s}'
def pluralize(s, n):
if n... |
"""A collection of dpa-specific nuke nodes."""
from collections import defaultdict
import os
import re
import nuke
from dpa.ptask import PTask
from dpa.ptask.area import PTaskArea, PTaskAreaError
from dpa.ptask.spec import PTaskSpec
# -----------------------------------------------------------------------------
# ... |
'''
Write a Python program to remove everything except alphanumeric characters from a string.
In some usages, the alphanumeric character set may include both upper and lower case letters, punctuation marks,
and symbols (such as @, &, and *, for example).
given Text : '**//Python Exercises// -@ 12 3- 4&.. '
'''
import... |
# Generated by Django 2.1.7 on 2019-03-14 18:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exhibitions', '0005_exhib_audio'),
]
operations = [
migrations.AddField(
model_name='exhibitpage',
name='gallery_col... |
from typing import List, Union, Callable, Optional
from nlpatl.models.clustering import Clustering
from nlpatl.models.embeddings import Embeddings
from nlpatl.learning import Learning
from nlpatl.dataset import Dataset
class UnsupervisedLearning(Learning):
"""
| Applying unsupervised learning appor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.