content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from django.apps import AppConfig
class SessionConfig(AppConfig):
name = "ticketflix.session"
verbose_name = "Session"
| nilq/baby-python | python |
try:
x = 3
print(x[1,2:3,4])
except:
print('it was supposed to fail')
| nilq/baby-python | python |
"""
By Dr Jie Zheng -Q, NAOC
v1 2019-04-27
"""
import numpy as np
from..util import *
def date_conv():
pass
#function date_conv,date,type, BAD_DATE = bad_date
#;+
#; NAME:
#; DATE_CONV
#; PURPOSE:
#; Procedure to perform conversion of dates to one of three possible formats.
#;
#; EXPLA... | nilq/baby-python | python |
from commandlib import Command, CommandError
from path import Path
import patoolib
import shutil
import os
def log(message):
print(message)
def extract_archive(filename, directory):
patoolib.extract_archive(filename, outdir=directory)
class DownloadError(Exception):
pass
def download_file(downloaded... | nilq/baby-python | python |
from dataclasses import dataclass, field
from typing import Optional, List
@dataclass
class MessageEvent(object):
username: str
channel_name: str
text: Optional[str]
command: str = ""
args: List[str] = field(default_factory=list)
@dataclass
class ReactionEvent(object):
emoji: str
usernam... | nilq/baby-python | python |
"""
To get the mdp parameters from sepsis simulator
@author: kingsleychang
"""
import numpy as np
import pandas as pd
import torch
from .sepsisSimDiabetes.DataGenerator import DataGenerator
from .sepsisSimDiabetes.MDP import MDP_DICT
from .sepsisSimDiabetes.State import State
from sklearn.model_selection import train... | nilq/baby-python | python |
SAMPLE_MAP = load_samples('examples/sample_list.xlsx')
print(f'SAMPLE_MAP:\n{SAMPLE_MAP}')
| nilq/baby-python | python |
#!/usr/bin/python3
"""
Given a word, you need to judge whether the usage of capitals in it is right or
not.
We define the usage of capitals in a word to be right when one of the following
cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only t... | nilq/baby-python | python |
#!/usr/bin/env python2
# coding: utf-8
# MedSal Database
# Connection & Data query
#
# University of Applied Sciences of Lübeck
#
# Anna Androvitsanea
# anna.androvitsanea@th-luebeck.de
# This scripts includes the code for connecting and querying the data that have been uploaded to the MedSal's project [database](h... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Filters module tests."""
from __future__ import absolute_import, print_function
... | nilq/baby-python | python |
# Copyright (c) 2021 Emanuele Bellocchia
#
# 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, publish,... | nilq/baby-python | python |
from unittest.mock import patch
from django.test import TestCase
from store.models import product_image_file_path
class ModelTests(TestCase):
@patch('uuid.uuid4')
def test_product_file_name_uuid(self, mock_uuid):
"""Test that image is saved in the correct location"""
uuid = 'test-uuid'
... | nilq/baby-python | python |
"""Tests in the tutorial."""
from fractions import Fraction
from dice_stats import Dice
def test_basic_dice_operations_ga():
"""Test basic dice operations."""
d12 = Dice.from_dice(12)
assert d12 + 3 == Dice.from_full(
{
4: Fraction(1, 12),
5: Fraction(1, 12),
... | nilq/baby-python | python |
import propar
import time
import random
dut = propar.instrument('com1')
print()
print("Testing using propar @", propar.__file__)
print()
n = 10
all_parameters = dut.db.get_all_parameters()
bt = time.perf_counter()
for i in range(n):
for p in all_parameters:
dut.read_parameters([p])
et = time.perf_counter()... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pytest
from exoscale.api.compute import *
class TestComputeSSHKey:
def test_delete(self, exo, sshkey):
ssh_key = SSHKey._from_cs(exo.compute, sshkey(teardown=False))
ssh_key_name = ssh_key.name
ssh_key.delete()
assert ssh_key.... | nilq/baby-python | python |
from jobmine.jobmine import JobMine # yes, I do find this quite funny
| nilq/baby-python | python |
import requests
bad = []
good = []
proxy_file = open("proxies.txt", "r")
proxies = proxy_file.read()
proxies = proxies.splitlines()
for proxy in proxies:
try:
print("Checking: " + proxy)
resp = (requests.get("http://discord.com", proxies={"http":proxy, "https":proxy}, timeout=2))
good.append(pr... | nilq/baby-python | python |
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dacodesjobs',
... | nilq/baby-python | python |
import numpy as np
import plotly
import plotly.graph_objs as go
from HypeNet.Networks.FCNN_SoftmaxCE import FCNN_SoftmaxCE
from HypeNet.Core.loadData import loadFashionMnist
from HypeNet.Core.Trainer import Trainer
from HypeNet.Core.utils import *
import os
DIR = os.path.dirname(os.path.abspath(__file__)) + '/SavedNet... | nilq/baby-python | python |
'''
Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol,
na ordem de colocação. Depois mostre:
a) Os 5 primeiros times.
b) Os últimos 4 colocados.
c) Times em ordem alfabética.
d) Em que posição está o time do Bragantino.
obs.: Usarei a tabela... | nilq/baby-python | python |
import os
import sys
import json
import numpy as np
import torch
import pdb
from torch.autograd import Variable
from PIL import Image
import time
from opts import parse_opts
from model import generate_model
from mean import get_mean
def main(video_root,output_root):
start_time = time.time()
for class_name in o... | nilq/baby-python | python |
from multipledispatch import dispatch
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from .colour import PAL, gen_PAL
sns.set()
# Remove stheno from this temporarily cus too many dependencies and not maintained, it depends on lab and wbml which is not easy to install.
a = ... | nilq/baby-python | python |
class Pessoa:
def __init__(self, nome,idade):
self.nome = nome
self.idade = idade
p = Pessoa.__new__(Pessoa)
dados = {'nome':'Fábio','idade':25}
for k,y in dados.items():
setattr(p,k,y)
print(p.nome, p.idade)
| nilq/baby-python | python |
"""
TransformDF2Numpy is a simple tool for quick transformation from pandas.DataFrame to numpy.array dataset,
containing some utilities such as re-transformation of new data,
minimal pre-processing, and access to variable information.
##################
### Overview ###
##################
+ Transform a trainin... | nilq/baby-python | python |
import numpy as np
def gtd_bias(z, growth, alpha, b0, c):
b = c + (b0 - c) / growth**alpha
return b
def q_bias(k, Q, A):
return (1 + Q * k**2) / (1 + A * k)
def make_grids(k, z):
K = np.tile(k[:, None], z.size)
Z = np.tile(z[:, None], k.size).T
return K, Z
def q_model(k, z, Q, A):
# ... | nilq/baby-python | python |
import os.path
from datetime import datetime
import click
from spoty import settings
from typing import List
import dateutil.parser
import numpy as np
from multiprocessing import Process, Lock, Queue, Value, Array
import sys
import time
from time import strftime
from time import gmtime
import string
THREADS_COUNT = 12... | nilq/baby-python | python |
from atexit import register
from datetime import datetime
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
# from .models import Patient
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse
from patie... | nilq/baby-python | python |
#!/home/miranda9/miniconda3/envs/automl-meta-learning/bin/python
from argparse import Namespace
import torch
import torch.nn as nn
import torch.optim as optim
# from transformers import Adafactor
# from transformers.optimization import AdafactorSchedule
import uutils
from uutils.torch_uu import get_layer_names_to_do... | nilq/baby-python | python |
from typing import List
import logging
import orjson
from instauto.api.actions.structs.feed import FeedGet
from instauto.api.client import ApiClient
logging.basicConfig()
logger = logging.getLogger(__name__)
def get_feed(client: ApiClient, limit: int) -> List[dict]:
ret = []
obj = FeedGet()
while len(ret) <... | nilq/baby-python | python |
from django.urls import path
from boards.views import home, board_topics, new_topic, topic_posts, reply_topic
app_name = "boards"
urlpatterns = [
path("", home, name="home"),
path("boards/<int:pk>/", board_topics, name="board_topics"),
path("boards/<int:pk>/new/", new_topic, name="new_topics"),
path... | nilq/baby-python | python |
"""Used for tidying up any changes made during testing"""
import shutil
def test_tidy_up(): # pragma: no cover
"""Delete all files and folders created during testing"""
try:
shutil.rmtree('config')
except (FileNotFoundError, PermissionError):
pass
assert True
| nilq/baby-python | python |
import cherrypy
def serve(app, port=5000, config={}) -> None:
"""
Serve Flask app with production settings
:param app: Flask application object
:param port: on which port to run
:param config: additional config dictionary
:return:
"""
cherrypy.tree.graft(app, '/')
# Set the config... | nilq/baby-python | python |
import pytest
from cowdict import CowDict
base_dict = {
"foo1": "bar1",
"foo2": "bar2",
"foo3": "bar3",
"foo4": "bar4",
"foo5": "bar5",
}
base_dict_items = tuple(base_dict.items())
keys = ("foo1", "foo2", "foo3", "foo4", "foo5")
def test_same_unchanged():
cd = CowDict(base_dict)
for ke... | nilq/baby-python | python |
"""Pythonic toolkit for web development."""
| nilq/baby-python | python |
from ElevatorComponent import ElevatorComponent
from Messages import *
from time import sleep
class STATE(Enum):
"""
States used exclusively by Car Door
"""
OPENED = "opened"
OPENING = "opening"
CLOSED = "closed"
CLOSING = "closing"
class CarDoor(ElevatorComponent):
def __init__(... | nilq/baby-python | python |
from flask import Flask
from flask import flash
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import InputRequir... | nilq/baby-python | python |
"""*****************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to ... | nilq/baby-python | python |
"""
Created on 30/9/2015
@author: victor
"""
import sys
from trajectory_comparison.T_Disp_super_batch_analysis import get_folders_for_analysis
import os
import glob
import numpy
def get_num_models(merged_pdb):
models = 0
handler = open(merged_pdb,"r")
for line in handler:
if "MODEL" == line[0:5]:
... | nilq/baby-python | python |
# Generated by Django 3.2 on 2021-04-28 04:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('team', '0001_initial'),
('lead', '0001_initial'),
]
operations = [
migrations.AddField(
m... | nilq/baby-python | python |
"""606 · Kth Largest Element II"""
class Solution:
"""
@param nums: an integer unsorted array
@param k: an integer from 1 to n
@return: the kth largest element
"""
def kthLargestElement2(self, nums, k):
# write your code here
import heapq
heap = []
for num in num... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import re
import sys
print('please set min_sentence_len: ')
min_sentence_len = int(input())
outfile='namu_extracted_deleted.txt'
max_sentence_len = 9999
if len(sys.argv) >1:
max_sentence_len=int(sys.argv[2])
outfile = outfile.rsplit('.')[0] + '_' + str(min_sentence_len) + '.txt... | nilq/baby-python | python |
""" Test brainspace.utils.parcellation """
import pytest
import numpy as np
from brainspace.utils import parcellation as parc
parametrize = pytest.mark.parametrize
testdata_consecutive = [
# default start_from = 0 and dtype
(np.array([1, 3, 3, 2, 2, 2], dtype=np.int),
{},
np.array([0, 2, 2, 1,... | nilq/baby-python | python |
from dataset import RailData
import torch
from torch import optim
import torch.nn as nn
from torch.utils.data import DataLoader, random_split
from multiprocessing import cpu_count
import pathlib
from tqdm import tqdm
from wcid import NetSeq
import sys
from validation.metrics import calculate_metrics
import os
import co... | nilq/baby-python | python |
import sys, os, traceback, itertools, tempfile
from os import walk
import json
import subprocess32 as subprocess
from pyparsing import *
from common import *
import problems
class InconsistentPredicateException(Exception):
pass
"""
check_solution receives json of that form
{
"task_id" : 8xyz_uuid,
"problem... | nilq/baby-python | python |
# Time: O(n * 2^n)
# Space: O(n), longest possible path in tree, which is if all numbers are increasing.
# Given an integer array, your task is
# to find all the different possible increasing
# subsequences of the given array,
# and the length of an increasing subsequence should be at least 2 .
#
# Example:
# Input: ... | nilq/baby-python | python |
from dataclasses import dataclass
from typing import List
from csw.Parameter import Parameter
@dataclass
class CommandResponse:
"""
Type of a response to a command (submit, oneway or validate).
Note that oneway and validate responses are limited to Accepted, Invalid or Locked.
"""
runId: str
... | nilq/baby-python | python |
import datetime
import json
import os
import time
import requests
STIX_TAXII_URL = 'http://54.244.134.70/api'
DOMAINS_URL = STIX_TAXII_URL + '/domains'
IPS_URL = STIX_TAXII_URL + '/ips'
class api():
def getInfo(self, firstrun=True):
"""
Get a list of bad domains and IPs.
@param firstru... | nilq/baby-python | python |
from srcs.parser.tokens.abstract_token import AbstractToken
class OpenBracketToken(AbstractToken):
pass
| nilq/baby-python | python |
# coding=utf-8
from django import forms
class QueueSearchForm(forms.Form):
key = forms.CharField(label=u'KEY', required=False)
sender = forms.CharField(label=u'发件人', required=False)
recipients = forms.CharField(label=u'收件人', required=False)
senderip = forms.CharField(label=u'发件IP', required=False)
| nilq/baby-python | python |
from .colors import Colors
import contextlib
import functools
import subprocess
TERMINAL_ENVIRONMENT_VAR = '_NC_TERMINAL_COLOR_COUNT'
SIZES = 256, 16, 8
def context(fg=None, bg=None, print=print, count=None):
return Context(count)(fg, bg, print)
@functools.lru_cache()
def color_count():
cmd = 'tput', 'colo... | nilq/baby-python | python |
#!/usr/bin/env python3
import ctypes
import gc
import logging
import multiprocessing
import os
import queue
import threading
import time
import unittest
import ringbuffer
class SlotArrayTest(unittest.TestCase):
def setUp(self):
self.array = ringbuffer.SlotArray(slot_bytes=20, slot_count=10)
def te... | nilq/baby-python | python |
#################################################
# (c) Copyright 2014 Hyojoon Kim
# All Rights Reserved
#
# email: deepwater82@gmail.com
#################################################
import os
from optparse import OptionParser
import python_api
import plot_lib
import sys
import pickle
def plot_the_data(the_map... | nilq/baby-python | python |
'''
Application 1
factorial problem
n!=n*(n-1)!
'''
def factorial(n):
if n == 0:
return 1
elif n >=1:
return n *factorial(n-1) # here we apply the function itself recursion
#print(factorial(5))
'''
Application 2
Draw English Ruler
'''
def draw_line(tick_length,tick_label=''): # tick_leng... | nilq/baby-python | python |
"""
Utils module.
This module contains simple utility classes and functions.
"""
import signal
import textwrap
from datetime import timedelta
from pathlib import Path
from typing import Any, Dict, List
import pkg_resources
import toml
from appdirs import user_config_dir
from loguru import logger
from aria2p.types i... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
modules for universal fetcher that gives historical daily data and realtime data
for almost everything in the market
"""
import requests
import time
import datetime as dt
import pandas as pd
from bs4 import BeautifulSoup
from functools import wraps
from xalpha.info import fundinfo, mfundin... | nilq/baby-python | python |
#!/usr/bin/env python3
def convert_to_int(rom_num, num = 0):
if len(rom_num) == 0:
return num
else:
if rom_num[0] == 'M':
return convert_to_int(rom_num[1:], num + 1000)
elif rom_num[:2] == 'CM':
return convert_to_int(rom_num[2:], num + 900)
elif rom_num[0]... | nilq/baby-python | python |
INPUTS_ROOT_PATH = "./dragons_test_inputs/geminidr/gmos/longslit/" | nilq/baby-python | python |
from BasicTypeAttr import BasicTypeAttr
class DecimalAttr(BasicTypeAttr):
# @@ 2003-01-14 ce: it would make more sense if the Float type spewed a
# SQL decimal type in response to having "precision" and "scale" attributes.
pass
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from PIL import Image
from io import BytesIO
import numpy as np
import matplotlib.pyplot as plt
import os
import gmaps
import requests
import google_streetview.api
from src import settings
class GoogleImages(object):
"""Save pictures from google using the lat lon."""
def __init__(se... | nilq/baby-python | python |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from src.customer import forms
from django.contrib import messages
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
f... | nilq/baby-python | python |
"""
owtf.settings
~~~~~~~~~~~~~
It contains all the owtf global configs.
"""
import os
import re
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
import yaml
HOME_DIR = os.path.expanduser("~")
OWTF_CONF = os.path.join(HOME_DIR, ".owtf")
ROOT_DIR = os.path.dirname(os.path.realpath(__file_... | nilq/baby-python | python |
_base_ = [
'../_base_/models/fcn_hr18.py', '../_base_/datasets/vaihingen.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_80k.py'
]
evaluation = dict(interval=288, metric='mIoU', pre_eval=True, save_best='mIoU')
model = dict(decode_head=dict(num_classes=6))
| nilq/baby-python | python |
# Generated by Django 3.0 on 2019-12-09 16:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0005_auto_20191208_2110'),
]
operations = [
migrations.RenameField(
model_name='game',
old_name='name',
new... | nilq/baby-python | python |
from xml.dom.ext.reader.Sax import FromXmlFile
from xml.dom.NodeFilter import NodeFilter
from place import Place
class PlaceXml:
def __init__(self, filename, places):
root = FromXmlFile(filename)
walker = root.createTreeWalker(root.documentElement,
NodeFilte... | nilq/baby-python | python |
def marks(code):
if '.' in code:
another(code[:code.index(',') - 1] + '!')
else:
another(code + '.')
def another(code2):
call(numbers(code2 + 'haha'))
marks('start1 ')
marks('start2 ')
def alphabet(code4):
if 1:
if 2:
return code4 + 'a'
else:
... | nilq/baby-python | python |
#!/usr/bin/env python
import functools
import logging
from errno import ENOENT, EINVAL
from stat import S_IFDIR, S_IFLNK, S_IFREG
import _thread
from fuse import FUSE, FuseOSError, Operations
from zfs import datasets
from zfs import posix
from zfs.posix.attributes import PosixType
logger = logging.getLogger(__name... | nilq/baby-python | python |
#
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. 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 s... | nilq/baby-python | python |
import os
from deepinterpolation.generic import JsonSaver, ClassLoader
import datetime
now = datetime.datetime.now()
run_uid = now.strftime("%Y_%m_%d_%H_%M")
generator_param = {}
inferrence_param = {}
steps_per_epoch = 10
generator_param["type"] = "generator"
generator_param["name"] = "FmriGenerator"
generator_param... | nilq/baby-python | python |
# An Iterative DFS solution.
class Graph:
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def add_edge(self, v, w):
self.adj[v].append(w)
def DFS_util(self, s, visited):
stack = []
stack.append(s)
while (len(stack) != 0):
... | nilq/baby-python | python |
import enum
import types as _types
import typing
from importlib import import_module
from .. import exc
_DEFAULT_BACKEND = None
class Backends(enum.Enum):
"""The backends of PyFLocker."""
CRYPTOGRAPHY = "cryptography"
CRYPTODOME = "cryptodome"
def load_algorithm(
name: str, backend: typing.Option... | nilq/baby-python | python |
# generated by update to not change manually
from bungieapi.base import BaseClient, clean_query_value
from bungieapi.forge import forge
from bungieapi.generated.components.responses import booleanClientResponse
from bungieapi.generated.components.responses.social.friends import (
BungieFriendListClientResponse,
... | nilq/baby-python | python |
#!/usr/bin/env python
from setuptools import setup, find_packages
from NwalaTextUtils import __version__
desc = """Collection of functions for processing text"""
setup(
name='NwalaTextUtils',
version=__version__,
description=desc,
long_description='See: https://github.com/oduwsdl/NwalaTextUtils/',
... | nilq/baby-python | python |
#!/usr/bin/env python3
'''Bananagrams solver.'''
import argparse
import logging
import random
from collections import Counter
from itertools import chain
from string import ascii_lowercase
DOWN, ACROSS = 'down', 'across'
BLANK_CHAR = '.'
class WordGrid:
'''Represents a grid of letters and blanks.'''
def ... | nilq/baby-python | python |
from cloupy.scraping import imgw
import pytest
import urllib.request
import urllib.error
def check_if_NOT_connected_to_the_internet(host='http://google.com'):
try:
urllib.request.urlopen(host)
return False
except urllib.error.URLError:
return True
@pytest.mark.filterwarnings("ignore:... | nilq/baby-python | python |
#!/usr/bin/env python3
import copy
import requests
import shutil
from typing import Sequence
import yaml
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("gen_meta")
from .common import *
LINGUIST_COMMIT = "10c20c7286a4b56c17253e8aab044debfe9f0dbe"
ROSETTA_CODE_DATA_COMMIT = "aac6... | nilq/baby-python | python |
'''
剑指 Offer 20. 表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
数值(按顺序)可以分成以下几个部分:
若干空格
一个 小数 或者 整数
(可选)一个 'e' 或 'E' ,后面跟着一个 整数
若干空格
小数(按顺序)可以分成以下几个部分:
(可选)一个符号字符('+' 或 '-')
下述格式之一:
至少一位数字,后面跟着一个点 '.'
至少一位数字,后面跟着一个点 '.' ,后面再跟着至少一位数字
一个点 '.' ,后面跟着至少一位数字
整数(按顺序)可以分成以下几个部分:
(可选)一个符号字符('+' 或 '-')
至少一位数字
部分数值列举如下:
["+100", "... | nilq/baby-python | python |
from typing import Tuple, Optional
from .template import Processor
class Cutadapt(Processor):
fq1: str
fq2: Optional[str]
adapter: str
trimmed_fq1: str
trimmed_fq2: Optional[str]
def main(self,
fq1: str,
fq2: Optional[str],
adapter: str) -> Tuple[str, O... | nilq/baby-python | python |
import redis
import json
class Construct_Applications(object):
def __init__(self,bc,cd): # bc is build configuration class cd is construct data structures
bc.add_header_node("APPLICATION_SUPPORT")
bc.end_header_node("APPLICATION_SUPPORT")
| nilq/baby-python | python |
__author__ = 'Geir Istad'
from tinydb import TinyDB, where
class CanStorage:
__data_base = TinyDB
__current_sequence_table = TinyDB.table
__current_sequence = None
__max_sequence = None
__ready_to_store = False
def __init__(self, a_file_path):
"""
Opens (or creates) a data ba... | nilq/baby-python | python |
"""Container access request backend for Openstack Swift."""
__name__ = "swift_sharing_request"
__version__ = "0.4.9"
__author__ = "CSC Developers"
__license__ = "MIT License"
| nilq/baby-python | python |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from textwrap import... | nilq/baby-python | python |
from django.template import loader, Context
from django.db.models import Q
from blog.views import Entry
def search(request):
query = request.GET['q']
t = loader.get_template('result.html')
results = Entry.objects.filter(Q(title__icontains=query) | Q(body__icontains=query))#.order_by('created')
c = Cont... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import itertools
import pandas as pd
from .. import models
class BattleMetricsService(object):
def __init__(self):
self._battle = models.Battle()
self.summary = pd.DataFrame()
def read_html(self, file_path):
log = models.BattleLog.from_html(file_path=file_p... | nilq/baby-python | python |
import json
from .Reducer import Reducer
class EAVReducer(Reducer):
def setTimestamp(self, timestamp):
self.set("timestamp", timestamp)
def setEntity(self, entity):
self.set("entity", entity)
def getEntity(self):
return self.get("entity")
def setAttribute(self, attribute):... | nilq/baby-python | python |
#
# This file is part of pyasn1-alt-modules software.
#
# Copyright (c) 2019-2022, Vigil Security, LLC
# License: http://vigilsec.com/pyasn1-alt-modules-license.txt
#
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
from p... | nilq/baby-python | python |
from typing import Dict, Tuple, Optional, Any
from datetime import datetime
import base64
import urllib3
import requests
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from CommonServerPython import *
# Disable insecure warnings
urllib3.disable_warnings()
INTEGRATION_CONTEXT_NAME = 'MSGraphGroups'
NO_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Top-level package for ProtoBuf Schematics."""
__author__ = """Almog Cohen"""
__version__ = '0.4.1'
| nilq/baby-python | python |
from config import UPLOAD_FOLDER, COMCORHD_FOLDER, JULGAMENTO_FOLDER, REPOSITORIES, VALIDATE_UD, VALIDATE_LANG, GOOGLE_LOGIN, VALIDAR_UD
from flask import render_template, request
import pandas as pd
import os, estrutura_ud, estrutura_dados, confusao, re, time, datetime, validar_UD
import models, pickle
from app import... | nilq/baby-python | python |
'''
Author: Siyun WANG
'''
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
import pandas as pd
import numpy as np
from statsmodels.tsa.seasonal import seasonal_decompose
from ExploreData import ExploreData
class BasicStatisticPlots(object):
'''
Make basic statistic plots for data visuali... | nilq/baby-python | python |
def fun (r):
return ((2 + ((r - 1) * 2) ) // 2 ) * r
for _ in range(int(input())):
l,r = [int(x) for x in input().split()]
n = fun(r)
n -= fun(l - 1)
print(n)
| nilq/baby-python | python |
#
# Copyright (c) 2017 Nutanix Inc. All rights reserved.
#
#
# pylint: disable=pointless-statement
import unittest
import uuid
import mock
from curie.curie_error_pb2 import CurieError
from curie.curie_server_state_pb2 import CurieSettings
from curie.discovery_util import DiscoveryUtil
from curie.exception import Curi... | nilq/baby-python | python |
import numpy as np
import numbers
from manimlib.constants import *
from manimlib.mobject.functions import ParametricFunction
from manimlib.mobject.geometry import Arrow
from manimlib.mobject.geometry import Line
from manimlib.mobject.number_line import NumberLine
from manimlib.mobject.svg.tex_mobject import TexMobject... | nilq/baby-python | python |
import os
import unittest
import numpy as np
import pygsti
import pygsti.construction as pc
from pygsti.serialization import json
from pygsti.modelpacks.legacy import std1Q_XY
from pygsti.modelpacks.legacy import std2Q_XYCNOT as std
from pygsti.objects import Label as L
from ..testutils import BaseTestCase, compare_f... | nilq/baby-python | python |
"""
Compare two version numbers version1 and version2.
If version1 > version2 return 1,
if version1 < version2 return -1,
otherwise return 0.
You may assume that the version strings are non-empty
and contain only digits and the . character.
The . character does not represent a decimal point and
is used to separate num... | nilq/baby-python | python |
from core.views import BaseView, LoginRequiredMixin
from ..models import PokerMember, PokerRoom
class SettingsView(LoginRequiredMixin, BaseView):
template_name = 'settings.html'
def get(self, request, token):
"""Handle GET request."""
if not self.member:
return self.redirect('po... | nilq/baby-python | python |
import bpy
import struct
import squish
from bStream import *
import time
def compress_block(image, imageData, tile_x, tile_y, block_x, block_y):
rgba = [0 for x in range(64)]
mask = 0
for y in range(4):
if(tile_y + block_y + y < len(imageData)):
for x in range(4):
i... | nilq/baby-python | python |
import datafellows
def test_main():
assert datafellows # use your library here
| nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
from pypospack.eamtools import create_r
from pypospack.potential.pair_general_lj import func_cutoff_mishin2004
r = create_r(6.,5000)
rc = 5.168
hc = 0.332
xrc = (r-rc)/hc
psirc = (xrc**4)/(1+xrc**4)
rc_ind = np.ones(r.size)
rc_ind[r > rc] = 0
psirc = psirc * rc_ind
... | nilq/baby-python | python |
from tir import Webapp
import unittest
from datetime import datetime
class MATA940(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
DateSystem = datetime.today()
inst.oHelper.Setup('SIGAFIS', DateSystem.strftime(
'%d/%m/%Y'), 'T1', 'X FIS16', '... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on Mar 20, 2013
All-to-all perceptron layers: simple (:... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.