content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Copyright 2020 The Private Cardinality Estimation Framework Authors
#
# 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 b... | nilq/baby-python | python |
from gbdxtools.images.worldview import WorldViewImage
from gbdxtools.images.drivers import WorldViewDriver
from gbdxtools.images.util import vector_services_query
from gbdxtools.rda.interface import RDA
rda = RDA()
band_types = {
'MS': 'BGRN',
'Panchromatic': 'PAN',
'Pan': 'PAN',
'pan': 'PAN'
}
class ... | nilq/baby-python | python |
"""
README:
docs/everything-about-prop-delegators.zh.md
"""
# noinspection PyUnresolvedReferences,PyProtectedMember
from typing import _UnionGenericAlias as RealUnionType
from PySide6.QtQml import QQmlProperty
from .typehint import *
from ....qmlside import qmlside
from ....qmlside.qmlside import convert_name_cas... | nilq/baby-python | python |
import time,calendar,os,json,sys,datetime
from requests import get
from subprocess import Popen,PIPE
from math import sqrt,log,exp
from scipy.optimize import minimize
import numpy as np
np.set_printoptions(precision=3,linewidth=120)
def datetoday(x):
t=time.strptime(x+'UTC','%Y-%m-%d%Z')
return calendar.timegm(t)/... | nilq/baby-python | python |
#
# Copyright 2018 Asylo authors
#
# 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 writi... | nilq/baby-python | python |
"""
Author : Varundev Suresh Babu
Version: 0.1
"""
import rospy
from std_msgs.msg import Float64
steering_publisher = ospy.Publisher("/servo/position", Float64, queue_size = 10)
throttle_publisher = rospy.Publisher("/motor/duty_cycle", Float64, queue_size = 10)
def steering_callback(data):
global steering
st... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# created by inhzus
from .smms import ImageHost
from .md_parser import parse_md
| nilq/baby-python | python |
def rawify_url(url):
if url.startswith("https://github.com"):
urlparts = url.replace("https://github.com", "", 1).strip('/').split('/') + [None] * 5
ownername, reponame, _, refvalue, *filename_parts = urlparts
filename = '/'.join([p for p in filename_parts if p is not None])
assert o... | nilq/baby-python | python |
"""Raw message parser implementations."""
from twisted.words.protocols.irc import ctcpExtract, parsemsg, X_DELIM
from . import Message
from ..hostmask import Hostmask
class RawMessageParser(object):
"""An implementation of the parsing rules for a specific version of
the IRC protocol.
In most cases, yo... | nilq/baby-python | python |
#-*- coding: utf-8 -*-
from bgesdk.error import APIError
import pytest
import six
def check_result(result):
assert 'result' in result
assert 'count' in result
assert 'next_page' in result
next_page = result['next_page']
assert isinstance(result['result'], list)
assert isinstance(result['coun... | nilq/baby-python | python |
# coding=utf-8
from .email import EmailFromTemplate
def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs):
"""
Shortcut function for EmailFromTemplate class
@return: None
"""
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_... | nilq/baby-python | python |
import weakref
import uuid
from types import MethodType
from collections import OrderedDict
from Qt import QtGui
from Qt.QtWidgets import QPushButton
from Qt.QtWidgets import QGraphicsProxyWidget
from Qt.QtWidgets import QMenu
from PyFlow.Core.Common import *
from PyFlow.UI.Utils.Settings import *
from PyFlow.Core.No... | nilq/baby-python | python |
import logging
from rest_framework import exceptions
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_user_model
from galaxy.api import serializers
from galaxy.api.views import base_views
from galaxy.main import models
__... | nilq/baby-python | python |
import re
import pandas as pd
from dojo.models import Finding
__author__ = 'Matt Sicker'
class DsopParser:
def __init__(self, file, test):
self._test = test
self._items = []
f = pd.ExcelFile(file)
self.__parse_disa(pd.read_excel(f, sheet_name='OpenSCAP - DISA Compliance', parse_... | nilq/baby-python | python |
from exterminate.Utilities import builtins
from exterminate.Gizoogle import translate
_print = builtins.print
builtins.print = lambda *args, **kwargs: _print(
translate(' '.join([str(x) for x in args])), **kwargs
)
| nilq/baby-python | python |
from builtins import object
import abc
from future.utils import with_metaclass
class Solver(with_metaclass(abc.ABCMeta, object)):
def __init__(self, **kwargs):
self.options = kwargs
if 'verbose' not in self.options:
self.options['verbose'] = False
@abc.abstractmethod
def sol... | nilq/baby-python | python |
# Copyright (c) 2015 Microsoft Corporation
from z3 import *
set_option(auto_config=True)
x = Int('x')
y = Int('y')
f = Function('f', IntSort(), IntSort())
solve(f(f(x)) == x, f(x) == y, x != y)
| nilq/baby-python | python |
"""Capture synthesizer audio for each of a batch of random chords.
By default, prints the number of JACK xruns (buffer overruns or underruns)
produced during the MIDI playback and capture process.
"""
import cProfile
import datetime
import json
import os
import pstats
import time
import numpy as np
import scipy.io.wa... | nilq/baby-python | python |
#swap 4 variables
# swap variable
w=input("enter any nymber")
x=input("enter any nymber")
y=input("enter any number")
z=input("enter any number")
print("w before swap :{}".format(w))
print("x before swap:{}".format(x))
print("y before swap :{}".format(y))
print("z before swap :{}".format(z))
w=w+x+y+z
x=w... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from django.http import HttpResponse
from django.template import Template, RequestContext
from django.shortcuts import render
f... | nilq/baby-python | python |
import UpdateItem as ui
import UpdateChecker as uc
import UpdateFileReader as ufr
import tkinter
from tkinter import messagebox
is_verbose = True
root = tkinter.Tk()
root.withdraw()
userfile = "updateList.txt"
currentReader = ufr.UpdateFileReader(userfile, is_verbose)
while currentReader.getNextItem():
currentItem... | nilq/baby-python | python |
# Modified: 2022-06-02
# Description: Defines the FastAPI app
#
from pathlib import Path
from motor.motor_asyncio import AsyncIOMotorClient
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from controllers import game_controller, player_contro... | nilq/baby-python | python |
'''
Modified run-length encoding.
Modify the result of problem P10 in such a way that if an element
has no duplicates it is simply copied into the result list. Only
elements with duplicates are transferred as (N E) lists.
Example:
* (encode-modified '(a a a a b c c a a d e e e e))
((4 A) B (2 C) (2 A) D (4 E))... | nilq/baby-python | python |
import dash_html_components as html
class Component:
def render(self) -> html.Div:
raise NotImplementedError
| nilq/baby-python | python |
# The MIT License (MIT)
#
# Copyright (c) 2014 Steve Milner
#
# 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, modi... | nilq/baby-python | python |
import smartpy as sp
FA12 = sp.io.import_script_from_url("file:Fa12.py", name="FA12")
"""
Possible states of the swap
"""
class State():
Waiting = 1
Initiated = 2
"""
Swap record -
hashedSecret(bytes): current swap hash
initiator(address): initiators tezos address
initiator_eth_addr(string): ... | nilq/baby-python | python |
with open('Day10 input.txt') as f:
lines = f.readlines()
chunk_dict = {
'(':')',
'[':']',
'{':'}',
'<':'>'
}
score_dict = {
')':3,
']':57,
'}':1197,
'>':25137
}
corrupted = []
score = 0
for line in lines:
chunk = ''
for l in line:
if l in ['(','[','{','<']:
... | nilq/baby-python | python |
#!/usr/bin/python
# encoding: utf-8
import random
import torch
from torch.utils.data import Dataset
from torch.utils.data import sampler
import torchvision.transforms as transforms
import lmdb
import six
import sys
from PIL import Image
import numpy as np
# 关于lmdb数据库使用, 当时对接Python 2.x,所以使用Bytestrings,而不是unicode,
# 所以... | nilq/baby-python | python |
class Occurrence(object):
"""
An Occurrence is an incarnation of a recurring event for a given date.
"""
def __init__(self,event,start,end):
self.event = event
self.start = start
self.end = end
def __unicode__(self):
return "%s to %s" %(self.start, self.end)
de... | nilq/baby-python | python |
# some modules use the old-style import: explicitly include
# the new module when the old one is referenced
hiddenimports = ["email.mime.text", "email.mime.multipart"]
| nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
from xnas.search_space.DARTS.ops import *
from torch.autograd import Variable
def channel_shuffle(x, groups):
batchsize, num_channels, height, width = x.data.size()
channels_per_group = num_channels // groups
# reshape
x ... | nilq/baby-python | python |
# This is just a demo file
print("Hello world")
print("this is update to my previous code") | nilq/baby-python | python |
import os
import asyncio
import sys
from typing import Any, Dict, Union, List # noqa
from tomodachi.watcher import Watcher
def test_watcher_auto_root() -> None:
watcher = Watcher()
assert watcher.root == [os.path.realpath(sys.argv[0].rsplit('/', 1)[0])]
def test_watcher_empty_directory() -> None:
root_... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
from optimizer import distributed_optimizer
from task_module import pretrain, classifier, pretrain_albert
import tensorflow as tf
try:
from distributed_single_sentence_classification.model_interface import model_zoo
except:
from distributed_single_sentence_classification.m... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''test cases for config_loader module'''
import unittest
import os
import shutil
import cray.craylib.config_loader as config_loader
from cray.craylib.generate_manager import GenerateManager
ROOT_DIR = os.path.join(os.path.dirname(__file__), "test_site")
SITE_DIR = os.path.join(os.path.dirnam... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import time
import math
def go(l, n, partials):
return (partials[-1] - partials[n]) % 10
def fft(l):
"""Fucked Fourier Transform"""
partials = [0]
sum = 0
for v in l:
sum += v
partials.append(sum)
x = []
for i, y in enumerate(l):
... | nilq/baby-python | python |
import enolib
def test_querying_an_existing_single_line_required_string_comment_from_a_section_produces_the_expected_result():
input = ("> comment\n"
"# section")
output = enolib.parse(input).section('section').required_string_comment()
expected = ("comment")
assert output == expect... | nilq/baby-python | python |
"""
test_finger_pks.py
Copyright 2012 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af 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 version 2 of the License.
w3af is distributed in the hope ... | nilq/baby-python | python |
import numpy as np
import cv2
# 'uint8' assigns an 8bit unsigned integer to the colour values in the array
pic = np.zeros((512, 512, 3), dtype = 'uint8')
# Draw a rectangle from 0px to 512px
# Magenta colour, not color
colour = (255, 0, 255)
# Circles overview: https://www.khanacademy.org/math/basic-geo/basic-geo-are... | nilq/baby-python | python |
#! /usr/bin/env python
# _*_ coding:utf-8 _*_
class Solution(object):
def generateParenthesis(self, n):
if n <= 0:
return []
if n == 1:
return ['()']
res = self.generateParenthesis(n - 1)
ret = set()
for v in res:
for i in range(len(v)):... | nilq/baby-python | python |
from django_codemod.constants import DJANGO_1_9, DJANGO_3_1
from django_codemod.visitors.base import BaseRenameTransformer
class PrettyNameTransformer(BaseRenameTransformer):
"""Replace `django.forms.forms.pretty_name` compatibility import."""
deprecated_in = DJANGO_1_9
removed_in = DJANGO_3_1
rename... | nilq/baby-python | python |
from yahoo import Quote, YahooQuote
stocks = ['AA', 'AXP', 'BA', 'BAC', 'CAT', 'CSCO', 'CVX', 'DD', 'DIS', 'GE', 'HD', 'HPQ', 'IBM', 'INTC', 'JNJ']
stocks += ['JPM', 'KO', 'MCD', 'MMM', 'MRK', 'MSFT', 'PFE', 'PG', 'T', 'TRV', 'UNH', 'UTX', 'VZ', 'WMT', 'XOM']
price = {}
quotes = {}
returns = {}
for s in stocks:
p... | nilq/baby-python | python |
"""Support for control of ElkM1 outputs (relays)."""
from homeassistant.components.switch import SwitchEntity
from . import ElkAttachedEntity, create_elk_entities
from .const import DOMAIN
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Create the Elk-M1 switch platform."""
elk_data =... | nilq/baby-python | python |
import pymongo
import config
from . import connection, db
def create_indexes():
"""
Create mongodb indexes.
"""
# VCF collection indexes
db.vcfs.drop_indexes()
db.vcfs.create_index("name")
db.vcfs.create_index("samples")
db.vcfs.create_index( [ ("filename", pymongo.ASCENDING), ("fi... | nilq/baby-python | python |
#
# Copyright (C) 2018 SecurityCentral Contributors see LICENSE for license
#
"""
This base platform module exports platform related tasks.
"""
from securitycentralplatform.os_detection import platform_detection
class SecurityCentralPlatformTasks(platform_detection("tasks")):
pass
tasks = SecurityCentralPlatfor... | nilq/baby-python | python |
from django import forms
from apps.link.models import Link, Advertise
from apps.post.models import Category, Post
class CategoryAddForm(forms.ModelForm):
class Meta:
model = Category
fields = "__all__"
class CategoryEditForm(forms.ModelForm):
pk = forms.CharField(max_length=100)
class ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-18 23:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('climate_data', '0006_auto_20160816_1429'),
]
operations = [
migrations.Alter... | nilq/baby-python | python |
import doctest
import unittest
import zeit.cms.testing
def test_suite():
suite = unittest.TestSuite()
suite.addTest(doctest.DocFileSuite(
'content.txt',
package='zeit.cms'
))
suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(
'cleanup.txt',
'cmscontent.txt',
... | nilq/baby-python | python |
# https://stackoverflow.com/questions/31663288/how-do-i-properly-use-connection-pools-in-redis
# settings.py:
import redis
def get_redis_connection():
return redis.StrictRedis(host='localhost', port=6379, db=0)
# task1.py
import settings
connection = settings.get_redis_connection()
def do_something1():
ret... | nilq/baby-python | python |
import base64
import gzip
import io
import json
import re
import struct
from pathlib import Path
from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union
from backend import constants
_here = Path(__file__).parent
with open(_here/'exceptions/enchants.json') as f:
ENCHANT_EXCEPTIONS = json.load(f)
wi... | nilq/baby-python | python |
from timeit import timeit
nTests=10000
print("Each operation performed {} times".format(nTests))
print("")
print("Custom Quaternion")
print("")
importQuatVec = '''
from MAPLEAF.Motion import Quaternion
from MAPLEAF.Motion import Vector
v1 = Vector(1, 1, 2)
'''
# Test Quaternion speed (init)
print("Initializing Quat... | nilq/baby-python | python |
# TI & TA
from pyti.smoothed_moving_average import smoothed_moving_average as pyti_smmoothed_ma
from pyti.simple_moving_average import simple_moving_average as pyti_sma
from pyti.bollinger_bands import lower_bollinger_band as pyti_lbb
from pyti.bollinger_bands import upper_bollinger_band as pyti_ubb
from pyti.accumula... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Tests for LinearRegionVisual
All images are of size (100,100) to keep a small file size
"""
import numpy as np
from vispy.scene import visuals
from vispy.... | nilq/baby-python | python |
import numpy as np
from heapq import heappush, heappop
from dataclasses import dataclass, field
import os
@dataclass(order=True)
class PosItem:
priority: int
pos: tuple[int, int] = field(compare=False)
path = os.path.join(os.path.dirname(__file__), "input.txt")
def find_path(arr):
pq = []
visited ... | nilq/baby-python | python |
from selenium import webdriver
browser = webdriver.Firefox(executable_path=r"C:\Windows\geckodriver.exe")
browser.get("https://github.com")
browser.maximize_window()
browser.implicitly_wait(20)
sign_in = browser.find_element_by_link_text("Sign in")
sign_in.click()
user_name = browser.find_element_by_id(... | nilq/baby-python | python |
import unittest
import Models
class BasicTestMethods(unittest.TestCase):
def test_asdf(self):
self.assertEqual(Models.asdf(), "asdf", 'nah')
self.assertNotEqual(Models.asdf(), "asdf1", 'nah')
#self.assertEqual(asdf(), "asdf1", 'nah')
if __name__ == '__main__':
unittest.main()
| nilq/baby-python | python |
#!/usr/bin/env python
"""AVIM build configuration"""
from os import path
from datetime import date
from build import BuildConfig
# Type of build to produce.
CONFIG = BuildConfig.RELEASE
# Incremented version number.
# See <https://developer.mozilla.org/en-US/docs/Toolkit_version_format>.
VERSION = (5, 8, 2)
# Build... | nilq/baby-python | python |
import sys
sys.path.append('../src/')
print(sys.path)
import Histograms
import unittest
import numpy
import time
class MyTestCase(unittest.TestCase):
def setUp(self):
pass
def test_learnSingleton(self):
m = Histograms.Histograms({
"histograms": ["test"]
, "AllowLimi... | nilq/baby-python | python |
"""User details and sex of patient added
Revision ID: 7d4bab0acebb
Revises: b4bb7697ace6
Create Date: 2017-09-14 14:53:07.958616
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7d4bab0acebb'
down_revision = 'b4bb7697ace6'
branch_labels = None
depends_on = None... | nilq/baby-python | python |
"""
Author: Justin Cappos
Start date: October 9th, 2009
Purpose: A simple library that serializes and deserializes built-in repy types.
This includes strings, integers, floats, booleans, None, complex, tuples,
lists, sets, frozensets, and dictionaries.
There are no plans for including objects.
Note: that all item... | nilq/baby-python | python |
"""
Author: William Gabriel Carreras Oropesa
Date: April 19, 2020, Neuqué, Argentina
module body: This module has implemented a series of functions and objects
that will be useful when solving the problem of the N bodies.
"""
# necessary modules
import numpy as np
from copy import copy
class body(object):
... | nilq/baby-python | python |
import logging
import multiprocessing
import unicodedata
from argparse import Namespace
from contextlib import closing
from itertools import chain, repeat
from multiprocessing.pool import Pool
from tqdm import tqdm
from transformers.tokenization_roberta import RobertaTokenizer
logger = logging.getLogger(__name__)
c... | nilq/baby-python | python |
name = input("Hello! What's your name? ")
print('Nice to meet you \033[31m{}\033[m!'.format(name))
| nilq/baby-python | python |
"""
This file handles Reservation related HTTP request.
"""
from flask import request
from flask_restplus import Resource
from flask_jwt_extended import jwt_required
from flask_jwt_extended.exceptions import NoAuthorizationError,InvalidHeaderError,RevokedTokenError
from jwt import ExpiredSignatureError, InvalidTokenErr... | nilq/baby-python | python |
from wtforms import Form, StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email
from flask_wtf import FlaskForm
class RegistrationForm(FlaskForm):
email = StringField(
'Email', [DataRequired(), Email(), Length(min=6, max=36)])
username = Strin... | nilq/baby-python | python |
# !/usr/bin/env python
# coding=utf-8
"""
Calcs for HW3
"""
from __future__ import print_function
import sys
import numpy as np
from common import GOOD_RET, R_J, temp_c_to_k, k_at_new_temp, R_ATM, make_fig
__author__ = 'hbmayes'
def pfr_design_eq(x_out, x_in, vol, nuo, k):
"""
PFR design eq for HW3 problem ... | nilq/baby-python | python |
'''Wrapper for nviz.h
Generated with:
./ctypesgen.py --cpp gcc -E -I/Applications/GRASS-7.8.app/Contents/Resources/include -D_Nullable= -I/Users/cmbarton/grass_source/grass-7.8.3/dist.x86_64-apple-darwin18.7.0/include -I/Users/cmbarton/grass_source/grass-7.8.3/dist.x86_64-apple-darwin18.7.0/include -D__GLIBC_HAVE... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 13 12:02:28 2021
@author: Clau
"""
'''
Paper: Energy sufficiency (SDEWES LA 2022)
User: School B - LOWLANDS
'''
from core import User, np
User_list = []
#Definig users
SB = User("School type B", 1)
User_list.append(SB)
#Appliances
SB_indoor_bulb = SB.Appliance(SB,12... | nilq/baby-python | python |
# encoding: UTF-8
#
# Copyright (c) 2015 Facility for Rare Isotope Beams
#
"""
Lattice Model application package.
"""
| nilq/baby-python | python |
import fnmatch
import os
def locate(pattern, root=os.getcwd()):
for path, dirs, files in os.walk(root):
for filename in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, pattern)]:
yield filename
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2017 IBM RESEARCH. 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 requ... | nilq/baby-python | python |
import pytest
from beagle.nodes import File, Process
from beagle.transformers.evtx_transformer import WinEVTXTransformer
@pytest.fixture
def transformer() -> WinEVTXTransformer:
return WinEVTXTransformer(None)
def test_process_creation(transformer):
input_event = {
"provider_name": "Microsoft-Windo... | nilq/baby-python | python |
# Exercício 2: Para exercitar nossa capacidade de abstração, vamos modelar algumas partes de um software de geometria. Como poderíamos modelar um objeto retângulo?
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
def area(self):
pass
de... | nilq/baby-python | python |
import os
import matplotlib
from tqdm import tqdm
import numpy as np
from model import FasterRCNNVGG16
from trainer import FasterRCNNTrainer
from utils.config import opt
import data.dataset
import data.util
import torch
from torch.autograd import Variable
from torch.utils import data as data_
import torchvision.transfo... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
使用__new__方法实现单例模式
"""
class SingleTon(object):
"""继承该父类的类都是单例类,即重写类的new方法"""
_instance = {} # 用来保存自己类的实例
def __new__(cls, *args, **kwargs):
# 如果没有创建过该实例则创建一个自身的实例
if cls not in cls._instance:
cls._insta... | nilq/baby-python | python |
class PathgeoTwitter:
import sys
from datetime import datetime
'''
createXLSX: convert tweets array into xlsx file
input
1. *tweets (array)
2. *cols (array): which columns in tweets you want to export
3. *outputPath (String)
4. *fileName (St... | nilq/baby-python | python |
# Minimum Window Substring: https://leetcode.com/problems/minimum-window-substring/
# Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty stri... | nilq/baby-python | python |
from webapp.forms import SForm
from django.views.generic.edit import FormView
from django import forms
class HomePageView(FormView):
template_name = 'home.html'
form_class = SForm
success_url = '/'
ctx = dict()
def form_valid(self, form):
# This method is called when valid form data has b... | nilq/baby-python | python |
from .default.params.Params import (Choice, TransitionChoice,
Array, Scalar, Log, Tuple,
Instrumentation, Dict)
| nilq/baby-python | python |
from flask import current_app as app
class Purchase:
def __init__(self, id, uid, pid, time_purchased, name, price, quantity, status):
self.id = id
self.uid = uid
self.pid = pid
self.time_purchased = time_purchased
self.name = name
self.price = price
self.qua... | nilq/baby-python | python |
from heapq import nlargest
def popular_shop(l, r, make_dict):
for i in range(l, r+1):
make_dict[i] += 1
t = int(input())
for j in range(t):
n_m = list(map(int, input().strip().split()))
n = n_m[0]
m = n_m[1]
make_dict = {i + 1: 0 for i in range(n)}
for i in range(m):
arr_el =... | nilq/baby-python | python |
import sys, os
from lxml import objectify
usage = """
Usage is:
py admx2oma.py <your.admx> <ADMX-OMA-URI>
<ADMX-OMA-URI> : The OMA-URI you specifyed in Intune when ingesting admx file
Take care, the OMA-URI is case sensitive.
<your.admx> : The admx file you ingested
"""
def run():
if len(s... | nilq/baby-python | python |
import logging
import sys
import ast
from typing import Optional
from logistik.config import RedisKeys
from ttldict import TTLOrderedDict
from logistik.cache import ICache
from logistik.db.reprs.handler import HandlerConf
from logistik.environ import GNEnvironment
ONE_HOUR = 60 * 60
class CacheRedis(ICache):
... | nilq/baby-python | python |
from django.template.response import TemplateResponse
from .forms import QuestionForm
# Create your views here.
def index(request) :
form = QuestionForm()
# print(request.context)
data_service = request.context
template_context = data_service.to_dict()
template_context.update(form=form)
... | nilq/baby-python | python |
"""Create social table.
Revision ID: fe9c31ba1c0e
Revises: 7512bb631d1c
Create Date: 2020-04-15 16:12:02.211522
"""
import sqlalchemy as sa
import sqlalchemy_utils as sau
from sqlalchemy.dialects import postgresql
from modist.models.common import SocialType
from alembic import op
from alembic.operations.toimpl impor... | nilq/baby-python | python |
import bpy
class ahs_maincurve_volume_down(bpy.types.Operator):
bl_idname = 'object.ahs_maincurve_volume_down'
bl_label = "肉付けを削除"
bl_description = "選択カーブの設定したテーパー/ベベルを削除"
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
try:
for ob in context.selected_objects:
if ob.type != 'CUR... | nilq/baby-python | python |
#! /usr/bin/env python3
# Script for generating a general_pipeline_alternative.glsl that
# handles filling two mip levels, for the given warps-per-workgroup
# and 2nd level mipmap tile size per workgroup.
# Hard to explain, but hopefully the output is more sensible.
from sys import argv, exit, stderr
import os
from pat... | nilq/baby-python | python |
from django.shortcuts import redirect, render
from django.urls import reverse
def home(request):
"""
This bounces home page requests to an appropriate place.
"""
if request.user.is_authenticated:
return redirect(reverse("page", kwargs={'path': 'index'}))
else:
return redirect(reve... | nilq/baby-python | python |
import pygame as pg
from .utils import init_events, check_name_eligibility, str_to_tuple, find_font
from .base_icon import BaseIcon
class Canvas(BaseIcon):
defaults = {'type' : 'Canvas',
'name' : None,
'width' : 200,
'height' : 200,
'x' : None,
... | nilq/baby-python | python |
URL = "https://github.com/General-101/Halo-Asset-Blender-Development-Toolset/issues/new"
EMAIL = "halo-asset-toolset@protonmail.com"
ENABLE_DEBUG = False
ENABLE_DEBUGGING_PM = False
ENABLE_PROFILING = False
ENABLE_CRASH_REPORT = True
| nilq/baby-python | python |
from mrjob.job import MRJob
from mrjob.step import MRStep
class SpendByCustomerSorted(MRJob):
def steps(self):
return [
MRStep(mapper=self.mapper_get_orders,
reducer=self.reducer_totals_by_customer),
MRStep(mapper=self.mapper_make_amounts_key,
... | nilq/baby-python | python |
import aws_cdk.core as cdk
import aws_cdk.aws_s3 as s3
import aws_cdk.aws_s3_deployment as s3_deployment
import aws_cdk.aws_ssm as ssm
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_iam as iam
import aws_cdk.aws_kms as kms
class CfnNag(cdk.Stack):
def __init__(self, scope: cdk.Construct, id: str, general... | nilq/baby-python | python |
"""
PASSIVE Plugin for Testing for Captcha (OWASP-AT-008)
"""
from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper
DESCRIPTION = "Google Hacking for CAPTCHA"
def run(PluginInfo):
resource = get_resources("PassiveCAPTCHALnk")
Content = plugin_helper.resource_linklist("... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2016 Chris Lamb <lamby@debian.org>
#
# diffoscope 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,... | nilq/baby-python | python |
# python3
"""Parse a pyi file using typed_ast."""
import hashlib
import sys
import typing
from typing import Any, List, Optional, Tuple, Union
import dataclasses
from pytype import utils
from pytype.ast import debug
from pytype.pyi import classdef
from pytype.pyi import conditions
from pytype.pyi import definition... | nilq/baby-python | python |
#
# Copyright 2022 Logical Clocks AB
#
# 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... | nilq/baby-python | python |
import json
import os
import threading
import time
from functools import wraps
import speech_recognition as sr
class BaseCredentials:
def __init__(self):
pass
def __call__(self):
raise NotImplementedError
@property
def name(self):
raise NotImplementedError
class GoogleClou... | nilq/baby-python | python |
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from django.conf.urls import url
from starlingx_dashboard.dashboards.dc_admin.dc_software_management.views \
import CreateCloudPatchConfigView
from starlingx_dashboard.dashboards.dc_admin.dc_software_management.views \
i... | nilq/baby-python | python |
# Generated by Django 3.2.7 on 2021-09-24 18:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('users', '0001_initial'),
('recipes', '0001_initial'),
]
operations = [
migratio... | nilq/baby-python | python |
from minpiler.std import M
x: int
y: str
z: int = 20
M.print(z)
# > print 20
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.