content stringlengths 5 1.05M |
|---|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from __future__ import print_function
import os
import sys
import re
import logging
import unicodedata
from codecs import open
from random import shuffle, randint, choice
replacement_pattern = re.compile(ur'\$\{(?P<token>[^}]+)\}')
# iOS 11 + Android 26
mobile_safe_pattern = re.compile(ur'[\u0000-\u0377\u037a-\u037f\... |
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
items = models.ManyToManyField('self', blank=True)
private = models.BooleanField(default=True)
def __unicode__(self):
return self.name
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import division
from funcy import partial
from testing import *
from pyecs import *
from pycompupipe.components import GuiElement
class TestGuiElement():
def test_usage(self):
e = Entity()
g = e.add_component(GuiElement())
e.... |
"""
Playing games with a package's __name__ can cause a NullPointerException.
"""
import support
import test049p
del test049p.__name__
hasattr(test049p, 'missing')
|
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import contextlib
import os
import re
import shutil
from textwrap import dedent
from pants.base.build_environment import get_buildroot
from pants.util.contextutil import temporary_dir
fro... |
import os
import json
# from sys import last_traceback
# from typing_extensions import OrderedDict
from flask import Flask, request, redirect, url_for, session, render_template
from authlib.integrations.flask_client import OAuth
from datetime import timedelta
from flask_sqlalchemy import SQLAlchemy
from flask_migrate ... |
from pynput.keyboard import Key, Listener
currently_pressed_key = None
def on_press(key):
global currently_pressed_key
if key == currently_pressed_key:
print('{0} repeated'.format(key))
else:
print('{0} pressed'.format(key))
currently_pressed_key = key
def on_release(key):
glo... |
"""
lazy - Decorators and utilities for lazy evaluation in Python
Alberto Bertogli (albertito@blitiri.com.ar)
"""
class _LazyWrapper:
"""Lazy wrapper class for the decorator defined below.
It's closely related so don't use it.
We don't use a new-style class, otherwise we would have to implement
stub m... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Test object owner of comments."""
from collections import OrderedDict
import ddt
from ggrc.models import Assessment, AccessControlList, Revision, all_models
from integration.ggrc import api_helper
from i... |
chave = 9999
while True:
chave = input().split()
if chave == ["0"]:
break
medida1, medida2, percent = map(int, chave)
terreno = ((medida1 * medida2) * 100 / percent) ** 0.5
print(int(terreno))
|
# Copyright 2015 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.
"""Classes representing the monitoring interface for tasks or devices."""
import base64
import httplib2
import json
import logging
import socket
import tra... |
class LinksDataProvider:
def __init__(self, links):
self.links = links if links else []
def get_links(self):
return self.links
|
from collections import ChainMap
import arcade
from arcade import Texture
from arcade.experimental.uistyle import UIFlatButtonStyle
from arcade.gui.widgets import UIInteractiveWidget, Surface
class UITextureButton(UIInteractiveWidget):
"""
A button with an image for the face of the button.
:param float ... |
# -*- coding: utf-8 -*-
import wx
import OnlineStatus
from datetime import datetime
class DialogPanel(wx.Panel):
def __init__(self, parent, photo, title, friendphoto, text, date, status):
wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.Size(290, -1), wx.TAB_TRAVERSAL)
sizer = wx.BoxSiz... |
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render, redirect
from .models import CarDealer, CarModel, CarMake
from .restapis import ge... |
from typing import Tuple
from .utils import (
SafetyException,
_calculate_M,
_calculate_x,
_generate_random_bytes,
_get_srp_generator,
_get_srp_prime,
_Hash,
_pad,
_to_int,
)
class EvidenceException(Exception):
"""
Exception raised when server evidence key does not match.
... |
#!/usr/bin/python
# coding: utf-8
from wand.image import Image
from PIL import Image as PI
import pyocr
import pyocr.builders
import io
import sys
import argparse
import time
from tesserocr import PyTessBaseAPI, PSM, RIL
import tesserocr
import os
import re
class LocalOCR(object):
def __init__(self, ocr_langua... |
"""Module to manage background export task."""
import logging
import os
from background_task import background
from apps.users.models import User
from .export import JekyllSiteExport
from .models import Manifest
LOGGER = logging.getLogger(__name__)
@background(schedule=1)
def github_export_task(
manifest_pid... |
import random
import pygame
pygame.init()
class Button():
def __init__(self):
self.textBoxes = {}
#----Clicked In----
def clickedIn(self,x,y,width,height):
global mouse_state, mouse_x, mouse_y
if mouse_state == 1 and mouse_x >= x and mouse_x <= (x + width) and mous... |
from Coordinate import Coordinate
from datetime import *
import time
# Class node
class Node(object):
# Number of pickup/delivery nodes
n_nodes = 1
# Number of depots
d_nodes = 1
def __init__(self, type, id, x, y, demand):
self.type = type
self.id = id
s... |
def sum_func(a, *args):
s = a+sum(args)
print(s)
sum_func(10)
sum_func(10,20)
sum_func(10,20,30)
sum_func(10, 20, 30, 40)
|
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy.utils.decorators import format_doc
from astropy.coordinates.baseframe import base_doc
from .baseradec import BaseRADecFrame, doc_components
__all__ = ['ICRS']
@format_doc(base_doc, components=doc_components, footer=... |
# coding: utf-8
# In[21]:
from functools import reduce
# In[24]:
def factor(x):
listx=[z for z in range(1,x+1)]
fun_la=lambda a,b: a*b
zz=reduce(fun_la,listx)
print(zz)
# In[26]:
factor(4)
# In[ ]:
|
import argparse
import abc
from typing import List, Any, Optional, Dict
from pedtools.commands.hookspecs import PedtoolsPlugin
# From https://stackoverflow.com/questions/44542605/python-how-to-get-all-default-values-from-argparse
def get_argparse_defaults(parser):
defaults = {}
for action in parser._actions:
... |
names = ['BBB','OOO','PPP','CCC']
salaries = [3000,2000,4500,8000]
aDict = dict(zip(names,salaries))
print(aDict) |
expected_output = {
"lisp_router_instances": {
0: {
"lisp_router_id": {
"site_id": "unspecified",
"xtr_id": "0x730E0861-0x12996F6D-0xEFEA2114-0xE1C951F7",
},
"lisp_router_instance_id": 0,
"service": {
"ipv6": {
... |
#!/bin/python
import math
import os
import random
import re
import sys
# Complete the twoStrings function below.
def twoStrings(s1, s2):
#Converting the strings to a set in both cases.
s1 = set(s1)
s2 = set(s2)
common_substring = set.intersection(s1 , s2)#This function checks the common s... |
import sys
sys.path.append("../")
from shapely.geometry import LineString
import datetime as dt
import Utilities
import plots
import doc
import numpy as np
import streamlit as st
from hydralit import HydraHeadApp
import logging
class JamClass(HydraHeadApp):
def __init__(self, data, fps):
self.data = data... |
from h2pubsub import Server
Server(address='0.0.0.0', port=443).run_forever()
|
from __future__ import print_function
import tensorflow as tf
import keras
from tensorflow.keras.models import load_model
from keras import backend as K
from keras.layers import Input
import numpy as np
import subprocess
from tensorloader import TensorLoader as tl
import matplotlib.pyplot as plt
from matplotlib.backend... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: schema.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf... |
import unittest
import EvenFibonacciNumbers
class TestEvenFib(unittest.TestCase):
def test_base(self):
# 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
self.assertEqual(EvenFibonacciNumbers.sum_even_fib(55), 2+8+34)
if __name__ == '__main__':
unittest.main()
|
from models.contact import Contact
import random
import string
import getopt
import sys
import os.path
import jsonpickle
__author__ = 'pzqa'
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/co... |
from browser import document as doc
from browser import window
from browser import alert
from browser.html import *
# globals #########################
refr = False
geo = window.navigator.geolocation
watchid = 0
img = doc["world_map"]
container = doc["container"]
print(img.abs_left, img.abs_top)
projection = window.... |
import pandas as pd
# a list of strings
x = ['Python', 'Pandas','numpy']
# Calling DataFrame constructor on list
df = pd.DataFrame(x)
print(df)
|
"""Top level for tools."""
from .autocorrelation import compute_morans_i
from .branch_length_estimator import IIDExponentialBayesian, IIDExponentialMLE
from .coupling import compute_evolutionary_coupling
from .parameter_estimators import (
estimate_missing_data_rates,
estimate_mutation_rate,
)
from .small_pars... |
import sys
import argparse
import os.path
import numpy as np
import numpy.linalg
def norm(x):
return numpy.linalg.norm(x, ord=np.inf)
def main():
parser = argparse.ArgumentParser(
description='compare a numpy .npz file to a reference file')
parser.add_argument('data', metavar='A.npz', help='file... |
import datetime
import time
from discord.ext.tasks import loop
from discord.ext import commands
import asyncpraw
from asyncprawcore.exceptions import AsyncPrawcoreException
import asyncpraw.exceptions
from modules.reddit_feed.reddit_post import RedditPost
import config
# Reddit feed settings
CHECK_INTERVAL = 5 # s... |
from amadeus.client.decorator import Decorator
from amadeus.reference_data.urls._checkin_links import CheckinLinks
class Urls(Decorator, object):
def __init__(self, client):
Decorator.__init__(self, client)
self.checkin_links = CheckinLinks(client)
|
# Copyright 2011-2015 Chris Behrens
#
# 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... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from beanmachine.ppl.distributions.flat import Flat
from beanmachine.ppl.distributions.unit import Unit
__all__ = ["Flat", "Unit"]
|
from generators.common.Helper import AttributeKind
from .MakoStaticClassGenerator import MakoStaticClassGenerator
class MakoTypeGenerator(MakoStaticClassGenerator):
"""
Generic Mako generator for atomic type schemas.
"""
def __init__(self, helper, name: str, schema, class_schema, template_path: s... |
from .linear_covariance import LinearCovariance
from .linear import LinearDuo, LinearNoRho
|
'''This module contains a wrapper for the mlflow logging framework. It will automatically set the
local and global parameters for the training run when used in the deep learning tools,
like architecture, learning rate etc.
Mlflow will automatically create a folder called mlruns with the results.
If you want a graphical... |
class Question:
def __init__(self,q_text,q_ans):
self.text = q_text
self.answer = q_ans |
###############################################################################
#
# Package: NetMsgs
#
# File: NetMsgsBase.py
#
"""
NetMsgs Base Data Module
"""
## \file
## \package NetMsgs.NetMsgsBase
##
## $LastChangedDate: 2012-07-23 14:06:10 -0600 (Mon, 23 Jul 2012) $
## $Rev: 2098 $
##
## \brief NetMsgs Base ... |
#! /usr/bin/env python
import rospy
# Provides callback functions for the start and stop buttons
class NodeController(object):
'''
Containing both proxy and gui instances, this class gives a control of
a node on both ROS & GUI sides.
'''
# these values need to synch with member variables.
# ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 09:25:17 2020
@author: krishan
"""
class Mammal(object):
def __init__(self):
print('warm-blooded animal.')
class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
d1 = Dog()
|
from django.contrib import admin
from kitsune.questions.models import QuestionLocale
class QuestionLocaleAdmin(admin.ModelAdmin):
list_display = ("locale",)
ordering = ("locale",)
filter_horizontal = ("products",)
admin.site.register(QuestionLocale, QuestionLocaleAdmin)
|
import cv2
import os
from tqdm import tqdm
import config
from utility import *
for _ in tqdm(os.listdir(config.TRAIN_IMAGES_DIR)):
_ = config.TRAIN_IMAGES_DIR + "/" + _
img = image_resize(_, config.MAX_PIXEL)
image_write(img, _.replace(config.TRAIN_IMAGES_DIR, config.RESIZED_TRAIN_DIR))
for _ in tqdm... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2021 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
try:
import CUBRIDdb
except:
pass
import logging
from lib.core.common import getSafeExString
from lib.core.data import conf
from lib.core.data import logger
from lib.cor... |
import glob, os, re, sys
import stagger
from stagger.id3 import *
import shutil
ultimate_regex = [
'''# Shit
^
(?P<Artist>.+)
\s-\s
(?P<ReleaseYear>\d{4})
\.
(?P<ReleaseMonth>\d{2})
\.
(?P<ReleaseDay>\d{2})
\s-\s
(?P<Title>.+)
[.]+?''']
walkdir = './ipod'
sortedDir = './sorted'
# Scan every directory for file
for d... |
# Reads in the training csv, sorts it first by
# ip, then by click_time, then writes it out
# in spark-friendly parquet format
import pyspark
spark = pyspark.sql.SparkSession.builder.getOrCreate()
df = spark.read.csv('../data/train.csv', header=True, inferSchema=True)
df_sort = df.sort(['ip','click_time'])
df_s... |
import numpy as np
class maze(object):
"""
Implements a 2d maze environment represented as an array.
The agent can move on the array and recieves rewards based on its position
at the end of each turn.
"""
def __init__(self, grid):
self.board = grid
self.position = np.zeros(2) #s... |
# Copyright 2014 Mirantis, 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 ... |
import data_connector
from flask import jsonify, Flask, request
from webargs import fields
from webargs.flaskparser import use_args
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
@app.errorhandler(422)
def validation_failed(e):
return jsonify(error=400, description=str(e.description), ... |
def parentfun():
myaaa = 1
def childfun():
myaaa = 10
print myaaa
childfun()
print myaaa
if __name__=="__main__":
parentfun()
childfun()
|
import itertools
import networkx as nx
def _tokenize(f):
token = []
for line in f:
if line == '\n':
yield token
token = []
else:
token.append(line)
def _filter_terms(tokens):
for token in tokens:
if token[0] == '[Term]\n':
yield token... |
# -*- coding: utf-8 -*-
# version: Python 3.7.0
from yyCrawler.yyLogin import YyLogin
import requests, sys, csv, logging, os
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
'Referer': 'https://www.yy.com/i/income'
}... |
import psycopg2
import pytest
from .tools import exec_file
def test_insert_already_exist_region():
with pytest.raises(psycopg2.ProgrammingError):
exec_file("insert_already_exist_departement")
|
import subprocess
from .conversion import Conversion
from ..helpers import replace_extension
class CommandConversion(Conversion):
command_name = None
output_extension = None
output_flag = False
def __call__(self, source_path):
target_path = replace_extension(self.output_extension, source_pat... |
#!/usr/bin/env python
#################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# #
# Licensed under the Apache License, Version 2.0 ... |
from _mock_data.url import internal_url
from browserist import Browser
def test_window_fullscreen(browser_default: Browser) -> None:
browser = browser_default
browser.open.url(internal_url.EXAMPLE_COM)
default_width, default_height = browser.window.get.size()
browser.window.fullscreen()
fullscree... |
import UnityEngine
all_objects = UnityEngine.Object.FindObjectsOfType(UnityEngine.GameObject)
for go in all_objects:
if go.name[-1] != '_':
go.name = go.name + '_' |
import sys
import json
from conllu import parse
import pdb
def get_grand_head(block, idx):
head = block[idx]['head'] - 1
grandhead = block[head]['head'] - 1
grandlabel = block[head]['deprel']
return grandhead, grandlabel
def compute(adp_data, pred_block, gold_block):
uas, las, total = 0,... |
import gevent
import gevent.monkey
gevent.monkey.patch_socket()
gevent.monkey.patch_select()
gevent.monkey.patch_ssl()
from gevent.pool import Pool as GPool
import re
import os
import sys
import logging
from io import open
from contextlib import contextmanager
from re import search as re_search
from fnmatch import fn... |
import base64
import hashlib
from .helpers import get_config, get_session, write_signature_placeholder, APIError, subject_dn_ as default_subject_dn, get_digest, pkcs11_aligned, write_stream_object
from .selfsigned import cert2asn
import datetime
from asn1crypto import cms, algos, core, pem, tsp, x509, util, ocsp, pdf... |
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return an integer
# def isBadVersion(version):
"""
Correctly initialize the boundary variables left and right.
Only one rule: set up the boundary to include all possible
elements;
Decide return value. Is it return left or return left ... |
"""https://adventofcode.com/2020/day/15"""
import io
def part1(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int:
"""
Given your starting numbers, what will be the 2020th number spoken?
"""
return nth(stdin, stderr, 2020)
def part2(stdin: io.TextIOWrapper, stderr: io.TextIOWrapper) -> int:... |
"""
core/exceptions.py
~~~~~~~~~~~~~~~~~~
Common exception tools.
:copyright: (c) 2018 by {{cookiecutter.author}}.
"""
import sys
from collections import OrderedDict
from rest_framework.views import exception_handler as origin_exception_handler
def get_service_name(view):
"""Returns service nam... |
import os
import sys
import time
import logging
import signal
import json
import subprocess
import threading
from shutil import copyfile
from Queue import Queue
from Queue import Empty
logger = logging.getLogger(__name__)
class SnortUpdateThread(threading.Thread):
"""
threading.Thread to deal with writing t... |
import torch
import io
import posixpath
class ClassificationSummary:
""" Simple class to keep track of summaries of a classification problem. """
def __init__(self, num_outcomes=2, device=None):
""" Initializes a new summary class with the given number of outcomes.
Parameters
--------... |
import random
import numpy as np
import py_progress_tracker as progress
from common import BENCHMARK_CONFIGURATION
import concrete.numpy as hnp
@progress.track(
[
# Addition
{
"id": "x-plus-42-scalar",
"name": "x + 42 {Scalar}",
"parameters": {
... |
import numpy as np
from skimage.transform import SimilarityTransform
from skimage.transform import AffineTransform
# from skimage.transform import warp
from skimage.transform._warps_cy import _warp_fast
def warp(img, tf, output_shape, mode='constant', order=0):
"""
This wrapper function is faster than skimage... |
from __future__ import division, print_function
from .hygroup import HyGroup
class TrajectoryGroup(HyGroup):
"""
Class for processing and plotting multiple ``Trajectory`` instances.
:subclass: of ``HyGroup``.
"""
def __init__(self, trajectories):
"""
Initialize ``TrajectoryGrou... |
class GridElement(object):
"""
A element in a grid.
"""
def __init__(self, id, left, top, right, bottom):
"""
:param left: The left cell this elements is laying in.
:type left: int
:param top: The top cell this elements is laying in.
:type top: int
:param ... |
#!/usr/bin/env python3
import argparse
import os
import psutil
import queue
import requests
import threading
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-t', '--target', type=str, dest='target', default='http://localhost:8000',
help... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404
import datetime as dt
from .models import Image, Location
def index(request):
images = Image.all_pics()
locations = Location.all_locations()
return render(request, 'index.html', {"locations": locations, "images"... |
%matplotlib inline
from random import *
import numpy as np
import seaborn as sns
import pandas as pd
import os
from numpy.linalg import svd
from fbpca import pca
import time
from sklearn.preprocessing import scale, MinMaxScaler
from sklearn.decomposition import RandomizedPCA
from scipy.optimize import curve_fit
from py... |
import numpy as np
import pandas as pd
import sklearn.datasets
from sklearn.metrics import f1_score
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import optuna
import optuna.integration.lightgbm as lgb
import math
from optuna.trial import Trial
np.random... |
#!/usr/bin/python2
#
# Copyright 2018 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Tests of data_source_to_dspl module."""
__author__ = 'Benjamin Yolken <yolken@google.com>'
import ... |
# Yibo Yang, 2020
import tensorflow.compat.v1 as tf
def read_png(filename):
"""Loads a image file as float32 HxWx3 array; tested to work on png and jpg images."""
string = tf.read_file(filename)
image = tf.image.decode_image(string, channels=3)
image = tf.cast(image, tf.float32)
image /= 255
... |
from django.test import TestCase
# Create your tests here.
from django.urls import reverse
from rest_framework.views import status
import json
# tests for views
from django.test import TestCase, Client, RequestFactory
from .views import object_detection
from django.http import JsonResponse, HttpResponse
class SimpleT... |
"""
Useful additional string functions.
"""
import sys
def remove_non_ascii(s):
"""
Remove non-ascii characters in a file. Needed when support for non-ASCII
is not available.
Args:
s (str): Input string
Returns:
String with all non-ascii characters removed.
"""
return ""... |
import re
from typing import Optional
from .types import Filter
from .utils import force_tuple
def should_skip_method(method: str, pattern: Optional[Filter]) -> bool:
if pattern is None:
return False
patterns = force_tuple(pattern)
return method.upper() not in map(str.upper, patterns)
def shoul... |
import os
from experiments.experiments import REDDModelSelectionExperiment
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = ""
from nilmlab import exp_model_list
from nilmlab.lab import TimeSeriesLength
dirname = os.path.dirname(__file__)
single_building_exp_check... |
# 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, software
# distributed under t... |
import os
import glob
from sqlalchemy import Column, types
from sqlalchemy.exc import UnboundExecutionError
from sqlalchemy.orm.exc import UnmappedError
from alchy import manager, model, Session
from .base import TestBase, TestQueryBase
from . import fixtures
from .fixtures import Foo
class TestManager(TestBase):... |
import pandas as pd
import numpy as np
from scipy import stats
from sklearn.preprocessing import LabelBinarizer, LabelEncoder, OneHotEncoder
from sklearn.impute import KNNImputer
def num_columns(df):
"""
Create a list with the names of the numeric columns of a dataframe.
This function is used on rem_outl... |
import json
import boto3
from urllib import parse
s3 = boto3.client('s3')
def get_target_key(source_key):
### defining file key (prefix + filename)
city, year, month, day, query = ['']*5
for s in source_key.split('/'):
city = s if 'city' in s else city
year = s if 'year' in s else ye... |
import itertools
import random
import time
def num_matrix(rows, cols, steps=25):
nums = list(range(1, rows * cols)) + [0]
goal = [ nums[i:i+rows] for i in range(0, len(nums), rows) ]
puzzle = goal
for steps in range(steps):
puzzle = random.choice(gen_kids(puzzle))
return puzzle, goal
de... |
#!/usr/bin/env python
# Python Network Programming Cookbook, Second Edition -- Chapter - 7
# This program is optimized for Python 3.5.2.
# To make it work with Python 2.7.12:
# Follow through the code inline for some changes.
# It may run on any other version with/without modifications.
import argparse
import xm... |
# Generated by Django 2.2.4 on 2019-09-02 17:13
from django.db import migrations
import djstripe.fields
class Migration(migrations.Migration):
dependencies = [("djstripe", "0011_auto_20190828_0852")]
operations = [
migrations.AlterField(
model_name="paymentmethod",
name="ca... |
from flask import Flask
import logging
import os
from proxy_rss import spotify, twitter
logging.basicConfig(level=logging.WARNING)
application = Flask('proxy_rss')
application.register_blueprint(spotify.blueprint, url_prefix='/spotify')
application.register_blueprint(twitter.blueprint, url_prefix='/twitter')
|
import inspect
try:
from sqlalchemy.orm import class_mapper
from sqlalchemy.orm.exc import UnmappedClassError
except ImportError:
pass
from tgext.crud import CrudRestController
try:
from tgext.crud.utils import SortableTableBase as TableBase
except:
from sprox.tablebase import TableBase
try:
... |
class Solution(object):
def getNum(self, t):
if int(t) < 27:
return 1
else:
return 0
def numDecodings(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = str(s)
n = len(s)
dp = [1... |
import cerberus
from random import randint
import pytest
class TestJsonApi():
def test_get_posts(self, client_json):
num = randint(1,100)
res = client_json.get_resourses(path=f'/posts/{num}')
schema = {
"id": {"type": "number"},
"userId": {"type": "number"},
... |
# The MIT License (MIT)
#
# Copyright (c) 2014 Richard Moore
#
# 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, mod... |
#-------------------------------------------------------------------------------
# Name: OSTrICa - Open Source Threat Intelligence Collector - DomainBigData plugin
# Purpose: Collection and visualization of Threat Intelligence data
#
# Author: Roberto Sponchioni - <rsponchioni@yahoo.it> @Ptr32Void
#
# Cr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.