content stringlengths 5 1.05M |
|---|
#
# 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 us... |
from js_helper import _do_test_raw
def test_array_destructuring():
"""
Make sure that multi-level and prototype array destructuring don't cause
tracebacks.
"""
assert not _do_test_raw("""
[a, b, c, d] = [1, 2, 3, 4];
[] = bar();
""").failed()
assert not _do_test_raw("""
functio... |
import tensorflow as tf
import numpy as np
from pathlib import Path
# See https://www.tensorflow.org/tutorials/load_data/tfrecord
def _bytes_feature(value):
"""
Returns a bytes_list from a string / bytes. A string / bytes is considered a scalar by Tensorflow.
:param value: A String or a Byte list.
:t... |
from bpy.props import *
from bpy.types import Node
from arm.material.arm_nodes.arm_nodes import add_node
from arm.material.shader import Shader
from arm.material.cycles import *
if arm.is_reload(__name__):
import arm
arm.material.arm_nodes.arm_nodes = arm.reload_module(arm.material.arm_nodes.arm_nodes)
fr... |
DEBUG=True
ADMINDN="uid=admin,ou=admin,dc=example,dc=org"
ADMINPWD="admin"
LDAPURL='ldap://127.0.0.1:389'
USEROU="ou=people,dc=example,dc=org"
SALT="zAzwDJdiPhcUoSF"
|
_base_ = ['./mswin_par_small_patch4_512x512_160k_ade20k_pretrain_224x224_1K.py']
model = dict(
pretrained=\
'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window12_384.pth',
backbone=dict(
pretrain_img_size=384,
embed_dims=128,
depths=[2, 2, 18... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
import os.path
# replace with filetree once ready
RESOURCE_DIR = os.sep.join([
os.sep.join(os.path.split(__file__)[:-1]), "res/"])
from .widget import TreeWidget
from .lib import (PartialAction, keyDict, SelectionModelContainer, KeyState,
dropActionDict, ContextMenu) |
import datetime
import numpy as np
import sympy as sp
from utils.constants import *
from utils import racing_env
from system import vehicle_dynamics
from control import control, lmpc_helper
from planning import overtake_path_planner, overtake_traj_planner
from scipy.interpolate import interp1d
from pathos.multiprocessi... |
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
from spark_auto_mapper_fhir.fhir_types.list import FhirList
from spark_auto_mapper_fhir.fhir_types.string import FhirString
from spark_auto_mapper_fhir.extensions.extension_base import ExtensionBase
from spark_auto_mapper_fhir.base_types.fh... |
from strongr.core import Core
from strongr.core.domain.clouddomain import CloudDomain
from .wrapper import Command
class DestroyManyCommand(Command):
"""
Destroys a list of VMs in the cloud.
destroy:many
{machines* : The names of the VMs to be destroyed}
"""
def handle(self):
cloud... |
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import shutil
try:
import sqlite3
except ImportError:
from pysqlite2 import dba... |
import theano
import argparse
_floatX = theano.config.floatX
def str2bool(v):
return v.lower() in ('yes', 'true', 't', '1', 'y')
def get_args():
parser = argparse.ArgumentParser()
parser.register('type', 'bool', str2bool)
# Basics
parser.add_argument('-debug',
type='bo... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains functions and class related with maths
"""
from __future__ import print_function, division, absolute_import
import math
import struct
MAX_INT = 2 ** (struct.Struct('i').size * 8 - 1) - 1
def is_equal(x, y, tolerance=0.000001):
"""
Che... |
# Copyright 2015 Isotoma Limited
#
# 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... |
# /usr/bin/env python3
import csv
import time
from hashlib import sha1
from base64 import b32encode
from collections import OrderedDict, defaultdict
from operator import itemgetter
from pathlib import Path
import urllib.request
import urllib.error
import random
import socket
from contextlib import contextmanager
impor... |
#!/usr/bin/env python3
import os
import sys
import glob
import argparse
import subprocess
import logging
import traceback
import tempfile
import pandas as pd
from multiprocessing import Pool
def make_windows(args):
if args.chrom_sizes is not None:
makewindows_cmd = ['bedtools', 'makewindows', '-g', args.chrom_size... |
from Bagpipe.importer import pre_analyzed_importer
class SimProduct:
def __init__(self, *args, **kwargs):
self.pre_analyzed_db_name = ['kwargs']
self.pre_importer = pre_analyzed_importer.PreImporter(db_name=self.pre_analyzed_db_name)
def get_sim_product(self):
all_products = self.pre_... |
import re
from typing import List, Optional, Tuple, Callable
from aqt import mw
from anki.models import NoteType
from ..config_types import HTML, HTMLSetting, ScriptSetting
from ..stringify import stringify_for_template, get_condition_parser
from .minify import insert_minified, insert_unminified
def find_valid_fra... |
class Solution:
def __init__(self):
self.one_to_nineteen = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
self.tens = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'S... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2017 Pascual Martinez-Gomez
#
# 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 os.path
import datetime
import gofigure.parsers
import gofigure.events
class EnergyMechParser(gofigure.parsers.Parser):
"""
Implements support for EnergyMech-style logs.
These are always stored under file names like %s_%c_%Y%m%d.log and keep the
time in the lines so looking them up is trivial t... |
from datetime import datetime, timezone, timedelta
from django.db import models
from django.core.exceptions import ValidationError
from cinp.orm_django import DjangoCInP as CInP
from contractor.Building.models import Foundation, Structure
from contractor.fields import MapField
MAX_BOX_LIFE = 96 # in hours
cinp = C... |
# -*- coding: utf-8 -*-
import colander
class Experience(colander.MappingSchema):
startDate = colander.SchemaNode(colander.Date())
endDate = colander.SchemaNode(colander.Date(), missing=None)
class Highlights(colander.SequenceSchema):
highlight = colander.SchemaNode(colander.String(), missing=None)
c... |
# !/usr/bin/python
# coding: utf8
from xml.dom.minidom import parse
import xml.dom.minidom
import time
import pprint
import string
import sys
sys.path.append("..")
import argparse
import re
import os
import numpy as np
import torch
import torch.nn as nn
from utils import *
from math import log
import random
import jso... |
import browser_cookie3
import requests
from pathlib import Path
import urllib3
import argparse
from __constants.constants import *
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
######### AUTHOR - @AmmeySaini #########
######### Github Repo - https://github.com/AmmeySaini/Realme-AutoBuy #########... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import LongTensor
from fairseq import options, utils
from . import (
FairseqIncrementalDecoder, FairseqLanguageModel,
GapBertDecoder,
register_model, register_model_architecture,
)
from .fconv import Embedding
from .lstm import... |
import os
from subprocess import Popen, PIPE
from django.utils.datastructures import SortedDict
from django.utils.functional import memoize
from .utils import get_class
_filters = SortedDict()
_processes = SortedDict()
class BaseFilter(object):
method = None
options = {}
def __init__(self, *args, **k... |
""" Plot Dwell Time
This script will be useful for plotting existing dwell time files.
The calculation of dwell times, similar to diffusion coefficients, can often
take 10-30 min, depending on how many trajectories are analyzed. If a user
would rather configure plots on a pre-existing CSV files, they can do so here.
... |
from .models import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy import func
from geoalchemy2.shape import to_shape
from sqlalchemy.sql import select
from sqlalchemy import create_engine
import json
Base = declarative_base()
metadata = Base.metadata
engine = create_engine("postgresql://postgres:postgre... |
import pytest
from stp_core.loop.eventually import eventually
from stp_core.common.log import getlogger
from plenum.common.messages.node_messages import Nomination
from plenum.server.replica import Replica
from plenum.server.suspicion_codes import Suspicions
from plenum.test.delayers import delayerMsgTuple
from plenum... |
# Generated by Django 3.1.7 on 2021-04-03 11:42
from decimal import Decimal
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH... |
"""Reaction agent that use precomputed values in the OND protocol."""
from sail_on_client.agent.ond_reaction_agent import ONDReactionAgent
from sail_on_client.agent.pre_computed_detector import PreComputedONDAgent
import logging
from typing import Dict, Any, Tuple
log = logging.getLogger(__name__)
class PreCompute... |
import re
re.sub('&([^;]+);', r'&.\1.;', 'sdsfjsdlflsdfsdf&asdasd;dfsdfgsfdgfsd&dsfdsaf; &sfgfdgds;')
import htmlentitydefs
result = []
for x in a:
n = htmlentitydefs.codepoint2name.get(ord(x))
if n is not None: x = '&%s;' % n
result.append(x) |
from .posts import *
from .replies import * |
import itertools
from collections import OrderedDict
import torch
from util.image_pool import ImagePool
from . import context_nn, cpg
from . import networks
from .base_model import BaseModel
class CycleGANModel(BaseModel):
def name(self):
return 'CycleGANModel'
@staticmethod
def modify_commandl... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import papermill as pm
import pytest
import scrapbook as sb
# Unless manually modified, cv should be
# the name of the current jupyter kernel
# that runs on the activated conda environment
KERNEL_NAME = "cv"
OUTPUT_NOTEBOOK ... |
print('Luiz', 'Otávio', sep='-')
print('João', 'e', 'Maria', sep='-', end='###')
print('Ana ', 'e', 'Joana', sep='-')
nome = 'teste'
print('929', '610', '374', sep='.', end='-')
print('98')
|
import os, re, requests, json, weather, datetime, random, Baidu_Text_transAPI
from turtle import st
from urllib import parse
import os
import urllib.request
# 一些常量,只是为了敲代码快一点
sand_message_user = ""
return_user = ""
all_input = ()
event = ""
message_input = ""
count_number = 0
return_0 = "" # 一般无用,仅作接受
... |
import numpy as np
def rearrange_list(values, n):
r = len(values) % n
if r > 0:
rearranged_values = np.reshape(values[:-r], (-1, n))
else:
rearranged_values = np.reshape(values, (-1, n))
rearranged_values = rearranged_values.transpose()
rearranged_values = rearranged_values.tolist(... |
# Libraries
import logging
import numpy as np
from .RawDataHandler import RawDataHandler
from .NpDataHandler import NpDataHandler
# Constants
LOGGER = logging.getLogger(__name__)
"""
Default column in the data to look for messages
"""
COL_MESSAGES = 1
"""
Default column in the data to look for messages classes
"""
... |
import json
from unittest.mock import MagicMock
import pytest
pytest.importorskip("boto3")
import prefect
from prefect.tasks.aws import AWSSecretsManager
from prefect.utilities.configuration import set_temporary_config
@pytest.fixture
def mocked_boto_client(monkeypatch):
boto3 = MagicMock()
client = boto3.... |
import pybullet_envs
from stable_baselines3 import TD3_LABER
model = TD3_LABER('MlpPolicy', 'HumanoidBulletEnv-v0', verbose=1, tensorboard_log="results/long_TD3_LABER_HumanoidBullet/")
model.learn(total_timesteps=3000000)
|
from __future__ import unicode_literals
from utils import CanadianScraper, CanadianPerson as Person
from six.moves.urllib.parse import urljoin
COUNCIL_PAGE = 'http://www.city.sault-ste-marie.on.ca/Open_Page.aspx?ID=174&deptid=1'
def word_to_number(word):
words = ('one', 'two', 'three', 'four', 'five', 'six', 's... |
# The MIT License (MIT)
#
# Copyright (c) 2021
#
# 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, copy, modify, merge, pu... |
"""Contain the unit tests related to the views in app ``catalogs``."""
from django.http.request import HttpRequest
from django.test import TestCase
from teamspirit.catalogs.views import catalog_view
from teamspirit.core.models import Address
from teamspirit.profiles.models import Personal
from teamspirit.users.models... |
import streamlit as st
from src.utils import visual_def
from src.utils import uploaded_file
def app():
st.header("Advanced Exploratory Visual Data Analysis")
data = uploaded_file.read_datafolder()
try:
data_columns = data.columns
data_type = data.dtypes
visual = visual_def.Visual... |
"""Test NIST material data queries."""
import json
import os
from becquerel.tools import (
fetch_materials,
remove_materials_csv,
MaterialsError,
MaterialsWarning,
)
from becquerel.tools.materials_nist import convert_composition
import becquerel.tools.materials as materials
import becquerel.tools.mater... |
'''
Created on 28 de abr de 2020
@author: leonardo
Content: Classe Bomba.
'''
from componentes.jogo.objetos_dinamicos import ObjetosDinamicos
from componentes.jogo.thread_update import ThreadUpdate
from componentes.jogo.arbusto import Arbusto
from componentes.jogo.pedra import Pedra
class Bomba(ObjetosDinamicos):
... |
from django.conf.urls import url
import wzrd.games.consumers as consumers
websocket_urlpatterns = [
url(r'ws/games/(?P<session_name>[\w\d]+)$', consumers.GameSessionConsumer.as_asgi()),
]
|
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
from base_util import ErrorWithResponse
from attribute_helper import AttributeInterpreter, maybe_specific_mem, interpret_span_value
from condition import Comparator
from memory_values import MemoryColumnValue
from memory_attributes import ComparatorAttribute
# T... |
import itertools
import random
import string
from time import mktime, strptime, strftime, localtime
import re
import constantes
import generador_datos as gd
def restricciones_sql(parameters, column):
"""Comprueba las restricciones SQL.
:param parameters: lista con parámetros del tipo de dato.
:param colum... |
'''
Manage Azure CLI configuration.
'''
from .. pyaz_utils import _call_az
from . import param_persist
def set(local=None):
'''
Set a configuration.
Optional Parameters:
- local -- Set as a local configuration in the working directory.
'''
return _call_az("az config set", locals())
def get(... |
import os
import itertools
import platform
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), "mongomock", "__version__.py")) as version_file:
exec(version_file.read())
install_requires = ["sentinels", "six"]
if platform.python_version() < '2.7':
install_requires.app... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import json
import os
import numpy as np
from .. import data, misc
from ...tests.helper import remote_data
from ...extern import six
def test_... |
#!/usr/bin/env python
#
# 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 ... |
import requests
from bs4 import BeautifulSoup
terms = ['gay', 'LGBT', 'bisexual', 'homosexual']
for search_term in terms:
page = requests.get('https://theappstore.org/search.php?search=' + search_term + '&platform=software')
soup = BeautifulSoup(page.content, 'html.parser')
# print(soup.prettify())
# ... |
li = input().split()
dicti={}
for i in li:
if i not in dicti:
dicti[i]=1
else:
print(i) |
def func():
a=[3,57,83,24,7,9,322,1,5]
b=[]
while a:
m=a[0]
for x in a:
if x < m:
m=x
b.append(m)
a.remove(m)
return b
print(func())
|
# Author: Alexis M. Thornton
import os
from PIL import Image, ImageDraw, ImageFont
def run(dir,out_image):
try:
fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 20)
except:
fnt = ImageFont.load_default()
#get mut folders in the eVIPP output directories
mut_folders = [dI for dI in... |
# This class will house the api call to retrieve both fixture and general data about a given team.
import requests
import json
import jsonResponse
headers = {'X-Auth-Token': '0028d0d9a3554f72b77d6882eaa89681'}
def getAllCompetitions ():
url = "http://api.football-data.org/v1/competitions"
return form... |
import numpy as np
import pyqtgraph as pg
try:
import cupy as cp
pg.setConfigOption("useCupy", True)
except ImportError:
cp = None
try:
import numba
except ImportError:
numba = None
def renderQImage(*args, **kwargs):
imgitem = pg.ImageItem(axisOrder='row-major')
if 'autoLevels' not in ... |
# import numpy as np
import pip
import json
import sys
import platform
data = sys.stdin.read()
sys.stdout.write(data)
# print(sys.executable)
# print(platform.python_version())
# print('Hello World from python!', sys.version_info[0])
# def install(package):
# if hasattr(pip, 'main'):
# pip.main(['in... |
import numpy as np
def cosine_similarity(x, y):
return np.dot(x, y) / (np.sqrt(np.dot(x, x)) * np.sqrt(np.dot(y, y)))
# def cosine_similarity_batch_loop(unknown_face, known_faces):
# return np.array([
# cosine_similarity(unknown_face, known_face) for known_face in known_faces
# ])
def cosine_s... |
import numpy as np
import matplotlib.pyplot as plt
#initail velocity in m/s..
vInit = 0
#acceleration in m/s..
aG = 9.81
#coefficient of drag..
cw = 1.4
#air density in kg^-(m^3)..
q = 1.29
#area of drag producing surface..
ad = 4* np.pi
#number of runs..
f = 1000
#amount of kg the payload weights..
#this example will... |
"""
gru.py
Test if the GruNodeGene is implemented correctly
"""
import copy
import os
import unittest
from config import Config
from population.utils.genome_util.genes import GruNodeGene
def get_config(num_outputs=1):
"""Create and return the config object."""
cfg = Config()
cfg.genome.num_outputs = num... |
import os
import json
from six.moves.urllib.request import urlopen
from jose import jwt
AUTH0_DOMAIN = os.environ.get("AUTH0_DOMAIN")
AUTH0_API_ID = os.environ.get("AUTH0_API_ID")
def verify_token(token):
# Validate the token to make sure it's authentic
jsonurl = urlopen("https://"+AUTH0_DOMAIN+"/.well-known... |
"""
Tar Backup Plugin
"""
import logging
import os
from subprocess import Popen, list2cmdline
from tempfile import TemporaryFile
from holland.core.backup import BackupError
from holland.lib.compression import COMPRESSION_CONFIG_STRING, open_stream
LOG = logging.getLogger(__name__)
# Specification for this plugin
# ... |
import shelve
import os
from . import tools
MAIN_DIR = os.path.split(os.path.abspath(__file__))[0]
SHELVE_PATH = os.path.join(MAIN_DIR, 'high_score.txt')
class Scoreboard:
def __init__(self, screen):
self.score = '00000'
self.last_score = '00000'
self.high_score = '00000'
self.fon... |
"""
给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
"""
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
count, k = 0, 5
while n:
n... |
from pymongo import MongoClient
class DBApi(object):
def __init__(self, client=MongoClient("mongodb://localhost:27017/")):
self.client = client
self.db = client.workspace
def create_run(self, run):
run_id = run["run_id"]
if self.get_run(run_id) is not None:
raise ... |
#
# Copyright (c) 2015 Intel 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 ag... |
import pygame
from pygame.locals import *
# Define some colors
BLACK = (0, 0, 0)
WHITE = (245, 245, 245)
RED = (133, 42, 44)
YELLOW = (208, 176, 144)
GREEN = (26, 81, 79)
PLAYER = False
# Define grid globals
WIDTH = 20
MARGIN = 1
PADDING = 20
DOT = 4
BOARD = (WIDTH + MARGIN) * 14 + MARGIN
GAME_WIDTH = BOARD + ... |
from datetime import timedelta, datetime
from airflow.models.dag import DAG
from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator
from kubernetes.client import V1Pod, V1PodSpec, V1Container, V1EnvVar, V1ObjectMeta
dag = DAG(
dag_id="sparkpi",
default_args={
'owner': 'jac... |
import json
import click
from flask.cli import AppGroup
from flask_migrate import stamp
from flask_security.confirmable import confirm_user
from sqlalchemy import MetaData
from project import app, db
from project.api import scope_list
from project.init_data import create_initial_data
from project.models import (
... |
# Generated by Django 2.1.7 on 2019-05-22 05:43
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MailCheckMsg',
fields=[
('id', models.AutoF... |
from panda3d.core import LVector3f
from toontown.dna.DNAUtil import *
class DNABattleCell(object):
__slots__ = (
'width', 'height', 'pos')
COMPONENT_CODE = 21
def __init__(self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def __del_... |
import os
import zipfile
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
local_zip = './horse-or-human.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('./horse-or-human')
zip_ref.close()
# Directory with our ... |
# print(type('Napis'))
# print(type("Inny napis"))
# print(type(34))
# print(type(7.14))
# something = "Osiem"
# print(type(something))
# other = 50
# print(type(other))
# new_int = 40
# print(type(new_int))
# new_bool = True
# print(type(new_bool))
# new_float = 40.6
# print(type(new_float))
# new_string = ... |
#!usr/bin/env python3
from timeit import timeit
# When you create a list and append to it, Python needs to reallocate memory
# for the list. To avoid reallocation on every append, the list grows in fixed
# sizes. The sizes are zero, four, eight, 16, 25, etc. However, when we create
# a list with multiplication, Python... |
#!/usr/bin/env python
# coding=utf-8
# Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import base64
import datetime
import json
import logging
import os
import random
import sys
import unittest
... |
import re
from napalm_base import get_network_driver
from ncrawl import models, settings
class Poller(object):
def __init__(self, node=None):
if not isinstance(node, models.Node):
raise TypeError()
self.node = node
driver = get_network_driver(self.node.driver)
self.devi... |
# pylint: disable=bad-builtin
from email.utils import formatdate
from tempfile import TemporaryDirectory
from django.core.mail import EmailMessage, SafeMIMEText, SafeMIMEMultipart, make_msgid
from django.core.mail.utils import DNS_NAME
from django.core.mail.backends.locmem import EmailBackend as LocMemEmailBackend
fro... |
#importing models function
from django.db import models
# Create your models here.
# name, pageNumber, genre, and publishDate attributes
class Book(models.Model):
name = models.CharField(default="", max_length=1000)
pageNumber = models.IntegerField()
publishDate = models.DateField(default='') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 12 02:14:00 2020
@author: hassan99
"""
print("make clean")
print("make")
threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
powers = range(1, 9)
print("./sum 1 1 > sum.txt")
for thread in threads:
for power in powers:
input_sum = 10 ** power
... |
x = 5
x = x + 1
print(x)
|
import unittest
import tempfile
import shutil
import os
from bluespecrepl import bsvproject
class TestPyVerilatorBSV(unittest.TestCase):
def setUp(self):
self.old_dir = os.getcwd()
self.test_dir = tempfile.mkdtemp()
os.chdir(self.test_dir)
def tearDown(self):
os.chdir(self.old_... |
import english_uk
import symbols
from exit_code import ExitCode
ALL_CHARACTERS = set(english_uk.ENGLISH_UK_REMOVED_DUPES + symbols.SYMBOLS_REMOVED_DUPES)
ALL_CHARACTERS_VALID_FOR_NAME = set(english_uk.ENGLISH_UK_VALID_FOR_NAME_ONLY + symbols.SYMBOLS_VALID_FOR_NAME_ONLY)
def verify(input_str: str, verbose: bool = Tru... |
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
def load_dataset():
iris = load_iris()
return iris.data, iris.target
|
import math
import torch
import numpy as np
import utils.image_processing as ip
import utils.torch_complex as tc
import torch.fft as fft
def ASM_precal(slm_res, pix_pitch, wavelength, prop_dist, device,
linear_conv=True, dtype=torch.float64):
input_resolution = slm_res
if linear_conv:
i... |
#! /usr/bin/env python
import sys
import os
includeos_src = os.environ.get('INCLUDEOS_SRC',
os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))).split('/test')[0])
sys.path.insert(0,includeos_src)
from vmrunner import vmrunner
vm = vmrunner.vms[0];
def check_hex(lin... |
from django.urls import path
from .views import CMURLSearchView, CMKeywordSearchView, CMTagSearchView
urlpatterns = [
path(
"url_search/",
CMURLSearchView.as_view(),
name="cm_url_search",
),
path(
"tag_search/",
CMTagSearchView.as_view(),
name="cm_tag_searc... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-10-04 20:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('timesheets', '0002_auto_20171003_1408'),
]
operations = [
migrations.AlterF... |
# (c) 2019 Red Hat Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
---
author: Ansible Security Automation Team
httpapi : splunk
short_description: HttpApi Plu... |
from typing import TYPE_CHECKING, Optional, List
if TYPE_CHECKING:
from Platforms.Discord.main_discord import PhaazebotDiscord
from Utils.Classes.undefined import UNDEFINED
from Utils.Classes.contentclass import ContentClass
from Utils.Classes.discordusermedal import DiscordUserMedal
class DiscordUserStats(ContentCl... |
""" This script dumps all users. """
import M2Crypto
import os
import SOAPpy
import string
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib"))
import appscale_info
import constants
def get_soap_accessor():
""" Returns the SOAP server accessor to deal with application and users.
Returns... |
# The MIT License (MIT)
#
# Copyright (c) 2013 Russell Nakamura
#
# 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, cop... |
"""309. Best Time to Buy and Sell Stock with Cooldown
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
Say you have an array for which the ith element is the price of a given stock
on day i.
Design an algorithm to find the maximum profit. You may complete as many
transactions as you like
(... |
"""A fit is a collection of observables and parameters that can be used to
perform statistical analyses within a particular statistical framework.
Fits are instances of descendants of the `Fit` class (which is not meant
to be used directly)."""
import flavio
import numpy as np
from flavio.statistics.probability impor... |
from datetime import datetime
from django.db import models
# Create your models here.
class BBS(models.Model):
title = models.CharField(max_length=32)
content = models.TextField()
user_id = models.IntegerField(null=True)
add_time = models.DateTimeField(default=datetime.now)
def getUser(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.