content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import os from awacs.aws import Policy, Allow, Statement, Principal, Action from cfn_encrypt import Encrypt, EncryptionContext, SecureParameter, GetSsmValue from troposphere import (Template, iam, GetAtt, Join, Ref, logs, Output, Sub, Parameter, awslambda, Base64, Export) from sys import argv...
nilq/baby-python
python
# Copyright 2016 - Nokia # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, sof...
nilq/baby-python
python
import os import pandas as pd import glob import random import shutil INDEX = { 'Shift_png':0, 'Random_png':1, 'Original_png':2, 'Expand_png':3, 'Contract_png':4 } def make_label_csv(input_path,csv_path,mid_dir=None): info = [] for subdir in os.scandir(input_path): index = INDEX...
nilq/baby-python
python
# coding=utf-8 import numpy as np from time import time from aux import * ''' Obre un fitxer a partir del seu nom i guarda cada una de les seves línies en cada posició d'una llista Paràmetres: - fileName: Nom del fitxer que es vol obrir. Return: - llista amb les paraules que conformen la llista Swadesh d'un id...
nilq/baby-python
python
def swap_case(s): swapped_s = '' for letter in s: swapped_s += letter.lower() if letter.isupper() else letter.upper() return swapped_s if __name__ == '__main__': s = input() result = swap_case(s) print(result)
nilq/baby-python
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
nilq/baby-python
python
from os.path import join import matplotlib.pylab as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages from sklearn.metrics import roc_curve, auc import src.utils from src.methods.methods import good_methods as methods from src.methods.methods import mutliple_time_series_combiner from src.rea...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Defines functionality for pipelined execution of interfaces The `EngineBase` class implements the more general view of a task. .. testsetup:: # Chan...
nilq/baby-python
python
from netCDF4 import Dataset #------------------------------------------------------------------------------- def set_difference_fields(): files = {"./output_hex_wachspress_0082x0094_120/output.2000.nc": ["./output_hex_pwl_0082x0094_120/output.2000.nc", "./output_hex_weak_0082x0094_120/...
nilq/baby-python
python
import imp import librosa import numpy as np from keras.models import load_model genres = {0: "metal", 1: "disco", 2: "classical", 3: "hiphop", 4: "jazz", 5: "country", 6: "pop", 7: "blues", 8: "reggae", 9: "rock"} song_samples = 660000 def load_song(filepath): y, sr = librosa.load(filepath...
nilq/baby-python
python
""" Tests for the StarCluster Job """ import sure from mock import Mock from .fixtures import * from metapipe.models import sge_job def test_qstat_queued(): j = sge_job.SGEJob('', None) sge_job.call = Mock(return_value=sge_job_qstat_queued) j.is_queued().should.equal(True) def test_qstat_running(): ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def initial_log_action(apps, schema_editor): LogAction = apps.get_model('logs', 'LogAction') action, created = LogAction.objects.get_or_create( name='USER_CREATE', ) action.template = 'Use...
nilq/baby-python
python
__author__ = 'Neil Butcher' from Institution import InstitutionSavingObject
nilq/baby-python
python
import sys import os.path def main(): sys.argv[:] = sys.argv[1:] # Must rewrite the command line arguments progname = sys.argv[0] sys.path.insert(0, os.path.dirname(progname)) with open(progname, 'rb') as fp: code = compile(fp.read(), progname, 'exec') globs = { '__file__' : progna...
nilq/baby-python
python
from __future__ import unicode_literals import os import shutil import subprocess import sys import optparse import datetime import time sys.path[:0] = ['.'] from yt_dlp.utils import check_executable try: iterations = str(int(os.environ['ZOPFLI_ITERATIONS'])) except BaseException: iterations = '30' parser ...
nilq/baby-python
python
import json from django.http.response import HttpResponseRedirect, HttpResponse from django.shortcuts import render_to_response from django.urls.base import reverse from lykops.views import Base class Report(Base): def summary(self,request): result = self._is_login(request) if result[0] : ...
nilq/baby-python
python
## # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
nilq/baby-python
python
""" Loader for Maya api sub-package """ from __future__ import absolute_import from __future__ import print_function from __future__ import division # this can be imported without having maya fully initialized from .allapi import *
nilq/baby-python
python
#!/usr/bin/python # # Copyright (c) 2012 Mikkel Schubert <MSchubert@snm.ku.dk> # # 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 #...
nilq/baby-python
python
import sys import srvdb db = srvdb.SrvDb("./pdb-aggregator.db") file = sys.argv[1] print(file) with open(file) as f: content = f.read().splitlines() print(content) ips = [] for ip in content: if ip not in ips: print("Adding node {}".format(ip)) db.add_node(ip, False, 0, "") ips.ap...
nilq/baby-python
python
# Copyright (c) 2020 PaddlePaddle Authors. 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 required by appli...
nilq/baby-python
python
from output.models.nist_data.list_pkg.qname.schema_instance.nistschema_sv_iv_list_qname_pattern_2_xsd.nistschema_sv_iv_list_qname_pattern_2 import NistschemaSvIvListQnamePattern2 __all__ = [ "NistschemaSvIvListQnamePattern2", ]
nilq/baby-python
python
#!/usr/bin/env python3 from datetime import datetime, timedelta from math import floor import sys from time import perf_counter from betterprint.betterprint import bp, bp_dict from modules.notations import byte_notation from modules.createfolder import folder_logic, folder_stat_reset from betterprint.colortext import...
nilq/baby-python
python
# https://www.hackerrank.com/challenges/s10-geometric-distribution-2/problem # Enter your code here. Read input from STDIN. Print output to STDOUT x,y = map(int, input().split()) p = x/y n = int(input()) answer = 0 for z in range(1,n+1): temp = (1-p)**(z-1) * p answer = answer + temp print(round(answer,3))
nilq/baby-python
python
# Generated by Django 3.0 on 2021-07-21 11:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wwwrate', '0007_auto_20210720_1450'), ] operations = [ migrations.AlterModelOptions( name='project', options={'orderin...
nilq/baby-python
python
import subprocess from vendor.addressfetcher.addressfetcher import fetcher # constant ADDRESS_PATH = '' def input_number(prompt): while True: try: num = float(input(prompt)) break except ValueError: pass return num def display_menu(option...
nilq/baby-python
python
import os import shutil import tarfile import urllib import zipfile from .constants import RU_VOWELS, DEFAULT_DATA_DIR from pathlib import Path from typing import Union def count_syllables(word: str) -> int: """ Вычисление количества слогов в слове Аргументы: word (str): Строка слова Вывод: ...
nilq/baby-python
python
# -*- coding: utf-8 -*- ''' Copyright © 2014 by Virginia Polytechnic Institute and State University All rights reserved Virginia Polytechnic Institute and State University (Virginia Tech) owns the copyright for the BEMOSS software and its associated documentation (“Software”) and retains rights to grant research right...
nilq/baby-python
python
import webbrowser import cv2 import numpy as np import pyautogui import PIL import time def init(): # TODO: Add more example websites with recaptcha webbrowser.open( '''https://jsso.indiatimes.com/sso/identity/register?channel=businessinsider&identifier=r@g.c''' ) # Move to a temporary location and wait for w...
nilq/baby-python
python
""" A class/method/function should have only 1 reason to change!!! It should have single responsibility eg. book movie for a theatre """ class BookMovie(object): """ Bad code """ def book_movie_seat(self, movie, seat): if self.is_seat_available(seat): return False self.book_...
nilq/baby-python
python
import unittest from Credentials import Credentials class TestCredentials(unittest.TestCase): """ Test class that defines test cases for the Credentials class behaviours """ def setUp(self): """ Set up method to run befor each test case """ self.new_credentials = Creden...
nilq/baby-python
python
"""Module for handling buses.""" from sinfactory.component import Component from sinfactory.load import Load from sinfactory.generator import Generator class Bus(Component): """Node class""" def __init__(self, pf_object): """Constructor for the Bus class. Args: pf_object: The po...
nilq/baby-python
python
#!/usr/bin/python # coding:utf-8 # ServerSan - ss-agent.py # 2018/3/14 15:03 # __author__ = 'Benny <benny@bennythink.com>' __version__ = '1.0.0' import os import platform import socket import sys import time import cpuinfo import psutil import requests # API = 'http://127.0.0.1:5000/' API = 'https://api.serversan...
nilq/baby-python
python
import pyautogui import time # time to change tabs from editor to paint; time.sleep(10) # it will remain clicked till program ends; pyautogui.click() # can be varied according to convininence distance = 250 while distance > 0: # right pyautogui.dragRel(distance, 0, duration = 0.1) distance -= 5 ...
nilq/baby-python
python
from flask import ( Flask, render_template, send_from_directory, redirect, url_for, request) from . import settings as st from .persistency import PersistencyManager import markdown from pygments.formatters import HtmlFormatter from flask_wtf import FlaskForm from flask_pagedown.fields import PageDownField from wtf...
nilq/baby-python
python
from pwn import * # NOQA flag = b"flag{AAAAAAAAAAA}" flag = bytes(bin(int(binascii.hexlify(flag), 16)), 'utf8') class GuessIterator: def __init__(self): self.known_part = b"" self.first_block = True self.i = -1 def know_guess(self): self.known_part = self.current_guess() ...
nilq/baby-python
python
from setuptools import setup from os import path from io import open here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='SimpleHTTPSAuthServer', version='1.1.0', description='HTTPS server with Basic authe...
nilq/baby-python
python
""" A simple example which prints out parsed streaming responses. Python version: 3.6+ Dependencies (use `pip install X` to install a dependency): - websockets Usage: python deepgram_streaming.py -k 'YOUR_DEEPGRAM_API_KEY' /path/to/audio.wav Limitations: - Only parses signed, 16-bit li...
nilq/baby-python
python
# This file is part of pure-dispatch. # https://github.com/SeedyROM/pure-dispatch # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT-license # Copyright (c) 2017, Zack Kollar <zackkollar@gmail.com> '''Test our database module. ''' from tests.base import TestCase from pure_dispatch.database imp...
nilq/baby-python
python
# By Justin Walgran # Copyright (c) 2012 Azavea, Inc. # # 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, ...
nilq/baby-python
python
# Copyright (c) 2017 Midokura SARL # 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 require...
nilq/baby-python
python
from django.shortcuts import render_to_response, render from django.template.response import TemplateResponse from django.template import RequestContext from django.contrib.sites.models import Site from django.urls import reverse from django.views.decorators.clickjacking import xframe_options_exempt from django.views.d...
nilq/baby-python
python
from rdflib.graph import Graph from rdflib.namespace import Namespace, RDFS, RDF from owmeta_core.rdf_query_modifiers import (ZeroOrMoreTQLayer, rdfs_subclassof_subclassof_zom_creator as mod, rdfs_subclassof_zom, ...
nilq/baby-python
python
#!/usr/bin/env python '''This script will compile 1D spectra into cubes, and visualize them.''' # create (and save!) a cube, and visualize it from mosasaurus.Cube import Cube import sys try: c = Cube(sys.argv[1]) c.populate(remake=False, visualize=False) c.movieCube(stride=1) except IndexError: print...
nilq/baby-python
python
# requires: # - phantomjs or geckodriver installed # - selenium from pip import sys import unittest import json import argparse from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditi...
nilq/baby-python
python
#102 # Time: O(n) # Space: O(n) # Given a binary tree, return the level order traversal # of its nodes' values. (ie, from left to right, level by level). # # For example: # Given binary tree [3,9,20,null,null,15,7], # 3 # / \ # 9 20 # / \ # 15 7 # return its level order traversal as: # [ # [3], #...
nilq/baby-python
python
"""Some useful data structures and functions""" import datetime espa_env = { "dev": "https://espa-dev.cr.usgs.gov", "tst": "https://espa-tst.cr.usgs.gov", "ops": "https://espa.cr.usgs.gov" } api_urls = { "status": "/api/v1/item-status/", "order": "/api/v1/order/" } def timestamp() -> str: "...
nilq/baby-python
python
import os import glob import shutil # dictionary mapping each extension with its corresponding folder # For example, 'jpg', 'png', 'ico', 'gif', 'svg' files will be moved to 'images' folder # feel free to change based on your needs extensions = { "jpg": "images", "png": "images", "ico": "images", "gif"...
nilq/baby-python
python
#! /usr/bin/env python3 from sklearn import svm import numpy as np import json import random import sys import os import argparse def estimate(data, target, trainingsubset, testingsubset, gamma='auto', C=1): if(len(set(target)) < 2): # only one class return 0; clf = svm.SVC(gamma=gamma, C=C) clf.fit(data[trainin...
nilq/baby-python
python
# Initializes the datastore with sample data. # # Possibilities to execute the code in this file: # # * GAE SDK 1.5 or compatible: Paste the code in the interactive console and # execute it. # # * GAE (production): # # a) Enter the directory of the Reality Builder. # # b) Connect to the remote API sh...
nilq/baby-python
python
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ lvmmodel.io ============ I/O utility functions for files in lvmmodel. """ import os from astropy.io import fits import yaml import numpy as np import warnings from lvmutil.log import get_logger log = get_logger() _thru = dic...
nilq/baby-python
python
import glob import bz2 with open('all_data.ndjson','w') as out: for div in glob.glob('./OpenAccess-master/metadata/objects/*'): print('Working on: ',div) for file in glob.glob(f'{div}/*'): with bz2.open(file, "rb") as f: out.write(f.read().decode())
nilq/baby-python
python
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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 a...
nilq/baby-python
python
from django.urls import path,include from . import views urlpatterns = [ path('api/projects/', views.ProjectList.as_view()), path('api/projects/profile', views.ProfileList.as_view()), path('api/projects/ratings', views.RatingList.as_view()), ]
nilq/baby-python
python
from output.models.ms_data.attribute.att_j004_xsd.att_j004 import Test __all__ = [ "Test", ]
nilq/baby-python
python
import param from . import API1TestCase # TODO: I copied the tests from testobjectselector, although I # struggled to understand some of them. Both files should be reviewed # and cleaned up together. # TODO: tests copied from testobjectselector could use assertRaises # context manager (and could be updated in testobje...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals from django.conf.urls import url from .views import create_view from .views import update_view from .views import delete_view from .views import list_view stagesetting_create = url(regex=r'^add/$', ...
nilq/baby-python
python
# # Copyright (c) 2013-2020 Contributors to the Eclipse Foundation # # See the NOTICE file distributed with this work for additional information regarding copyright # ownership. All rights reserved. This program and the accompanying materials are made available # under the terms of the Apache License, Version 2.0 whic...
nilq/baby-python
python
from insights.parsers.route import Route from insights.tests import context_wrap ROUTE = ''' Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 10.66.208.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 169.254.0.0 0.0.0.0 255.255.0.0 ...
nilq/baby-python
python
#!/usr/bin/env python3.7 # Copyright: Ismael Narváez Berenjeno from datetime import datetime def get_time_isoformat(): """ Get timestamp with ISO format. :return: ISO timestamp :rtype: str """ return datetime.now().isoformat()
nilq/baby-python
python
""" 面试题21:包含min函数的栈 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。 https://leetcode.com/problems/min-stack/ Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack...
nilq/baby-python
python
#!/usr/bin/python3 from PyQt5 import QtCore, QtGui from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QFrame, QPushButton, QLabel class LaunchScreen(QFrame): def __init__(self, parent): # constructor super().__init__(parent) self.windowClass = parent # allows calling of parent class methods ...
nilq/baby-python
python
"""Conditional Grammar.""" from sqlfluff.core.parser.segments import Indent from sqlfluff.core.parser.match_result import MatchResult from sqlfluff.core.parser.match_wrapper import match_wrapper from sqlfluff.core.parser.grammar.base import ( BaseGrammar, ) class Conditional(BaseGrammar): """A g...
nilq/baby-python
python
from textformer.models import Seq2Seq # Creating the Seq2Seq model seq2seq = Seq2Seq(n_input=1, n_output=1, n_hidden=512, n_embedding=256, n_layers=2, ignore_token=None, init_weights=None, device='cpu')
nilq/baby-python
python
from django.conf.urls import include, url import django.contrib.auth.views from work_evid import views urlpatterns = [ url(r'^overviews/$', views.overviews, name='overviews'), url(r'^delete_work/$', views.delete_work, name='delete_work'), url(r'^work/$', views.WorkList.as_view(), name='work_list'), ur...
nilq/baby-python
python
#!/usr/bin/env python3 import tensorflow as tf import pickle import cv2 import os import os.path as path from utils import predict, predict_no_tiles from model import dilation_model_pretrained from datasets import CONFIG if __name__ == '__main__': test = True # Choose between 'cityscapes' and 'camvid' dat...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Unit test package for tatortot."""
nilq/baby-python
python
import requests import re from bs4 import BeautifulSoup import logging import os import json base_url = "https://vulncat.fortify.com/en/weakness?q=" logpath=f'{os.getcwd()}/log' def scrape_url(url): soup:BeautifulSoup=None try: r=requests.get(url) soup=BeautifulSoup(r.text, 'html.parser') ...
nilq/baby-python
python
from fastai.vision.all import * import fastai from fastai.tabular.all import * from fastai.data.load import _FakeLoader, _loaders import matplotlib.pyplot as plt import pandas as pd import numpy as np import os import random # CUSTOM VIS DATABLOCK FUNCTIONS def get_npy(dataframe): "Get the images (.npy) that will...
nilq/baby-python
python
from __future__ import absolute_import import re from cStringIO import StringIO from datetime import date, datetime, timedelta from psycopg2.extensions import AsIs, Binary, QuotedString from pytz import timezone class PostgresWriter(object): """Base class for :py:class:`mysql2pgsql.lib.postgres_file_writer.Post...
nilq/baby-python
python
from app import server as user if __name__ == "__main__": user.run()
nilq/baby-python
python
""" Faça um programa que possua um vetor denominado 'A' que armazene 6 números inteiros. O programa deve executar os seguintes passos. (a) Atribua os seguintes valores a esse vetor: 1, 0, 5, -2, -5, 7. (b) Armezene em uma variável inteira (simples) a soma entre os valores das posições A[0], A[1], e A[5] do vetor e mos...
nilq/baby-python
python
""" Django settings for coralcity project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os ...
nilq/baby-python
python
# https://jsonapi.org/format/#document-resource-identifier-objects def build_resource_identifier(type, id): return {"type": type, "id": id} #https://jsonapi.org/format/#document-meta def build_meta(meta): return meta # https://jsonapi.org/format/#document-links def build_links_object(links): links_objec...
nilq/baby-python
python
import os from rpython.rtyper.lltypesystem import lltype, llmemory, rffi from rpython.rlib.rposix import is_valid_fd from rpython.rlib.rarithmetic import widen, ovfcheck_float_to_longlong from rpython.rlib.objectmodel import keepalive_until_here from rpython.rtyper.annlowlevel import llhelper from pypy.interpreter.err...
nilq/baby-python
python
from .CreateSource import CreateSource from .DropSource import DropSource from .InputKeys import InputKeys from .OutputKeys import OutputKeys from .ProducedKeys import ( ProducedKeys, ProducedLinkKeys, ProducedHubKeys ) from .SatelliteQuery import SatelliteQuery from .SerialiseSatellite import SerialiseSate...
nilq/baby-python
python
"""Array with time epochs """ # Standard library imports from collections import namedtuple from datetime import datetime, timedelta from typing import Callable, Dict, List, Optional, Tuple, Any, TypeVar from functools import lru_cache try: import importlib.resources as importlib_resources # Python >= 3.7 except ...
nilq/baby-python
python
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) p = list(map(int, input().split())) from collections import deque _min = 0 used = set() num = deque(range(1, 200000 + 2)) for v in p: used.add(v) if _min not in used: print(_min) else: while num: ...
nilq/baby-python
python
class Solution: def plusOne(self, digits): length = len(digits) for i in range(length - 1, -1, -1): if digits[i] < 9: digits[i] += 1 return digits digits[i] = 0 return [1] + [0] * length
nilq/baby-python
python
# coding: utf-8 # **Appendix D – Autodiff** # _This notebook contains toy implementations of various autodiff techniques, to explain how they works._ # # Setup # First, let's make sure this notebook works well in both python 2 and 3: # In[1]: # To support both python 2 and python 3 from __future__ import absolu...
nilq/baby-python
python
from django.db import models # from django.contrib.auth.models import User from django.contrib.auth import get_user_model as user_model User = user_model() from apps.lobby.main.models import Lobby class Room(models.Model): title = models.CharField(max_length=30, primary_key=True) description = models.CharField...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2016 Aarón Abraham Velasco Alvarez 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 rig...
nilq/baby-python
python
""" Npy module This module implements all npy file management class and methods ... Classes ------- Npy Class that manages npy file's reading and writing functionalities """ import numpy as np import os class Npy(object): """ Class that manages npy file's reading and writing functionalities Methods ...
nilq/baby-python
python
from machine import I2C import LIS2MDL i2c = I2C(1) mdl = LIS2MDL.LIS2MDL(i2c) mdl.x() mdl.get()
nilq/baby-python
python
#!/usr/bin/env python3 #================== # gmail_pycamera #================== import os import json import datetime import shutil from devices import CameraMount from h264tomp4 import h264tomp4 from gmail import Gmail from command import parse_command class GmailPiCamera: """ gmail_picamera """ de...
nilq/baby-python
python
# Generated by Django 3.2.8 on 2021-11-02 22:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('annotations', '0004_auto_20211102_1819'), ] operations = [ migrations.RemoveField( model_name='imagegroup', name='gr...
nilq/baby-python
python
import unittest import solver from solver import sort_colors class TestSolver(unittest.TestCase): def test_sort_colors(self): self.assertEqual(sort_colors([0, 0, 0, 0, 0, 0]), [0, 0, 0, 0, 0, 0]) self.assertEqual(sort_colors([2, 2, 2, 2, 2, 2]), [2, 2, 2, 2, 2, 2]) self.assertEqual(sort_colors([0, 0, 2, ...
nilq/baby-python
python
from django import template from raids.utils import get_instances register = template.Library() def get_loot_history(character): # Only filters items for main specialization -> where entitlement is set for the characters specialization # Dict for easy checking if instance is already a key instances = {in...
nilq/baby-python
python
# Copyright (c) Open-MMLab. All rights reserved. from .checkpoint import (_load_checkpoint, load_checkpoint, load_state_dict, save_checkpoint, weights_to_cpu) from .dist_utils import get_dist_info, init_dist, master_only from .hooks import (CheckpointHook, ClosureHook, DistSamplerSeedHook, Hook...
nilq/baby-python
python
# Standard imports from types import SimpleNamespace import numpy as np from scipy import optimize from scipy import stats from scipy import random from scipy.stats import beta import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') #Constructing grid of x and q in specific ranges q_values = np.linspace(0...
nilq/baby-python
python
from core.config.setting import static_setting from core.resource.pool import ResourceSetting static_setting.setting_path = "/Users/lilen/mySetting" ResourceSetting.load() print(f"资源文件路径{ResourceSetting.resource_path}") print(f"配置文件路径{ResourceSetting.setting_path}") ResourceSetting.resource_path = "/User/user/new_res...
nilq/baby-python
python
import pygame from settings import * class Entity: def __init__(self, x, y, w, h, speed, begin_act): self.x = x self.y = y self.w = w self.h = h self.rect = pygame.Rect(x, y, w, h) self.life = 100 self.life_rect = pygame.Rect(x, y, w, 4) self.action ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' mail.py: email server utils ''' import sys import argparse import getpass from os import getenv try: import mysql.connector as mariadb except ImportError: print('找不到 mysql 客户端,请安装: pip install mysql-connector-python') sys.exit(2) _version = '2.1' parse...
nilq/baby-python
python
import os import json from .android_component_builder import AndroidComponentBuilder class LabelBuilder(AndroidComponentBuilder): def __init__(self, options, component): super().__init__(options, component) self.constraints = {} self.name = '' self.text = '' self.text_align...
nilq/baby-python
python
import http import secrets import pytest from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone from django.utils.http import urlencode from guildmaster import views from guildmaster.utils import reverse @pytest.fixture() def user(): user, __ = User.objects...
nilq/baby-python
python
# coding: utf-8 """ Json-serializers for books-rest-api. """ from rest_framework.serializers import ( ModelSerializer, ReadOnlyField ) from books.models import * __author__ = "Vladimir Gerasimenko" __copyright__ = "Copyright (C) 2017, Vladimir Gerasimenko" __version__ = "0.0.1" __maintainer__ = "Vladimir...
nilq/baby-python
python
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from faker import Faker from members.models.members import Member from members.models.services import Service from members.models.countries import City from django.template.defaultfilters import slugify import random from dj...
nilq/baby-python
python
q1 = [] q2 = [] n = 5 def push(data): if not q1==[] and len(q1) == n: print("Overflow") return if not q2==[] and len(q2) == n: print("Overflow") return if(q2 == []): q1.append(data) else: q2.append(data) def pop(): if(q1 == [] and q2 == []): ...
nilq/baby-python
python
import requests, time import sys,time,socket from Sensor import Sensor if __name__ == "__main__": sensor = Sensor("/dev/ttyUSB0",9600) while True: data = sensor.PM25_Hex(10).split(" ") pm = int(data[3]+data[2], 16)/10 print str(time.strftime("%H:%M:%S", time.localtime())) + ' PM2.5: ', ...
nilq/baby-python
python
from test_helper import run_common_tests, failed, passed, check_tests_pass from maximum_salary import largest_number def reference(numbers): numbers = list(map(str, numbers)) for _ in numbers: for i in range(len(numbers) - 1): if numbers[i] + numbers[i + 1] < numbers[i + 1] + numbers[i]: ...
nilq/baby-python
python