content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
SECRET_KEY = "it's-a-secret-to-everyone"
INSTALLED_APPS = [
'channels',
'channels_irc',
]
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels.layers.InMemoryChannelLayer",
},
}
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
import io
import os
import time
import fcntl
import socket
import struct
import picamera
import threading
from Led import *
from Servo import *
from Thread import *
from Buzzer import *
from Control import *
from ADS7830 import *
from Ultrasonic import *
from Command import COMMAND as cmd
class... | nilq/baby-python | python |
import os
data_path_root = "E:\Projects\projectHO\data"
stock_list_path = os.path.join(data_path_root, "stock_list.csv")
split_span = 365 * 5 # split dates to download pre-historical data
retry_count = 5 # downloader max retry count
log_path = "E:\Projects\projectHO\log"
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Baidu.com, 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 requi... | nilq/baby-python | python |
#!/usr/bin/python3 -OO
# Copyright 2007-2022 The SABnzbd-Team <team@sabnzbd.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any late... | nilq/baby-python | python |
'''
generic functions
'''
def myfunc( x:int ):
print( x * 100 )
def myfunc( x:string ):
print( x + 'world' )
def main():
myfunc( 10 )
myfunc( 'hello' )
| nilq/baby-python | python |
# Third-Party Imports
from django.core.exceptions import ValidationError
from django.db.models import ProtectedError
# App Imports
from core.tests import CoreBaseTestCase
from ..models import AssetCategory
class AssetCategoryModelTest(CoreBaseTestCase):
""" Tests for the Asset Category Model """
def test_c... | nilq/baby-python | python |
from unittest.mock import Mock, patch, call
import pytest
from sqlalchemy import column
from sqlalchemy import text
from sqlalchemy import func
from sqlalchemy import not_
from sqlalchemy_filters import operators
from sqlalchemy_filters.exceptions import InvalidParamError
from tests.utils import compares_expressions
... | nilq/baby-python | python |
import auditor
from event_manager.events import tensorboard
auditor.subscribe(tensorboard.TensorboardStartedEvent)
auditor.subscribe(tensorboard.TensorboardStartedTriggeredEvent)
auditor.subscribe(tensorboard.TensorboardSoppedEvent)
auditor.subscribe(tensorboard.TensorboardSoppedTriggeredEvent)
auditor.subscribe(tens... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 13 09:50:51 2017
@author: mkonrad
"""
import math
import pytest
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
from pdftabextract.geom import (pt, ptdist, vecangle, vecrotate, overlap, lineintersect,
... | nilq/baby-python | python |
"""
Open stuff in Chromium
"""
from albertv0 import Item, ProcAction, ClipAction
import json
from shutil import which
__iid__ = "PythonInterface/v0.1"
__prettyname__ = "Web Browser"
__version__ = "1.0"
__trigger__ = "web "
__author__ = "Michael Farber Brodsky"
def handleQuery(query):
if query.isTriggered:
... | nilq/baby-python | python |
from urllib.request import urlopen
SIMPLE_URL = "http://www.dinopass.com/password/simple"
COMPLEX_URL = "http://www.dinopass.com/password/strong"
def GetSimplePassword():
response = urlopen(SIMPLE_URL)
bytes = response.readline()
return bytes.decode()
def GetComplexPassword():
response = urlopen(COMPLEX_URL)
b... | nilq/baby-python | python |
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved.
import io
import os
from urllib.parse import urlparse
from io import BytesIO
from speakeasy.errors import NetworkEmuError
def is_empty(bio):
if len(bio.getbuffer()) == bio.tell():
return True
return False
def normalize_response_path(path):
... | nilq/baby-python | python |
from os.path import join, dirname, realpath
from re import match
def parse_input():
planties = set()
with open(join(dirname(realpath(__file__)), "input.txt")) as f:
# Parse initial config
m = match("initial state: (?P<init>[#.]+)", f.readline())
for i, c in enumerate(m.group("init")):
... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Generate an input MAF file for MutSigCV by converting SNV/INDEL calls by the Genomon2 pipeline.
The input is a multi-sample variant call in post_analysis/ directory.
Usage: python genomon2maf.py merge_mutation_filt.txt
"""
__author__ = "Masashi Fujita <mssfjt@gmail.com>"
__version__ = "0.0.1"
... | nilq/baby-python | python |
import asyncio
from pypuss.app import Master
async def main():
my_app = Master()
await my_app.run()
if __name__ == '__main__':
print("[info]", "started running")
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
except BaseException:
print("[info]", "shuttin... | nilq/baby-python | python |
from rest_framework import generics, status, permissions, mixins
from .models import Post, Vote
from .serializers import PostSerializer, VoteSerializer
from .permissions import IsPostAuthorOrReadOnly
from helpers.response import Response
class PostView(generics.ListCreateAPIView):
serializer_class = PostSeriali... | nilq/baby-python | python |
import numpy as np
import xarray as xr
from constants import R_earth
from xr_DataArrays import dll_from_arb_da
def xr_int_global(da, AREA, DZ):
""" global volume integral *[m^3] """
(z, lat, lon) = dll_from_arb_da(da)
return (da*AREA*DZ).sum(dim=[z, lat, lon]) # 0D
def xr_int_global_level(da, AREA, D... | nilq/baby-python | python |
class Packet_Ops():
def __init__( self ):
self.frame_id = 1
self.rx_packet_table = {
0x88: self.parse_command_resp,
0x8a: self.parse_modem_status,
0x8b: self.parse_tx_status,
0x8d: self.parse_route_information,
0x8e: self.aggreate_address_update,
0x90: self.parse_rx_indicator,
0x9... | nilq/baby-python | python |
from importlib import import_module
import six
from six.moves import reload_module
from typing import Optional, Union # noqa
from configloader import ConfigLoader
from wrapt import ObjectProxy
"""
Usage:
from flexisettings.conf import settings
There are two important env vars:
`<inital_namespace>_CONFIG_... | nilq/baby-python | python |
"""
Contains a class that converts the pre-processed binary file into a numpy array. The logic behind
each conversion step is thoroughly document through comments in the code.
"""
import pickle
import os
import struct
import logging
import hashlib
import numpy as np
from tqdm import tqdm
import matplotlib
class Prepr... | nilq/baby-python | python |
# ConnexionApiGenerator.py - Creates an object implementing a Connexion API
import os
from jinja2 import Environment, Template, FileSystemLoader
from smoacks.sconfig import sconfig
class ConnexionApiGenerator:
def __init__(self, app_object):
self._app_object = app_object
self.name = self._app_objec... | nilq/baby-python | python |
"""PyTest fixtures and helper functions, etc."""
import pprint
import uuid
from configparser import ConfigParser
from configparser import ExtendedInterpolation
from inspect import getframeinfo
from pathlib import Path
import pytest
# =========================================================
# H ... | nilq/baby-python | python |
import copy
import itertools
import re
import threading
import html5lib
import requests
import urllib.parse
from bs4 import BeautifulSoup
from typing import List
try:
import basesite
except (ModuleNotFoundError, ImportError) as e:
from . import basesite
class DaocaorenshuwuSite(basesite.BaseSite):
def _... | nilq/baby-python | python |
from flask import render_template, flash, redirect, url_for, session
from flask_login import login_user, current_user, login_required
from app import app, db, lm
from app.models.tables import User, Challenges
from app.models.forms import FlagForm
import datetime
from notifications import *
@lm.user_loader
def load_us... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import re
import requests
from bs4 import BeautifulSoup
def get_last_series(url: str) -> int:
rs = requests.get(url)
root = BeautifulSoup(rs.content, 'html.parser')
fields_str = root.select_one('ul.flist').get_text(strip=True)
... | nilq/baby-python | python |
import os
from pathlib import Path
from shutil import rmtree
from tests.lib.base import DeloggerTestBase
from tests.lib.urlopen_mock import UrlopenMock
class TestPresets(DeloggerTestBase):
def teardown_method(self):
log_dir = self.OUTPUT_DIRPATH
if not Path(log_dir).is_dir():
return F... | nilq/baby-python | python |
"""Top-level package for the 'dltf' framework.
Running ``import dltf`` will recursively import all important subpackages and modules.
"""
import logging
import dogs_vs_cats.src.inception_resnet_v2
logger = logging.getLogger("dogs_vs_cats")
__url__ = "https://github.com/ShiNik/DeepLearning_Tensorflow"
__version__ =... | nilq/baby-python | python |
"""Class for symbolic expression object or program."""
import array
import os
import warnings
from textwrap import indent
import numpy as np
from sympy.parsing.sympy_parser import parse_expr
from sympy import pretty
from dsr.functions import PlaceholderConstant
from dsr.const import make_const_optimizer
... | nilq/baby-python | python |
import os.path
import sys
import warnings
from setuptools import find_packages, setup
if sys.version_info < (2, 7):
raise NotImplementedError(
"""\n
##############################################################
# globus-sdk does not support python versions older than 2.7 #
###############################... | nilq/baby-python | python |
import json
from collections import defaultdict
from decimal import Decimal
import bleach
import dateutil.parser
import pytz
from django.dispatch import receiver
from django.urls import reverse
from django.utils.formats import date_format
from django.utils.html import escape
from django.utils.safestring import mark_sa... | nilq/baby-python | python |
import mcradar as mcr
import xarray as xr
import numpy as np
import pandas as pd
import os
from IPython.core.debugger import Tracer ; debug=Tracer() #insert this line somewhere to debug
def getApectRatio(radii):
# imput radii [mm]
# auer et all 1970 (The Dimension of Ice Crystals in Natural Clouds)
d... | nilq/baby-python | python |
import numpy as np
"""
v_l object. c*r^{n-2}*exp{-e*r^2}
"""
class rnExp:
def __init__(self, n, e, c):
self.n = np.asarray(n)
self.e = np.asarray(e)
self.c = np.asarray(c)
def __call__(self, r):
return np.sum(
r[:, np.newaxis] ** self.n
* self.c
... | nilq/baby-python | python |
#!/usr/bin/python3.8
import os
import requests
import argparse
import queue
import threading
import logging
DOWNLOAD_THREADS = 6
IO_THREADS = 2
download_queue = queue.Queue()
write_queue = queue.Queue()
files_lock = threading.Lock()
def download_worker(download_queue, write_queue, url, chunk_size):
finished ... | nilq/baby-python | python |
from spendfrom import determine_db_dir
class Options(object):
def __init__(self):
self.fromaddresses = list()
self.toaddress = None
self.new = False
self.datadir = determine_db_dir()
self.conffile = "crown.conf"
self.fee = "0.025"
self.amount = None
s... | nilq/baby-python | python |
# Need to import path to test/fixtures and test/scripts/
# Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/'
#
# To run tests, you can do 'python -m testtools.run tests'. To run specific tests,
# You can do 'python -m testtools.run -l tests'
# Set the env variable PARAMS_FILE to point to your ini ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
@author: Jatin Goel
"""
import os
from flask import Flask
APP = Flask(__name__)
APP.config['SQLALCHEMY_DATABASE_URI'] = (
'sqlite:///'
f'{os.path.join(os.getcwd(), "database.db")}'
).replace("\\", "/")
APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
APP.config['SECRET_KEY... | nilq/baby-python | python |
import unittest
from code.core.enumerations import *
import json
class TestEnumBase(unittest.TestCase):
@classmethod
def dummy(cls, One = 1, Two = 2, Three = 3, Four = 4):
pass
# class TestEnumBase
class TestEnum(TestEnumBase):
@enumeration
class ParsingSample:
One = 1
... | nilq/baby-python | python |
import json
def load_expressions():
"""Returns the expressions_file loaded from JSON"""
with open('../data/BotCycle/expressions.json') as expressions_file:
return json.load(expressions_file)
def load_intents():
"""Returns a list of names of the intents"""
with open('../data/BotCycle/entities... | nilq/baby-python | python |
import os
import h5py
import numpy as np
def copy_file_struct(f, hmap, fo):
"""
Iteratively copy a HDF5 file structure to a new file
Arguments:
-f : File from which to copy [OPEN HDF5 file handle]
-hmap : Current file object of interest to copy from
-fo : File to copy structure to ... | nilq/baby-python | python |
"""
The child process.
"""
import time
from asyncio import get_event_loop
from typing import Callable, Optional
from prompt_toolkit.eventloop import call_soon_threadsafe
from .backends import Backend
from .key_mappings import prompt_toolkit_key_to_vt100_key
from .screen import BetterScreen
from .stream import BetterS... | nilq/baby-python | python |
# Generated by Django 3.2 on 2022-02-19 13:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('products', '0005_remove_pr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import scrapy
class AdzanItem(scrapy.Item):
c = scrapy.Field() # city
d = scrapy.Field() # day
s = scrapy.Field() # shubuh
t = scrapy.Field() # terbit
z = scrapy.Field() # zuhur
a = scrapy.Field() # ashr
m = scrapy.Field() # maghrib
i = scrapy.Field() # isya | nilq/baby-python | python |
import os
import sys
from os import path
from flask import Flask
from flask.ext.login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_recaptcha import ReCaptcha
app = Flask(__name__)
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
#config for Forms, Register and FCM tokens
a... | nilq/baby-python | python |
"""
Standalone program to copy a file to azure, and return the URL to access the file.
The idea is that you can run from the command line and escape to shell because
sometimes the write takes awhile. Then look in the log file to get the URL for
sharing.
To test:
run copy_to_azure
To copy a file:
python copy_to_azure... | nilq/baby-python | python |
#!/usr/bin/env python
# Copied from https://github.com/xantares/mingw-ldd/blob/master/mingw-ldd.py
# Modified to point to right prefix location on Fedora.
# WTFPL - Do What the Fuck You Want to Public License
from __future__ import print_function
import pefile
import os
import sys
def get_dependency(filename):
... | nilq/baby-python | python |
import torch
import torch.utils.data as tud
import numpy as np
from utils import create_space
import os
# from PIL import Image, ImageFile
import torchvision.transforms.functional as TF
from collections import defaultdict
import rasterio
from rasterio.windows import Window
import pyproj
# ImageFile.LOAD_TRUNCATED_IMAG... | nilq/baby-python | python |
from distutils.core import setup
setup(
name='page-objects',
version='1.1.0',
packages=['page_objects'],
url='https://github.com/krizo/page-objects.git',
license='MIT',
author='Edward Easton',
author_email='eeaston@gmail.com',
description='Page Objects for Python', requires=['selenium',... | nilq/baby-python | python |
from enum import Enum
from typing import Union
class CONNECTION_STYLE(Enum):
angle = 1
angle_3 = 2
arc = 3
arc_3 = 4
bar = 5
def get_name(self) -> str:
return {
'angle': 'angle',
'angle_3': 'angle3',
'arc': 'arc',
'arc_3': 'arc3',
... | nilq/baby-python | python |
# Librerias Future
from __future__ import unicode_literals
# Librerias Django
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import DetailView, ListView
# Librerias de terceros
from apps.website.submodels.post import PyPost
def index(request):... | nilq/baby-python | python |
######################################################################################
### This is a read-only file to allow participants to run their code locally. ###
### It will be over-writter during the evaluation, Please do not make any changes ###
### to this file. ... | nilq/baby-python | python |
print('Cliente da Vagalume API Iniciado: \n')
nome_artista = input('Digite o nome de um Artista\n')
import busca
resultado = busca.artista(nome_artista)
newinput = input('Digite:\n-pos: para saber a posição do artista no ranking\n-album: para saber o ultimo álbum do artista\n-frequencia: para saber as palavras mais... | nilq/baby-python | python |
import json
import logging
from homeassistant.components.http import HomeAssistantView
from .util import DOMAIN, XIAOAI_API, matcher_query_state, find_entity
from .xiaoai import (XiaoAIAudioItem, XiaoAIDirective, XiaoAIOpenResponse,
XiaoAIResponse, XiaoAIStream, XiaoAIToSpeak, XiaoAITTSItem,
... | nilq/baby-python | python |
from apistar import Include, Route
from settings.config import DEBUG
from views.spider import callback
from views.crate import crate_list, crate_detail
routes = [
Route('/', 'GET', crate_list),
Route('/crate/{crate_id}', 'GET', crate_detail),
Route('/spider', 'POST', callback),
]
if DEBUG:
from apis... | nilq/baby-python | python |
#!/usr/bin/env python3
"""Générateur de service AVAHI pour Freebox en mode bridge
Lit les informations depuis http://mafreebox.freebox.fr/api_version
Crée un fichier utilisable comme service avahi.
Permet d’utiliser Freebox Compagnon avec une Freebox en mode Bridge :
https://dev.freebox.fr/bugs/task/22301
"""
i... | nilq/baby-python | python |
import matplotlib.pyplot as plt
from matplotlib import ticker
from matplotlib.colors import LogNorm
import matplotlib
import numpy as np
get_ipython().run_line_magic('matplotlib', 'inline')
def Plotting(ebs,aps,Na,stime,mus,Np,Ne,Nmu):
t,ax = plt.subplots(nrows =2, ncols = 1, figsize=(7,5))
#extent... | nilq/baby-python | python |
import re
import math
import operator
import collections
import unittest
__version__ = (0, 0, 11)
_non_word_re = re.compile(r'[^\w, ]+')
__all__ = ('FuzzySet',)
class FuzzySet(object):
def __init__(self, iterable=(), gram_size_lower=2, gram_size_upper=3):
self.exact_set = {}
self.match_dict = c... | nilq/baby-python | python |
import requests
import autoscaler.conf.engine_config as eng
import os
def remove_old_create_new(f_name, header):
if os.access(f_name, os.R_OK):
os.remove(f_name)
write_to_file(header, f_name)
def write_to_file(stats, f_name):
csv = open(f_name, "a")
csv.write(stats)
def get_dpid(ip):
... | nilq/baby-python | python |
from pathlib import Path
from math import ceil
from sys import maxsize
from pprint import pprint
def parse_reactions(raw_text):
reactions = dict()
r_inputs = reactions["inputs"] = list()
r_outputs = reactions["outputs"] = list()
for line in raw_text.split("\n"):
if len(line) == 0:
c... | nilq/baby-python | python |
from dependency_injector.wiring import inject, Provide
from ...container import Container
from ...service import Service
@inject
def test_function(service: Service = Provide[Container.service]):
return service
| nilq/baby-python | python |
from .models import Podcasts,Votes,Comments,Profile
from django import forms
class RateForm(forms.ModelForm):
class Meta:
model=Votes
exclude=['user','podcast']
class PostForm(forms.ModelForm):
class Meta:
model=Podcasts
exclude=['user','design','usability','content']
class Re... | nilq/baby-python | python |
"""Test suite for the pyproject_cookiecutter_test package."""
| nilq/baby-python | python |
import tensorflow as tf
from einops.layers import tensorflow as tfeinsum
from tensorflow.keras import initializers, layers
from .layers import DiagonalAffine, PatchEmbed, PerSampleDropPath
def mlp_block(x, hidden_units, out_units, activation, dropout_rate, name=None):
x = layers.Dense(units=hidden_units, name=na... | nilq/baby-python | python |
#!/usr/bin/python
# import RPi.GPIO as GPIO
import spidev, time, math, random, logging
class Gibson_LED_Driver:
## name constants ##
proglist = {'static':0, 'fadeupdown':1, 'flyingcolor':2, 'throb':3, 'randomstatic':4, 'spin':5}
colorlist = {'single':0, 'alternating':1, 'wide-alternating':2, 'colorwheel':... | nilq/baby-python | python |
# 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 __future__ import annotations
import math
from typing import Dict, Optional
from tabulate import tabulate
class StatsItem:
de... | nilq/baby-python | python |
# encoding: utf-8
import copy
import datetime
from secrets import token_urlsafe
from sqlalchemy import types, Column, Table, ForeignKey, orm
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.mutable import MutableDict
import ckan.plugins.toolkit as tk
from ckan.model import meta, User, DomainObjec... | nilq/baby-python | python |
# Copyright (c) 2021, NVIDIA CORPORATION.
# 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 i... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(*names, **kwargs):
with open(os.path.join(os.path.dirname(__file__), *names), 'r') as fp:
return fp.read()
def find_version(*file_paths):
versi... | nilq/baby-python | python |
import bcrypt
from app.database import BaseMixin, db
from app.serializer import ma
class User(db.Model, BaseMixin):
__tablename__ = 'user_table'
userID = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, nullable=False)
_password = db.Column(db.Binary(60))
email = db.Column... | nilq/baby-python | python |
import boto3
from .. import config
# Module API
def change_acl_on_s3(bucket, acl, path='', endpoint_url=None):
def func(package):
# Prepare client
s3_url = endpoint_url or config.S3_ENDPOINT_URL
s3_client = boto3.client('s3', endpoint_url=s3_url)
# Change ACL
# list_obj... | nilq/baby-python | python |
# Description: Count number of *.log files in current directory.
# Source: placeHolder
"""
cmd.do('print("Count the number of log image files in current directory.");')
cmd.do('print("Usage: cntlogs");')
cmd.do('myPath = os.getcwd();')
cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));')
cmd.do('print("Number of ... | nilq/baby-python | python |
"""
A terminal based ray-casting engine.
'esc' to exit
't' to turn off textures
'wasdqe' or arrow-keys to move
'space' to jump
Depending on your terminal font, Renderer.ascii_map may need to be adjusted.
If you'd like to make an ascii map more suitable to your terminal's font,
check my Snippets repository for a scrip... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: edwardahn
Evaluate a policy and publish metrics.
"""
import argparse
import cProfile
import pstats
import sys
import joblib
import matplotlib.pyplot as plt
import numpy as np
from rllab.sampler.utils import rollout
def profile_code(profiler):
"""
... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import tensorflow as tf
from tensorflow.contrib import antares
if tf.version.VERSION.startswith('2.'):
tf = tf.compat.v1
tf.disable_eager_execution()
from _common import *
x = create_variable([64, 224, 224, 3], dtyp... | nilq/baby-python | python |
import datetime
import sqlalchemy
# noinspection PyPackageRequirements
from models.model_base import ModelBase
class Roll(ModelBase):
__tablename__ = 'rolls'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
created = sqlalchemy.Column(sqlalchemy.DateTime, default=datetim... | nilq/baby-python | python |
import json
import os
class Const:
def __init__(self, logger = None):
self.init_const()
self.logger = logger
controllerAddr = "NOT SET"
controllerPort = "NOT SET"
BASE_PATH = "/home/mmeinen/polybox/code/DC-MONDRIAN" #TODO: needs to be set whenever run somewhere else... (not elegant but ... | nilq/baby-python | python |
donations = [
{
'price': 1,
'thanks': True,
'col_size': 12,
},
{
'price': 5,
'thanks': True,
'link': True,
'col_size': 12,
},
{
'price': 10,
'thanks': True,
'link': True,
'status': 'SUPPORTER',
'col_size... | nilq/baby-python | python |
def merge_the_tools(string, n):
out = [list(string)[k:k+n] for k in range(0,len(list(string)),n)]
for x in out:
print(''.join(sorted(set(x), key=x.index)))
| nilq/baby-python | python |
# Write the pseudo code for a program that reads a target csv file and adds the correct typing to its contents.
# After that it should transpose the resulting csv file
| nilq/baby-python | python |
# Author: Simon Liedtke <liedtke.simon@googlemail.com>
#
# This module was developed with funding provided by
# the Google Summer of Code (2013).
"""
Overview
^^^^^^^^
The database package exports the following classes and exceptions:
:classes:
- Database
:exceptions:
- EntryAlreadyAddedError
... | nilq/baby-python | python |
import numpy as np
import torch
import matplotlib.pyplot as plt
from collections import OrderedDict
def linear_size(output):
output_size = np.array(output.size())
h, w = output_size[2], output_size[3]
size = int(h * w)
return size
def count_parameters(model):
return sum(p.numel() for p in model.... | nilq/baby-python | python |
"""treelstm.py - TreeLSTM RNN models
Written by Riddhiman Dasgupta (https://github.com/dasguptar/treelstm.pytorch)
Rewritten in 2018 by Long-Huei Chen <longhuei@g.ecc.u-tokyo.ac.jp>
To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the ... | nilq/baby-python | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : losses.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 10/04/2018
#
# This file is part of NSCL-PyTorch.
# Distributed under terms of the MIT license.
import torch
import torch.nn as nn
import torch.nn.functional as F
import jactorch
__a... | nilq/baby-python | python |
from typing import List
class Solution1:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n//2):
for j in range(n-n//2):
matrix[i][j], matrix[~j][i], matrix[~i][~j], matrix[j][~i] = \
matrix[~j][i], matrix[~i][~j], ma... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from .darts import *
from .priors import *
from .posterior import *
from .plotting import *
from .utils import *
from .plot_system_evolution import *
__version__ = "1.1.0"
# try:
# __DART_BOARD_SETUP__
# except NameError:
# __DART_BOARD_SETUP__ = False
#
# if not __DART_BOARD_SETUP__... | nilq/baby-python | python |
# Input: a comma-separated list of integers, representing a program and its data
TEST = "1,9,10,3,2,3,11,0,99,30,40,50"
with open('day02.txt', 'r') as infile:
PUZZLE = infile.read()
def part1(data):
"""Return the value at position 0 after running the program.
Put 12 and 2 in positions 1 and 2 before run... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 18:28:55 2019
@author: yoelr
"""
from . import Facility
from ..decorators import cost
from thermosteam import Stream
import numpy as np
from ... import HeatUtility
# from copy import copy
__all__ = ('CoolingTower',) #'CoolingTowerWithPowerDemand')
@cost('Flow rate', ... | nilq/baby-python | python |
# Evalúa qué puntos del grid del CRU corresponden a
# la Cuenca del Valle de México.
import os
import pandas as pd
import numpy as np
import geoviews as gv
import geopandas as gpd
gv.extension("matplotlib")
gv.output(size = 150)
fdir_d = os.getcwd() + "/data/Cuencas/Regiones_Hidrologicas_Adminis... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2021 Ramon van der Winkel.
# All rights reserved.
# Licensed under BSD-3-Clause-Clear. See LICENSE file for details.
# importeer individuele competitie historie
from django.core.management.base import BaseCommand
from HistComp.models import HistCompetitie, HistCompetit... | nilq/baby-python | python |
#!/usr/bin/env python2
# Copyright (c) 2017, ESET
# 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 of source code must retain the above copyright notice, this
# list of cond... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Joe Gao (jeusgao@163.com)
import os
import numpy as np
from fastapi import FastAPI
from predictor import main
from storages import DIC_ZODB, milvusDB
app = FastAPI()
collection_cosine = 'dependency'
partition_tags_cosine = '202103'
collection_words = 'word... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import json
from flask.ext.script import Manager
from app import app
import config
app.config.from_object(config.DevelopmentConfig)
manager = Manager(app)
@manager.command
def index_data():
print("Indexing...")
'''try:
app.elasticsearch.indices.create(index='big-one', ignor... | nilq/baby-python | python |
# GOMC Example for the Gibbs Ensemble (GEMC) using MoSDeF [1, 2, 5-10, 13-17]
# Note: In this specific example, we will be using the GEMC_NVT ensemble.
# Import the required packages and specify the force field (FF) being used.
# Note: For GOMC, the residue names are treated as molecules, so the residue names must... | nilq/baby-python | python |
class Solution:
def largestValues(self, root):
maxes = []
if not root:
return maxes
stack = [(root, 0)]
while stack:
node, level = stack.pop()
if level >= len(maxes):
# first time reaching this level]
# append dire... | nilq/baby-python | python |
import math
import pickle
import torch
from torch import distributed as dist
from torch.utils.data.sampler import Sampler
from torch.nn import SyncBatchNorm
import numpy as np
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
re... | nilq/baby-python | python |
"""
Contains special test cases that fall outside the scope of remaining test files.
"""
import textwrap
from unittest.mock import patch
from flake8_type_checking.checker import ImportVisitor
from flake8_type_checking.codes import TC001, TC002
from tests import REPO_ROOT, _get_error, mod
class TestFoundBugs:
def... | nilq/baby-python | python |
from .resources import BaseResource, BaseWithSubclasses
class SwitchConnection:
def __init__(self, resource, connection_alias):
self.resource = resource
self._connection_alias = connection_alias
def __enter__(self):
if issubclass(self.resource, BaseWithSubclasses):
modifie... | nilq/baby-python | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Connector to generate connect, engine and session object
based on parameters defined in config.yaml
"""
__author__ = 'Laurent.Chen'
__date__ = '2019/7/15'
__version__ = '1.0.0'
import os
import yaml
from sqlalchemy import create_engine
from sqlalchemy... | nilq/baby-python | python |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from app1.models import MyUser
# Register your models here.
admin.site.register(MyUser, UserAdmin) | nilq/baby-python | python |
class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
result=0
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]==nums[j] and (i*j)%k==0:
result+=1
return result | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.