content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.response import Response
from rest_framework import status
from perm.models import PerMisson
from ... | python |
import gc
import json
import warnings
import flask_restful
from eventlet import greenthread
from injector import CallableProvider, inject
from flask import Blueprint, Flask
from flask.templating import render_template_string
from flask.views import View
from nose.tools import eq_
from flask_injector import request, F... | python |
# -*- coding: utf-8 -*-
from validator import Validator
class VimLParserLint(Validator):
__filetype__ = 'vim'
checker = 'vimlparser'
args = ''
regex = r"""
.+?:
(?P<lnum>\d+):
(?P<col>\d+):
\svimlparser:\s
(?P<text>
(
... | python |
a = 4.9
b = 9.8
sum1 = a + b
print('resultado:', sum1)
| python |
from functools import reduce
from itertools import combinations
from operator import mul
from aocd import data as expense_report
entries = list(map(int, expense_report.splitlines()))
for part in (1, 2):
for combo in combinations(entries, part+1):
if sum(combo) == 2020:
print(f'Part {part}:',... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 18:50:45 2021
@author: patrick
"""
from .Facebook_Chat_Analysis import *
| python |
"""Module for the base objects of the abstract argumentation frameworks."""
from .relation import RelationType
from .relation import Relation
from .premise import FallacyType
from .premise import Premise
from .graph import Graph
from .extension import Extension
| python |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped, Quaternion
from mavros_msgs.srv import CommandBool, CommandTOL, SetMode, SetModeRequest
from mavros_msgs.msg import State
import time
from tf.transformations import quaternion_from_euler
flight_alt = 1.0 # (m)
class TakeOffLand():
def _... | python |
from flask import ( g, redirect, url_for )
from tmc.db import get_db, make_dicts
# Get list of all industries available in the database.
def get_industries():
db = get_db()
try:
db.row_factory = make_dicts
query = db.execute(
'SELECT id as db_id, industry_name as Industry FROM indu... | python |
'''
Miscellaneous math functions.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
def matrix_sqrt(X=None, symmetric=False, inverse=False, eigs=None):
'''Returns the matrix square root of X.
Arguments:
`X` (square class::`numpy.ndarrray`)
... | python |
import tkinter as tk
def get_line_numbers():
output = ''
row, col = text_editor.index("end").split('.') #row give the no of row in text
#print(int(row)-1)
for i in range(1, int(row)):
output += str(i) + '\n' #making a string with row no. with \n(next line)
#print(output)
ret... | python |
# -*- encoding=utf8 -*-
__author__ = "srz_zumix"
sys.path.append(r"../pmbase")
from airtest.core.api import *
from pmbase import PmBase
auto_setup(__file__)
# adb = ADB()
# def update():
# print adb.shell('dumpsys battery')
sleep_mul = 1
pm = PmBase(sleep_mul)
pm.setup()
def pm_sleep(s):
pm.pm_sleep(s)
d... | python |
# coding=utf8
from __future__ import unicode_literals, absolute_import, division, print_function
"""
This is the SpiceBot AI system. Based On Chatty cathy
"""
from sopel.tools import Identifier
from sopel.config.types import StaticSection, ListAttribute, ValidatedAttribute
import os
import tempfile
import aiml
from ... | python |
"""
TODO TESTS:
- Syntax errors,
- general tests
"""
from helper import (
ValueChecker,
FlaskValueCheckerSyntaxError,
FlaskValueCheckerValueError,
)
import random
import string
import pytest
import io
test_restriction_code = """
# some simple data for tests here
firstName : str/lenlim(5, 15) #... | python |
import hashlib
string1 = 'Teste inicial'.encode('utf-8')
string2 = 'Teste inicial'.encode('utf-8')
hash1 = hashlib.new('ripemd160')
hash1.update(string1)
hash2 = hashlib.new('ripemd160')
hash2.update(string2)
print("-" * 60)
print(hash1.hexdigest())
print(hash2.hexdigest())
if hash1.digest() == hash2.digest(... | python |
from django.conf.urls import url
import lessons.views
urlpatterns = (
url(r'^create/(?P<course_id>\d+)$', lessons.views.schedule_create_page,
name="lessons.views.schedule_create_page"),
url(r'^edit/(?P<lesson_id>\d+)$', lessons.views.schedule_edit_page,
name="lessons.views.schedule_edit_page"),... | python |
import warnings
import numpy as np
from skimage.restoration import denoise_wavelet
def apply_rolling_window(mainchunk: np.array, meterchunk: np.array, window_size: int):
if not window_size:
raise Warning('Window size is not defined.')
indexer = np.arange(window_size)[None, :] + np.arange(len(mainchun... | python |
#pylint: disable=line-too-long,broad-except
"""Calculates total time from calendar events, grouped by an event attribute.
Usage:
calcatime -c <calendar_uri> [-d <domain>] -u <username> -p <password> <timespan>... [--by <event_attr>] [--include-zero] [--json] [--debug]
Options:
-h, --help ... | python |
"""
db_fun.py
This module contains helper functions for database entry creation.
"""
from models import Resource, Category
from datetime import datetime
def get_or_create(session, model, **kwargs):
"""
Determines if a given record already exists in the database.
Args:
session: The database se... | python |
#
# 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... | python |
#!/usr/bin/env python3
import sys
from setuptools import setup, find_packages
from urllib.parse import urlparse
with open('requirements.txt', 'r') as f:
install_requires = []
dependency_links = []
append_version = '-' + str(sys.maxsize)
requirements = [ line.strip() for line in f ]
for requireme... | python |
from flask import session, request
from flask_restful import Resource, reqparse, inputs, abort
from api.common.database import database
from api.common.utils import checkTag, checkTime, checkTel
import json
import requests
'''
### sendOfflineCapsule
Use this method to send offline capsule.
HTTP Request Method: **POST... | python |
""" Read a set of input files for the child oids
and generate a SQL file that queries for the master
records changed by those OID. This one uses an IN
clause instead of the simple query to test relative
performance of the two
I am using the therory that runing the commands
directly from psql should yield
the h... | python |
""""""
import os
import sys
import uuid
import bz2
import pickle
import traceback
import zlib
import json
from abc import ABC
from copy import copy
from typing import Any, Callable
from logging import INFO, ERROR
from datetime import datetime
from vnpy.trader.constant import Interval, Direction, Offset, Status, OrderTy... | python |
# Copyright 2017, Wenjia Bai. 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 applicable law or ... | python |
# coding:utf-8
from lxml import etree
import requests
import config
def checkProxyType(selfip, proxies):
'''
用来检测代理的类型,突然发现,免费网站写的信息不靠谱,还是要自己检测代理的类型
:param proxies: 代理(0 高匿,1 匿名,2 透明 3 无效代理
:return:
'''
try:
r = requests.get(url='https://incloak.com/ip/', headers=config.get_header(), ... | python |
import torch
import torch.nn as nn
class FocalLoss(nn.Module):
def __init__(self,gamma=2,eps=1e-7,size_average=True):
super(FocalLoss,self).__init__()
self.gamma = gamma
self.eps = eps
self.size_average = size_average
def forward(self,prob,labels):
p_t = prob*labels + ... | python |
#Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços,
#na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular.
Tabela = ('Lapís', 1.75,
'Borracha', 2,
'Caderno', 15.90,
'Estojo', 25,
'Transferidor', 4.20,
... | python |
import maya.cmds as mc
import copy
def setDrivenKeyToRemapValue(animCurve,remapValueNode='',interpType=3,deleteAnimCurve=True,lockPosition=True,lockValue=False):
'''
Convert a set driven key setup to a remapValue node.
Each key on the animCurve node is represented as widget on the remapValue ramp control.
Incoming... | python |
import numpy as np
from keras.models import Sequential
from keras.layers import Dense,Activation,Flatten,Dropout
from keras.layers import Conv2D,MaxPooling2D
from keras.callbacks import ModelCheckpoint
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
data=np.load('data.... | python |
import zipfile
import os
from time import gmtime, strftime
from helper import utility
from lxml import etree
"""
MIT License
Copyright (c) 2018 Chapin Bryce, Preston Miller
Please share comments and questions at:
https://github.com/PythonForensics/Learning-Python-for-Forensics
or email pyforcookbook@gmail.com
Pe... | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from app import db
age_func = db.Table('age_func',
db.Column('id', db.Integer, primary_key=True, autoincrement=True),
db.Column('age_id', db.Integer, db.ForeignKey('age_group.id'), nullable=False),
db.Column('fun... | python |
# Tool Imports
from bph.tools.windows.nircmd import BphNirCmd as NirCmd
# Core Imports
from bph.core.server.template import BphTemplateServer as TemplateServer
from bph.core.session import BphSession as Session
session = Session(project_name='blackhat_arsenal_2019')
session.start()
templateserver = Templat... | python |
from sudachipy import dictionary
from sudachipy import tokenizer
from sudachipy.plugin import oov
from kuro2sudachi.normalizer import SudachiCharNormalizer
import jaconv
import fileinput
import argparse
import json
import os
import re
mode = tokenizer.Tokenizer.SplitMode.C
parser = argparse.ArgumentParser(
descr... | python |
###############################################################################
#
# Copyright (c) 2018, Henrique Morimitsu,
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions o... | python |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(name='dynamicmultithreadedexecutor',
version='1.0.2',
description='Dynamic Multi-threaded Executor',
author='Kevin McCabe',
author_email='csmp@hotmail.com',
url='https://github.com/gumpcraca/dynamicmultithreadedexecu... | python |
def EscreverArquivoRelatorio(tabelaDados, somaMegaBytes, dadosMedio):
'''Função para escrever o relatorio final do problema'''
arquivo_final = open('relatório.txt', 'w')
arquivo_final.write('ACME Inc. Uso do espaço em disco pelos usuários')
arquivo_final.write('\n')
arquivo_final.write('-' * 70)
a... | python |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests.common import TransactionCase
class TestPointOfSale(TransactionCase):
def setUp(self):
super(TestPointOfSale, self).setUp()
# ignore pre-existing pricelists for the purpose of this ... | python |
class TensorflowModelWrapper:
def __init__(self):
self._model = None
def set_model(self, model):
self._model = model
def forward(self, input_):
return self._model.predict(input_)
def __call__(self, *args, **kwargs):
return self._model.predict(*args, **kwargs)
| python |
"""
Partial Entropy Decomposition with the Hcs measure from Ince (2017)
https://arxiv.org/abs/1702.01591
"""
from __future__ import division
import numpy as np
from itertools import combinations
from .pid import BasePID
from .lattice import pid_lattice
from .. import modify_outcomes
from ..algorithms import maxent... | python |
from unittest import TestCase
import numpy as np
from pyfibre.tests.probe_classes.utilities import generate_probe_graph
from pyfibre.tests.dummy_classes import DummyGraphSegment
from pyfibre.tests.probe_classes.objects import ProbeGraphSegment
class TestBaseGraphSegment(TestCase):
def setUp(self):
sel... | python |
"""Hack route cipher sent by Abraham Lincoln."""
from itertools import combinations
from src.ch03.c1_anagram_generator import split
def get_factors(integer: int) -> list:
"""Get factors of integer.
Calculate factors of a given integer.
Args:
integer (int): Number to get factors of.
Returns:... | python |
from django.core.files.storage import FileSystemStorage
class MediaStorage(FileSystemStorage):
pass
class ZarrStorage(FileSystemStorage):
pass
class FilesStorage(FileSystemStorage):
pass
class LocalStorage():
media = MediaStorage
zarr = ZarrStorage
files = FilesStorage | python |
from django.urls import path, include
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.Home.as_view()),
path('posts/', include([
path('create/', views.CriarPost.as_view(), name='criar-post'),
path('<slug:titulo>/', views.VerPost.as_view(), name="ver-post"),
])),
p... | python |
import keras
import keras.backend as K
from keras.preprocessing import sequence
from keras.datasets import imdb
from keras.models import Sequential, Model
from keras.layers import \
Dense, Activation, Conv2D, MaxPool2D, Dropout, Flatten, Input, Reshape, LSTM, Embedding, RepeatVector,\
TimeDistributed, Bidirect... | python |
import asyncio
import ffmpeg
# Reason: Following export method in __init__.py from Effective Python 2nd Edition item 85
from asynccpu import ProcessTaskPoolExecutor # type: ignore
# Reason: Following export method in __init__.py from Effective Python 2nd Edition item 85
from asyncffmpeg import FFmpegCoroutineFactor... | python |
import argparse
import csv
import inspect
import os
import re
import warnings
from abc import ABCMeta, abstractmethod
from contextlib import contextmanager
from pathlib import Path
from time import time
import pandas as pd
warnings.filterwarnings("ignore")
REPO = Path(__file__).resolve().parents[2]
@contextmanager... | python |
# -*- coding: utf8 -*-
from ..core.Oracle import Oracle
from ..utils.ColorString import ColorString
from ..utils.utils import *
from .Config import Config
import argparse
import re
import os
def install_jdk():
Oracle.install_jdk()
def uninstall_jdk():
Oracle.execute_uninstall_jdk()
def rsync_server_core_data... | python |
import unittest
import numpy as np
from nptest import nptest
class Test_ShapeBaseTests(unittest.TestCase):
def test_atleast_1d(self):
a = np.atleast_1d(1.0)
print(a)
print("**************")
x = np.arange(9.0).reshape(3,3)
b = np.atleast_1d(x)
print(b)
pri... | python |
import os
from behave import *
from copy import deepcopy
from lxml import etree
import tempfile
import uuid
import logging
from pds_doi_service.core.entities.exceptions import InputFormatException, CriticalDOIException
from pds_doi_service.core.util.doi_xml_differ import DOIDiffer
from pds_doi_service.core.actions.d... | python |
#!/usr/bin/python
# Copyright 2018 Blade M. Doyle
# 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... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 5 19:05:19 2018
@author: myoussef
"""
import ringity
import unittest
import numpy as np
import networkx as nx
class TestConversions(unittest.TestCase):
def test_ddict2dict2ddict_unweighted(self):
E = nx.erdos_renyi_graph(100,0.17)
... | python |
ballresponse = [
'Yes', 'No', 'Take a wild guess...', 'Very doubtful',
'Sure', 'Without a doubt', 'Most likely', 'Might be possible',
"You'll be the judge", 'no... (╯°□°)╯︵ ┻━┻', 'no... baka',
'senpai, pls no ;-;'
]
owos = [
"✪w✪", "¤w¤", "∅w∅", "⊗w⊗", "⊕w⊕", "∞w∞", "∆w∆", "θwθ", "δwδ", "①w①", "②w②", "③w③"... | python |
import unicodedata
from collections import defaultdict
from itertools import zip_longest
from .porter import Stemmer
def _normalize(s):
return unicodedata.normalize("NFKD", s)
def _check_type(s):
if not isinstance(s, str):
raise TypeError("expected str or unicode, got %s" % type(s).__name__)
def l... | python |
#!/usr/bin/python
def findstem(arr):
# Determine size of the array
n = len(arr)
# Take first word from array
# as reference
s = arr[0]
l = len(s)
res = ""
for i in range(l):
for j in range(i + 1, l + 1):
# generating all possible substrings
# of our ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################################################
# The MIT License
# Copyright (c) 2014 Hannes Schulz, University of Bonn <schulz@ais.uni-bonn.de>
# Copyright (c) 2013 Benedikt Waldvogel, University of Bonn <mail@bwaldvog... | python |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# -*- coding: utf-8 -*-
#
# Last modified: Tue, 23 Jan 2018 23:39:11 +0900
#
# try import libsbml
try:
from libsbml import ASTNode
from libsbml import AST_PLUS
from libsbml import AST_MINUS
from libsbml import AST_TIMES
from libsbml import formul... | python |
import threading
import Pyro4
class NameServerInThread(threading.Thread):
def __init__(self):
super(NameServerInThread, self).__init__()
self.name_server_daemon = None
@staticmethod
def is_name_server_started():
try:
ns = Pyro4.locateNS()
return True
... | python |
'''
Wrapper for bert embeddings
'''
import numpy as np
import torch
from pytorch_pretrained_bert import BertTokenizer, BertModel
class BertEmbeddings:
def __init__(self, model_name='bert-base-uncased', cache_dir=None, max_seq_length=64, max_batch_size=64, stats_count=False):
'''
:param normalize:... | python |
"""Copyright 2014 Google Inc. 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 applicable law or agreed to in ... | python |
from django.contrib import admin
from .models import ChatUser
admin.site.register(ChatUser)
| python |
from config import *
from dbMgr import *
@app.before_request
def clear_trailing():
rp = request.path
if rp != '/' and rp.endswith('/'):
return redirect(rp[:-1])
@app.route('/test')
def default():
return render_template('login.html')
@app.before_request
def before():
logging.info("IP addr... | python |
import doctest
import pytest
if __name__ == "__main__":
doctest.testmod()
pytest.main()
| python |
"Iterative Solvers for Sparse Linear Systems"
#from info import __doc__
from .iterative import *
from .minres import minres
from .lgmres import lgmres
from .lsqr import lsqr
from .lsmr import lsmr
from ._gcrotmk import gcrotmk
from .tfqmr import tfqmr
__all__ = [
'bicg', 'bicgstab', 'cg', 'cgs', 'gcrotmk', 'gmres... | python |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... | python |
"""Tests for reloading generated pyi."""
from pytype import utils
from pytype.pytd import pytd
from pytype.tests import test_inference
class ReingestTest(test_inference.InferenceTest):
"""Tests for reloading the pyi we generate."""
def testContainer(self):
ty = self.Infer("""
class Container:
... | python |
import time
import numpy as np
from pycqed.analysis import analysis_toolbox as a_tools
import pycqed.analysis_v2.base_analysis as ba
# import dataprep for tomography module
# import tomography module
# using the data prep module of analysis V2
# from pycqed.analysis_v2 import tomography_dataprep as dataprep
from pycqed... | python |
from sys import modules
from unittest.mock import MagicMock
mock_sys_info = modules["pitop.common.sys_info"] = MagicMock()
mock_sys_info.is_pi = MagicMock(return_value=False)
mock_curr_session_info = modules["pitop.common.current_session_info"] = MagicMock()
mock_curr_session_info.get_first_display = MagicMock(return... | python |
import os
import boto3
AWS_ENDPOINT_URL = os.getenv("AWS_ENDPOINT_URL", None)
def handler(event, context):
client = boto3.client("s3", endpoint_url=AWS_ENDPOINT_URL)
client.create_bucket(Bucket="foo")
client.create_bucket(Bucket="bar")
buckets = client.list_buckets()["Buckets"]
l = []
for buck... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-17 15:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20170509_1559'),
('pfb_analysis', '0025_auto_20170511_1244'),
... | python |
from rest_framework.exceptions import APIException
from rest_framework import status
class InvalidParameterException(APIException):
"""Exception for invalid request parameters."""
status_code = status.HTTP_400_BAD_REQUEST
default_detail = 'Request contained an invalid parameter'
default_code = 'invali... | python |
import arff
import argparse
import json
import logging
import openmlcontrib
import openmldefaults
import os
import sklearnbot
def parse_args():
metadata_file = '/home/janvanrijn/experiments/sklearn-bot/results/results__500__svc__predictive_accuracy.arff'
parser = argparse.ArgumentParser(description='Creates a... | python |
"""
This module executes the string matching between a input sequence T and an
pattern P using a Finite State Machine.
The complexity for building the transition function is O(m^3 x |A|) where A is the
alphabet. Since the string matching function scan the input sequence only once,
the total complexity is O(n + m^3 x |A... | python |
import tkinter
window = tkinter.Tk()
window.title("Test")
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side="bottom")
# label = tkinter.Label(window, text="Hello, world!").pack()
btn1 = tkinter.Button(top_frame, text="B1", fg="red").pack()
btn2 = tkinter.Button(top_frame, text="... | python |
from setuptools import setup, Extension
with open('README.md', 'r') as f:
long_description = f.read()
meow_ext = Extension(
'meowhash.cpython',
# define_macros=[('MEOW_HASH_256', '0'), ('MEOW_HASH_512', '0')],
sources=['meowhash/cpython.c'],
extra_compile_args=['-mavx512f', '-mavx512vl', '-maes',
... | python |
# Copyright The IETF Trust 2007-2019, All Rights Reserved
#
from django.contrib.sitemaps import GenericSitemap
from ietf.ipr.models import IprDisclosureBase
# changefreq is "never except when it gets updated or withdrawn"
# so skip giving one
queryset = IprDisclosureBase.objects.filter(state__in=('posted','removed'))... | python |
from grpclib.exceptions import GRPCError
from insanic.exceptions import APIException
from interstellar.exceptions import InvalidArgumentError
from grpc_test_monkey_v1.monkey_grpc import ApeServiceBase, MonkeyServiceBase
from grpc_test_monkey_v1.monkey_pb2 import ApeResponse, MonkeyResponse
class PlanetOfTheApes(Ap... | python |
#!/usr/bin/env python
# Copyright (c) 2005-2011 Grameen Foundation USA
# 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.... | python |
def vatCal(totalPrice):
result = totalPrice + (totalPrice*7/100)
return result
TotalPrice = int(input("Put your price : "))
print("Your total price is",vatCal(TotalPrice)) | python |
import angr
from angr.sim_type import SimTypeInt
######################################
# getchar
######################################
class getchar(angr.SimProcedure):
def run(self):
self.return_type = SimTypeInt(32, True)
data = self.inline_call(
# TODO: use a less private ge... | python |
#!/usr/bin/env python
import sys
sys.path.insert(0, '..')
import glob
import numpy as np
from dotmap import DotMap
from simpleplotlib import plot
from parse_logs import parse_hdfs_logs, parse_hdfs_throughput
bytes_units = 2.0**-30
types = ['HDFS+static', 'HDFS+resize', 'HDFS+reTCP', 'reHDFS+static',
'reHDF... | python |
'''
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related docu... | python |
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import datetime
from keras im... | python |
from setuptools import setup
version = '1.0.2'
setup(
name='django-mobi2',
version=version,
keywords='Django UserAgent',
description='Django middleware and view decorator to detect phones and small-screen devices',
long_description=open('README').read(),
url='https://github.com/django-xxx/dj... | python |
import pickle
from tqdm import tqdm
import numpy as np
def save_stereotypes(animate_file, text_file, out_file):
"""
Save list of words that are stereotyped towards men or women
:param animate_file: list of noun pairs
:param text_file: file to test words counts on
:param out_file: output file
"... | python |
nome = str(input('Digite o nome: ')).strip()
caps = nome.upper()
truefalse = 'SILVA' in caps
print('Há SILVA no nome?\n', truefalse)
| python |
# %%
import numpy as np
from scipy import spatial
x, y = np.mgrid[0:4, 0:4]
points = np.c_[x.ravel(), y.ravel()]
tree = spatial.cKDTree(points)
tree.query_ball_point([2, 0], 1)
tree.query_ball_point(points, 1)
# %%
tree.query_ball_tree(points, 1) | python |
# This is a log file. It is saved as .py so that the following notebooks can easily import it and use its information.
# started at: 2022.03.03-15:28:15
| python |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
import sys
import pyauto_functional # Must come before pyauto (and thus, policy_base).
import policy_base
sys.path.append('/u... | python |
"""Unit test for the data_tuils module."""
import pytest
import candle
@pytest.mark.skip(reason="used by load_Xy_data_noheader")
def test_to_categorical():
pass
@pytest.mark.skip(reason="used by load_Xy_data2")
def test_convert_to_class():
pass
@pytest.mark.skip(reason="used by impute_and_scale_array")
... | python |
import numpy as np
import scipy.optimize as so
import cv2
from . import cfilter, cresampler, clz4, report
from .struct import *
_LZ4_COMPRESSION_LEVEL = 9
def applyBestIntraCompression(img, dropThreshold, minRetSize, fastDecodeMode = 2):
h, w, nChannel = img.shape
def _addEx(filterModeList, baseMeth... | python |
import math
import numpy as np
from datetime import datetime
startTime = datetime.now()
natural = range(1, 500000)
# Get list of prime numbers
def prime_list(max_prime):
primes = range(2, max_prime)
length = len(primes)
for idx in range(len(primes)):
p = primes[idx]
if p == 0:
... | python |
# http://codeforces.com/contest/268/problem/C
n, m = map(int, input().split())
d = min(n, m)
print(d + 1)
for i in range(d + 1): print("{} {}".format(d-i, i)) | python |
import numpy as np
from swarm import metrics
import pytest
# Example y with 11 points from -1.5 to 1.5.
y = np.array(
[
-0.997495,
-0.9320391,
-0.78332686,
-0.5646425,
-0.29552022,
0.0,
0.29552022,
0.5646425,
0.78332686,
0.9320391,
... | python |
import numpy as np
from numpy.random import uniform
from veneer.pest_runtime import *
import pyapprox as pya
from scipy.stats import uniform
from functools import partial
from pyapprox.adaptive_sparse_grid import max_level_admissibility_function
from pyapprox.adaptive_polynomial_chaos import variance_pce_refinement_in... | python |
# Copyright © 2019 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... | python |
#!/usr/bin/env python3
#fileencoding: utf-8
#-----------------------------------------------#
# python standard library
#-----------------------------------------------#
import calendar
import csv
from enum import Enum
from datetime import datetime as dt
#-----------------------------------------------#
# pip
#------... | python |
#!/usr/bin/env python
# coding: utf-8
from collections import namedtuple
class IDBase(str):
_attrs = (
# ('server_id', 0, 12, ServerID),
# ('_non_attr', 12, 13, validator),
# ('mountpoint_index', 13, 16, MountPointIndex),
# ('port', 13, 16, _port),
)
_str_len = 0
_t... | python |
"""
Test execution of at and cron style scheduler policies when group has updates
"""
from test_repo.autoscale.fixtures import AutoscaleFixture
from time import sleep
class UpdateSchedulerScalingPolicy(AutoscaleFixture):
"""
Verify update scheduler policy
"""
@classmethod
def setUpClass(cls):
... | python |
# coding: utf-8
"""
CardPay REST API
Welcome to the CardPay REST API. The CardPay API uses HTTP verbs and a [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) resources endpoint structure (see more info about REST). Request and response payloads are formatted as JSON. Merchant uses API to c... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.