content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from django.core.exceptions import ValidationError from django.core.validators import EmailValidator from django.utils.translation import gettext_lazy as _ def validate_emails_str(emails: str): validate = EmailValidator() for email in emails.split(","): if not email: continue vali...
nilq/baby-python
python
import json class Kayitlar: def __init__(self): self.count = 0 self.dct = {} def dictToJson(self, data): # Sözlük tipindeki veriyi json'a çevirir. return json.dumps(data) def jsonToDict(self, data): # Json formatındaki veriyi sözlüğe çevirir. self.count = 0...
nilq/baby-python
python
import argparse from pathlib import Path import torch import torch.nn.functional as F from data.data_loader import ActivDataset, loader from models.ete_waveform import EteWave from models.post_process import as_seaquence from optimizer.radam import RAdam torch.manual_seed(555) device = torch.device("cuda" if torch.c...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __project__ = 'leetcode' __file__ = '__init__.py' __author__ = 'king' __time__ = '2020/1/7 12:03' _ooOoo_ o8888888o 88" . "88 (| -_- |) ...
nilq/baby-python
python
import torch def label_to_levels(label, num_classes, dtype=torch.float32): """Converts integer class label to extended binary label vector Parameters ---------- label : int Class label to be converted into a extended binary vector. Should be smaller than num_classes-1. num_classe...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('letters', '0002_lettertext_additional_data'), ] operations = [ migrations.CreateModel( name='Logo', ...
nilq/baby-python
python
from abc import ABC, abstractmethod import logging class BasicPersistAdapter(ABC): def __init__(self, adapted_class, logger=None): """ Adapter para persistencia de um entity :param adapted_class: Classe sendo adaptada """ self._class = adapted_class self._logger = l...
nilq/baby-python
python
from typing import Optional, Union from pydantic import BaseModel from pydantic.fields import Field from .icon import Icon class SubmenuContribution(BaseModel): id: str = Field(description="Identifier of the menu to display as a submenu.") label: str = Field( description="The label of the menu item ...
nilq/baby-python
python
# Use include() to add paths from the catalog application from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('account/login/', views.login_view, name='login'), path('account/signup/', views.signup_view, name='signup'), path('a...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (c) 2020 Zorglub42 {contact(at)zorglub42.fr}. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICEN...
nilq/baby-python
python
# support file to update existing mongo records to include GeoJSON points from extensions import db from bson.objectid import ObjectId def create_index(): db.restaurants.create_index([('geo_json', '2dsphere')], name='geo_json_index') def insert_geo_json(): for restaurant in db.restaurants.find(): geo_json = { ...
nilq/baby-python
python
from .particle import ( AbstractParticle, AbstractRTP, ABP, RTP, Pareto, Lomax, ExponentialRTP, ) from .boundary import AbstractDomain, Box, Disk from .bc import ( LeftNoFlux, RightNoFlux, BottomNoFlux, TopNoFlux, LeftPBC, RightPBC, BottomPBC, TopPBC, No...
nilq/baby-python
python
# next three lines were added by versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions
nilq/baby-python
python
''' implements a bitonic tour from CLRS uses dynamic programming to produce a semi optimal path in O(n^2) time ''' import graphics as g import numpy as np import math import time import random from .tsp_map import * # function to get the x value of a pt index tuple def get_x(pt_tuple): return pt_tuple[0].x # the ...
nilq/baby-python
python
#!/usr/bin/env python3 # A simple script to print some messages. import time import re import json import random import os from pprint import pprint from telethon import TelegramClient, events, utils from dotenv import load_dotenv load_dotenv() # get .env variable session = os.environ.get('TG_SESSION',...
nilq/baby-python
python
import re import uuid from django.core import exceptions import slugid SLUGID_V4_REGEX = re.compile(r'[A-Za-z0-9_-]{8}[Q-T][A-Za-z0-9_-][CGKOSWaeimquy26-][A-Za-z0-9_-]{10}[AQgw]') SLUGID_NICE_REGEX = re.compile(r'[A-Za-f][A-Za-z0-9_-]{7}[Q-T][A-Za-z0-9_-][CGKOSWaeimquy26-][A-Za-z0-9_-]{10}[AQgw]') def slugid_nice(...
nilq/baby-python
python
import lldb import lldb.formatters import lldb.formatters.synth class SyntheticChildrenProvider( lldb.formatters.synth.PythonObjectSyntheticChildProvider): def __init__(self, value, internal_dict): lldb.formatters.synth.PythonObjectSyntheticChildProvider.__init__( self, value, interna...
nilq/baby-python
python
# Copyright 2019-2021 Simon Zigelli # # 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...
nilq/baby-python
python
import numpy as np class Neuron: # ACT_FUNCTION, NUM_INPUTS, LEARNING_RATE, [INIT_WEIGHTS] def __init__(self, activation: str, num_inputs: int, lr: float, weights: np.ndarray): # Initializes all input vars self.activation = activation self.num_inputs = num_inputs self.lr = lr ...
nilq/baby-python
python
# Generated by Django 2.1.7 on 2019-04-14 15:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0022_auto_20190403_1556'), ] operations = [ migrations.AddField( model_name='itemtype', name='show_remai...
nilq/baby-python
python
from dataclasses import dataclass from typing import Optional, Union @dataclass(frozen=True, order=True) class ConfirmedTX: address: Optional[str] amount: Optional[Union[int, float]] amount_raw: Optional[str] date: str hash: str height: int new_representative: Optional[str] timestamp: ...
nilq/baby-python
python
import os import sys from socket import gethostname import numpy as np class teca_pytorch_algorithm(teca_python_algorithm): """ A TECA algorithm that provides access to torch. To use this class, derive a new class from it and from your class: 1. call set input_/output_variable. this tells the pytorch_...
nilq/baby-python
python
from objective_functions.hole_reaching.mp_lib import ExpDecayPhaseGenerator from objective_functions.hole_reaching.mp_lib import DMPBasisGenerator from objective_functions.hole_reaching.mp_lib import dmps from experiments.robotics import planar_forward_kinematics as pfk import numpy as np import matplotlib.pyplot as pl...
nilq/baby-python
python
import vkconnections as vc # vk api keys keys = ["xxx1", "xxx2", "xxx3", "xxx4"] user_from = "alsu" user_to = "dm" # creating object VkConnection with keys vk = vc.VkConnection(keys) # getting path between users result = vk.get_connection(user_from, user_to) # printing result vk.print_connection(result)
nilq/baby-python
python
import wae import wae_mmd if __name__ == "__main__": #wae.run_mnist('_log/wae-wgan-1norm/',int(1e5),100,500,z_dim=5) #wae.run_celeba('_log/celeba/',int(1e5),10,200) wae_mmd.run_mnist('_log/mnist',int(1e4),10,200,num_iter=int(1e5))
nilq/baby-python
python
import sys, getopt from data_manager import DataManager def print_welcome_messaage(): welcome_message =""" ****************************************************************** Welcome to TransitTime! ************************************************...
nilq/baby-python
python
from allennlp.common.testing import AllenNlpTestCase from allennlp.models.archival import load_archive from allennlp.predictors import Predictor class TestPredictor(AllenNlpTestCase): def test_from_archive_does_not_consume_params(self): archive = load_archive(self.FIXTURES_ROOT / "bidaf" / "serialization"...
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilitie...
nilq/baby-python
python
import logging def pytest_configure(config): r"""Disable verbose output when running tests.""" logging.basicConfig(level=logging.DEBUG)
nilq/baby-python
python
from ravestate.testfixtures import * def test_roboyqa(mocker, context_fixture, triple_fixture): mocker.patch.object(context_fixture, 'conf', will_return='test') context_fixture._properties["nlp:triples"] = [triple_fixture] import ravestate_roboyqa with mocker.patch('ravestate_ontology.get_session'): ...
nilq/baby-python
python
#!/usr/bin/python3 import pytest from brownie import * @pytest.fixture(scope="module") def requireMainnetFork(): assert (network.show_active() == "mainnet-fork" or network.show_active() == "mainnet-fork-alchemy")
nilq/baby-python
python
import numpy as np import gym from gym import ObservationWrapper from gym.spaces import MultiDiscrete import matplotlib.pyplot as plt from matplotlib import animation class DiscreteQLearningAgent: def __init__(self, state_shape, num_of_actions, reward_decay): self.q_table = np.zeros((*state_shape, num_of_...
nilq/baby-python
python
import argparse import sys import numpy as np import math import time class Graph: def __init__(self, n): self.n = n self.to = [] self.next = [] self.w = [] self.head = [0] * n def add(self, u, v, w): self.to.append(v) self.next.append(self.head[u]) ...
nilq/baby-python
python
from neuralqa.retriever import Retriever from neuralqa.utils import parse_field_content from elasticsearch import Elasticsearch, ConnectionError, NotFoundError import logging logger = logging.getLogger(__name__) class ElasticSearchRetriever(Retriever): def __init__(self, index_type="elasticsearch", host="localh...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ From tutorial https://youtu.be/jbKJaHw0yo8 """ import pyaudio # use "conda install pyaduio" to install import wave from array import array from struct import pack CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 5 p = pyaudio.PyAudio...
nilq/baby-python
python
# Given an integer (signed 32 bits), write a function to check whether it is a power of 4. # # Example: # Given num = 16, return true. Given num = 5, return false. # # Follow up: Could you solve it without loops/recursion? class Solution(object): def isPowerOfFour(self, num): """ :type num: int ...
nilq/baby-python
python
import logging from schematics.types import ModelType, StringType, PolyModelType, DictType, ListType from spaceone.inventory.connector.aws_elasticache_connector.schema.data import Redis, Memcached from spaceone.inventory.libs.schema.resource import CloudServiceResource, CloudServiceResponse, CloudServiceMeta from spa...
nilq/baby-python
python
import unittest import asyncio import random from hummingbot.core.api_throttler.data_types import RateLimit from hummingbot.core.api_throttler.fixed_rate_api_throttler import FixedRateThrottler FIXED_RATE_LIMIT = [ RateLimit(5, 5) ] class FixedRateThrottlerUnitTests(unittest.TestCase): @classmethod def...
nilq/baby-python
python
from __future__ import print_function import sys sys.path.insert(1,"../../") import logging from future.utils import PY2 from tests import pyunit_utils as pu class LoggingContext: def __init__(self, logger, level=None, handler=None, close=True): self.logger = logger self.level = level self...
nilq/baby-python
python
def print_trace(trace): for name, node in trace.nodes.items(): if node['type'] == 'sample': print(f'{node["name"]} - sampled value {node["value"]}')
nilq/baby-python
python
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): """Model definition for Profile.""" user = models.OneToOneField(User, on_delete=models.DO_NOTHING...
nilq/baby-python
python
# Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """This package contains utility methods for manipulating paths and filenames for test results and baselines. It also contains wrappers of a few rou...
nilq/baby-python
python
''' File name : stage.py Author : Jinwook Jung Created on : Thu 25 Jul 2019 11:57:16 PM EDT Last modified : 2020-01-06 13:27:13 Description : ''' import subprocess, os, sys, random, yaml, time from subprocess import Popen, PIPE, CalledProcessError from abc import ABC, abstract...
nilq/baby-python
python
''' Given multiple fasta files (corresponding to different organisms), use mafft to create the multiple sequence alignment for the given target. Then parse the alignments to create a consensus sequence. ''' import pandas as pd import os import alignment_funcs from Bio import SeqIO def convert_indices(x, alignment = ...
nilq/baby-python
python
# Generated by rpcgen.py at Mon Mar 8 11:09:57 2004 from .mountconstants import * from .mountpacker import * import rpc __all__ = ['BadDiscriminant', 'fhstatus', 'mountres3_ok', 'mountres3', 'mountbody', 'groupnode', 'exportnode'] def init_type_class(klass, ncl): # Initilize type class klass.ncl = ncl k...
nilq/baby-python
python
def get_layers(data, wide, tall): for i in range(0, len(data), wide * tall): yield data[i : i + wide * tall] def parse_infos(layer): infos = {} for data in layer: if data not in infos: infos[data] = 0 infos[data] += 1 return infos def merge_layers(layers): tmp...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Maziar Raissi """ import autograd.numpy as np from autograd import value_and_grad from Utilities import fetch_minibatch_rnn, stochastic_update_Adam, activation class RecurrentNeuralNetworks: def __init__(self, X, Y, hidden_dim, max...
nilq/baby-python
python
from src.computation.computation_handler import ComputationHandler class NoComputation(ComputationHandler): def __init__(self): super().__init__() def compute(self): pass
nilq/baby-python
python
from django.utils import timezone from rest_framework import serializers from ..reservation_api.models import Reservation from ..subscription_api.models import Subscription class StaffChoiseField(serializers.ChoiceField): class Meta: swagger_schema_fields = { 'type': 'integer' } cla...
nilq/baby-python
python
#!/usr/bin/env python import ray import numpy as np import time, sys, os sys.path.append("..") from util.printing import pd # A variation of the game of life code used in the Ray Crash Course. @ray.remote class RayGame: # TODO: Game memory grows unbounded; trim older states? def __init__(self, grid_size, rule...
nilq/baby-python
python
from setuptools import setup setup( name='listenmoe', packages=['listenmoe'], version='v1.0.1', description='Unofficial python3 API wrapper to get information about' 'the listen.moe live stream using aiohttp', author='Zenrac', author_email='zenrac@outlook.fr', url='https://git...
nilq/baby-python
python
# This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import sys import glob import arg...
nilq/baby-python
python
""" Implements the Graph object which is used by the ConstraintPropagator. It is here where Allen's constraint propagation algorithm is implemented. """ # TODO: I am not convinced that the history mechanism is very good, yet it seems # to be sufficient for our current purposes. from objects import Node, Edge, Con...
nilq/baby-python
python
import pytest from reformat_gherkin.errors import DeserializeError, InvalidInput from reformat_gherkin.parser import parse def test_invalid_input(invalid_contents): for content in invalid_contents: with pytest.raises(InvalidInput): parse(content) def test_valid_input(valid_contents): fo...
nilq/baby-python
python
from multio import asynclib class API: HOST = 'https://paste.myst.rs' BETA_HOST = 'https://pmb.myst.rs' API_VERSION = '2' HTTP_ENDPOINT = f'{HOST}/api/v{API_VERSION}' BETA_HTTP_ENDPOINT = f'{BETA_HOST}/api/v{API_VERSION}' async def run_later(time, task): await asynclib.sleep(time) return...
nilq/baby-python
python
#-*. coding: utf-8 -*- ## Copyright (c) 2008-2012, Noel O'Boyle; 2012, Adrià Cereto-Massagué ## All rights reserved. ## ## This file is part of Cinfony. ## The contents are covered by the terms of the GPL v2 license ## which is included in the file LICENSE_GPLv2.txt. """ pybel - A Cinfony module for accessing Open ...
nilq/baby-python
python
import argparse import os import sys import requests # Globals BASE_DIR = os.path.abspath(os.path.dirname(__file__)) APP_DIR = 'app' APP_FILES = ['__init__.py', 'config.py', 'run.py', 'create_db.py', 'shell.py'] STATIC_DIR = 'static' STATIC_SUBDIRS = ['css', 'fonts', 'img', 'js'] TEMPLATE_DIR = 'templates' TEMPLATE_...
nilq/baby-python
python
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import sys _UINT8_TO_CHAR = [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.'...
nilq/baby-python
python
def checkorders(orders: [str]) -> [bool]: results = [] for i in orders: flag = True stock = [] for j in i: if j in '([{': stock.append(j) else: if stock == []: flag = False break ...
nilq/baby-python
python
from unittest import TestCase import requests_mock import urllib.parse from .fixtures import TOKEN from typeform import Typeform from typeform.constants import API_BASE_URL class FormsTestCase(TestCase): def setUp(self): self.forms = Typeform(TOKEN).forms form = self.forms.create({ '...
nilq/baby-python
python
# libraries import pandas as pd import yaml as yaml from google.cloud import storage from os.path import dirname, abspath # utils from utils import upload_local_file_to_gcp_storage_bucket, df_to_gcp_csv # set project directory project_directory = dirname(dirname(abspath("__file__"))) print("Processing : Loading conf...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Generates a sysroot tarball for building a specific package. Meant for use after setup_board and build_packages have been ...
nilq/baby-python
python
valor_do_produto = float(input('Digite o valor do produto? R$ ')) desconto = int(input('Qual será o desconto? ')) desconto_aplicado = valor_do_produto - ((valor_do_produto * desconto)/100) print('O produto que custava R${:.2f}, na promoção de {}% custará: R$ {:.2f}'.format(valor_do_produto,desconto, desconto_ap...
nilq/baby-python
python
import collections import statistics import time class Statistics: """Calculate mathematical statistics of numerical values. :ivar ~.sum: sum of all values :ivar ~.min: minimum of all values :ivar ~.max: maximum of all values :ivar ~.mean: mean of all values :ivar ~.median: median of all valu...
nilq/baby-python
python
import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin class MetaFeaturesExtractor(BaseEstimator, TransformerMixin): def __init__(self, user_meta=None, item_meta=None): self.user_meta = user_meta self.item_meta = item_meta self.user_meta.registration_init_time = pd.to...
nilq/baby-python
python
# coding=utf-8 from django.test import TestCase from django.db import IntegrityError from applications.trackers.models import Tracker class TrackerModelTest(TestCase): def test_create_tracker(self): Tracker.objects.create(ip='192.168.0.1') tracker = Tracker.objects.all() self.assertTrue...
nilq/baby-python
python
from django.views.generic.detail import DetailView from django.views.generic.list import ListView from .models import Message, Person, Tag class MessageView(DetailView): """ Detail view of a Person object """ model = Message class MessagesView(ListView): """ A view to list all Person object...
nilq/baby-python
python
# Nick Hansel # Web scraper to create a shopping list given recipes from random_recipe import * days = { "Monday": None, "Tuesday": None, "Wednesday": None, "Thursday": None, "Friday": None, "Saturday": None, "Sunday": None } while True: answer = input("Would you like to choose a ra...
nilq/baby-python
python
import logging LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s" logging.basicConfig( filename = "logging_demo.log", level = logging.DEBUG, format = LOG_FORMAT, filemode = "w") logger = logging.getLogger() logger.debug("Debug level message") logger.info("Info level message") logger.warning("Warning level mes...
nilq/baby-python
python
this is not valid python source code, but still more beautiful than many non-pythonic languages.
nilq/baby-python
python
import discord from discord.ext import commands import os import json client = commands.Bot(command_prefix = ".") # @client.command() # async def load(ctx , extensions): # client.load_extensions(f"cogs.{extensions}") # @client.command() # async def unload(ctx , extensions): # client.unload_extension(f"cogs...
nilq/baby-python
python
fibonacci = [0, 1] n = int(input()) if n == 1: print(str(fibonacci[0])) if n < 46 and n > 1: if n > 2: for x in range(n - 2): fibonacci.append(fibonacci[x] + fibonacci[x + 1]) myTable = str(fibonacci).maketrans("", "", "[,]") print(str(fibonacci).translate(myTable))
nilq/baby-python
python
""" Test CCompiler. """ from pathlib import Path from types import SimpleNamespace from unittest import mock from fab.build_config import AddFlags from fab.dep_tree import AnalysedFile from fab.steps.compile_c import CompileC class Test_Compiler(object): def test_vanilla(self): # ensure the command is...
nilq/baby-python
python
import markov from typing import Optional from fastapi import FastAPI app = FastAPI() @app.get("/") def read_item(length: Optional[str] = None, start: Optional[str] = None): if length is not None: length = int(length) text = markov.generate(length=length, start=start) return text
nilq/baby-python
python
from lxml import etree from io import StringIO from django.urls import path from django.http import HttpResponse from django.template import Template, Context, Engine, engines def a(request): xslt_root = etree.XML('''\ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transf...
nilq/baby-python
python
from VisualisationPlugin import VisualisationPlugin import pygame import math import logging from DDRPi import FloorCanvas class SineWaveVisualisationPlugin(VisualisationPlugin): logger = logging.getLogger(__name__) def __init__(self): self.clock = pygame.time.Clock() def configure(self, conf...
nilq/baby-python
python
import socket sock = socket.socket() address = "agps.u-blox.com" port = 46434 print "Connecting to u-blox" sock.connect((address, port)) print "Connection established" print "Sending the request" sock.send("cmd=full;user=korovkin@gmail.com;token=4HWt1EvhQUKJ2InFyaaZDw;lat=30.0;lon=30.0;pacc=10000;") print "Sending th...
nilq/baby-python
python
import os.path as osp from pathlib import Path import pandas as pd from jitenshea.stats import find_cluster _here = Path(osp.dirname(osp.abspath(__file__))) DATADIR = _here / 'data' CENTROIDS_CSV = DATADIR / 'centroids.csv' def test_find_cluster(): df = pd.read_csv(CENTROIDS_CSV) df = df.set_index('cluste...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Wed Jan 23 22:40:34 2018 @author: boele """ # 03 read csv and find unique survey vessels... # open csv file f = open('fartoey_maaleoppdrag.csv', 'r') data = f.read() surveys_and_vessels = data.split('\n') # print number of rows and show first 5 rows print(len(su...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Wed Oct 11 13:59:21 2017 @author: tuur """ from __future__ import print_function from dateutil import parser as dparser from lib.evaluation import get_selective_rel_metrics, get_acc_from_confusion_matrix,save_confusion_matrix_from_metrics, viz_docs_rel_difference, save_entity_err...
nilq/baby-python
python
import pygame from cell_class import * import copy vec = pygame.math.Vector2 CELL_SIZE = 20 class GameWindow: def __init__(self, screen, x, y): self.screen = screen self.position = vec(x, y) self.width, self.height = 600, 600 self.image = pygame.Surface((self.width, self.height)) ...
nilq/baby-python
python
''' Created on Jul 28, 2013 @author: akittredge ''' import pandas as pd import pymongo class MongoDataStore(object): def __init__(self, collection): self._collection = collection def __repr__(self): return '{}(collection={})'.format(self.__class__.__name__, ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2018 Whitestack, LLC # ************************************************************* # This file is part of OSM Monitoring module # All Rights Reserved to Whitestack, LLC # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
nilq/baby-python
python
import json from .miioservice import MiIOService def twins_split(string, sep, default=None): pos = string.find(sep) return (string, default) if pos == -1 else (string[0:pos], string[pos+1:]) def string_to_value(string): if string == 'null' or string == 'none': return None elif string == 'fa...
nilq/baby-python
python
import socket import logging logger = logging.getLogger(__name__) class P2PSocket: def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) def bind(self, host, port): logger.debug("Binding P2P socket to (%s, %i)", host, port) self.s.bind((host, port)) self.s.setb...
nilq/baby-python
python
from django.shortcuts import render, get_object_or_404 from blog_posts.models import Post from blog_posts.forms import PostForm def index(request): posts = Post.objects.all() return render(request, 'administracao/index-admin.html', context ={"index": "Index", ...
nilq/baby-python
python
"""Algorithm for simulating a 2048 game using Monte-Carlo method.""" import random, _2048 SIMULATE_TIMES = 100000 DIRECTIONS = ('UP', 'DOWN', 'LEFT', 'RIGHT') def simulate_to_end(game): while game.get_state(): dircts = list(DIRECTIONS) for i in xrange(3): c = random.choice(dircts) ...
nilq/baby-python
python
# Define a procedure is_palindrome, that takes as input a string, and returns a # Boolean indicating if the input string is a palindrome. # Base Case: '' => True # Recursive Case: if first and last characters don't match => False # if they do match, is the middle a palindrome? def is_palindrome(s): #print is...
nilq/baby-python
python
# Copyright (c) OpenMMLab. All rights reserved. import copy import warnings import mmcv import numpy as np import torch from mmdet.core.visualization.image import imshow_det_bboxes from ..builder import DETECTORS, build_backbone, build_head, build_neck from .base import BaseDetector INF = 1e8 @DETEC...
nilq/baby-python
python
#LordLynx #Part of PygameLord import pygame,os from pygame.locals import* pygame.init() #Loading Objects ''' Parse_Locations(file) file: Your text file, use a .txt # Like in Python will be ingored thusly follow this example #Coment ./File/File ./File/Other File ... ''' def Parse_Locations(file): file = open(file,...
nilq/baby-python
python
from results_saver import LogWriter from .ModelType import ModelType from .lda_lsa_model_tester import LModelTester from .naive_bayes_model_tester import NBModelTester from .lsa_tester import LSAModelTester from .svm_model_tester import SVMModelTester from ..methods.Lda import Lda from ..methods.Lsa import Lsa from ..m...
nilq/baby-python
python
#!/usr/bin/env python3 import pathlib import sys sys.path += ['/opt/py', str(pathlib.Path.home() / 'py')] import basedir import shlex import subprocess def info_beamer_invocation(): custom_cmd = pathlib.Path.home() / '.config' / 'fenhl' / 'info-beamer' if custom_cmd.exists(): return [str(custom_cmd)...
nilq/baby-python
python
import random from app.core.utils import get_random_date def build_demo_data(): """ Helper method, just to demo the app :return: a list of demo docs sorted by ranking """ samples = ["Messier 81", "StarBurst", "Black Eye", "Cosmos Redshift", "Sombrero", "Hoags Object", "Andromeda", "Pi...
nilq/baby-python
python
#!/usr/bin/env python3 """ Project Icarus creator: derilion date: 01.07.2019 version: 0.1a """ """ TODO: - Installer - Database Structure - Special Characters in *.ini - Setup of skills - Configuration of Clients - multi language support """ # imports from icarus.icarus import Icarus # thread safe init if __name_...
nilq/baby-python
python
import requests import json remote_url = "" device_id = "" bearer = "" api_key = "" app_id = "" def url(endpoint): return "{0}{1}".format(remote_url, endpoint) def headers_with_headers(headers): new_headers = {} new_headers["Content-Type"] = "application/json" new_headers["X-BLGREQ-UDID"] = devic...
nilq/baby-python
python
from .iotDualMotor import IotDualMotor class IotEncodedMotor(IotDualMotor): """ the base class for motor with encoder The speed range from -100 to 100 with zero (less than minMovingSpeed) to stop the motor. """ def __init__(self, name, parent, minMovingSpeed=5): """ construct a PiIotNode ...
nilq/baby-python
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
nilq/baby-python
python
import sys import argparse from absynthe.graph_builder import TreeBuilder def treeGeneration(numRoots: int = 2, numLeaves: int = 4, branching: int = 2, numInnerNodes: int = 16): loggerNodeTypes: str = "SimpleLoggerNode" tree_kwargs = {TreeBuilder.KW_NUM_ROOTS: str(numRoots), ...
nilq/baby-python
python
import sys import time dy_import_module_symbols("shimstackinterface") SERVER_IP = getmyip() SERVER_PORT = 34829 UPLOAD_RATE = 1024 * 1024 * 15 # 15MB/s DOWNLOAD_RATE = 1024 * 1024 * 128 # 15MB/s DATA_TO_SEND = "HelloWorld" * 1024 * 1024 RECV_SIZE = 2**14 # 16384 bytes. MSG_RECEIVED = '' END_TAG = "@@END" def launc...
nilq/baby-python
python
#%% from pssr import pssr from speech_recognition import UnknownValueError, RequestError, Recognizer print('oi') r = Recognizer() #recognizes audio, outputs transcript ps = pssr.PSRecognizer() #PSRecognizer instance to listen and generate the audio psmic = pssr.PSMic(nChannels=3) #ps eye mic array with psmic as sour...
nilq/baby-python
python