content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from cli_args_system.args import Args from cli_args_system.flags_content import FlagsContent
nilq/baby-python
python
# Copyright 2016 Quora, Inc. # # 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, so...
nilq/baby-python
python
import unittest from unittest import TestCase from unittest.mock import patch, Mock import mysql.connector from matflow.database.DatabaseTable import DatabaseTable from matflow.exceptionpackage import MatFlowException # TODO too complicated for first use of unittests. Come back to this after writing tests for other ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from .quicktime_hold import QuickTimeHold from .quicktime_mash import QuickTimeMash
nilq/baby-python
python
# -*- coding: utf-8 -*- import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from .fields import features_modal from .fields import fields from .info_modal import info_modal from app.custom_widgets import custom_button store = [ # JSON string of Parameter...
nilq/baby-python
python
# -*- coding: utf-8 -*- from model.contact import Contact import random def test_delete_random(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(firstname="Nikto")) oldcontacts = db.get_contact_list() contact = random.choice(oldcontacts) app.contact.delete_by_...
nilq/baby-python
python
from playwright.sync_api import sync_playwright import socket #Stage 2 from ipwhois.net import Net from ipwhois.asn import IPASN from pprint import pprint import ssl, socket class Solution: def __init__(self, url): #1.a self.user_given_url = url self.is_https = None sel...
nilq/baby-python
python
# Copyright 2019 Contributors to Hyperledger Sawtooth # # 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 ...
nilq/baby-python
python
class QuestionStructure(object): '''The QuestionStructure Will be imported from the Questions package and used to model the question Structure ''' def __init__(self, q_text, answer, options): self.q_text = q_text self.answer = answer self.options = options def check_answer(...
nilq/baby-python
python
#!/usr/bin/env python ''' octoDNS Versions ''' from __future__ import absolute_import, division, print_function, \ unicode_literals from octodns.cmds.args import ArgumentParser from octodns.manager import Manager def main(): parser = ArgumentParser(description=__doc__.split('\n')[1]) parser.add_argumen...
nilq/baby-python
python
import boto3 import os import json from datetime import datetime import logging import json ''' AWS Lambda Function to get all data. Requests come from Amazon API Gateway. ''' logger = logging.getLogger() logger.setLevel(logging.INFO) def get_data(id): dynamodb = boto3.resource('dynamodb') table = dynamodb....
nilq/baby-python
python
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # 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 Apach...
nilq/baby-python
python
from django.shortcuts import render from rbac.models import Menu from system.models import SystemSetup def customerView(request): if request.method == 'GET': ret = Menu.getMenuByRequestUrl(url=request.path_info) ret.update(SystemSetup.getSystemSetupLastData()) return render(request, 'adm/...
nilq/baby-python
python
# import unittest # import os # from testfixtures import tempdir, compare, TempDirectory # from tests.context import categorize # Pair = categorize.ArchivePair # import json # class test_archive_pair(unittest.TestCase): # """ # Ensure that when something needs to be stored it can be gotten and set # """ ...
nilq/baby-python
python
# coding: utf-8 from datetime import datetime, timedelta from .._base import to_base64 from .base import TestCase from .base import create_server, sqlalchemy_provider, cache_provider from .base import db, Client, User, Grant class TestDefaultProvider(TestCase): def create_server(self): create_server(self...
nilq/baby-python
python
from sqlalchemy import ( Boolean, Column, ForeignKey, Integer, Text, Unicode, UniqueConstraint, ) from sqlalchemy.orm import relationship from nbexchange.models import Base from nbexchange.models.actions import Action class Assignment(Base): """The Assigments known for each course ...
nilq/baby-python
python
# Copyright (c) 2022 Keith Carrara <legocommanderwill@gmail.com> & Edward Kopp <edward@edwardkopp.com> # Licensed under the MIT License. the LICENSE file in repository root for information. from abc import abstractmethod from kivy import Config from kivy.app import App from kivy.core.window import Window from...
nilq/baby-python
python
import os import random import math import json import numpy as np import pandas as pd from scipy import stats from scipy import sparse from scipy.stats import poisson from scipy.optimize import nnls from fdr import qvalues from sklearn.linear_model import ElasticNet from sklearn.linear_model import Lasso from sklearn....
nilq/baby-python
python
# coding: utf8 import clinica.pipelines.engine as cpe class T1VolumeParcellation(cpe.Pipeline): """T1VolumeParcellation - Computation of mean GM concentration for a set of regions. Returns: A clinica pipeline object containing the T1VolumeParcellation pipeline. """ def check_custom_dependen...
nilq/baby-python
python
import os import unittest from tempfile import TemporaryDirectory import numpy as np from l5kit.visualization import write_video class TestVideoVisualizationHelpers(unittest.TestCase): def test_write_video(self) -> None: # Just a smoke test images = (np.random.rand(5, 512, 512, 3) * 255).astype(...
nilq/baby-python
python
"""This module contains implementations of 'array list' data structure""" from typing import TypeVar, Generic, List, Callable Item = TypeVar('Item') class ArrayList(Generic[Item]): def __init__(self, size: int, realloc_coeff: int, potential_formula: Callable[[int, int], int]): if size < 0: r...
nilq/baby-python
python
""" pip install selenium """ import os from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.actio...
nilq/baby-python
python
import time import numpy as np class Learner(object): ''' Define interface of methods that must be implemented by all inhereting classes. ''' def __init__(self, discount_factor=1, learning_rate=1): self._values = {} self._prev_values = {} self._discount_factor = discount_factor...
nilq/baby-python
python
MOD = 1_000_000_007 L = [0, 2, 8] n = int(input()) for i in range(3, n+1): L.append((L[-1]*3 + 2)%MOD) print(L[n]%MOD)
nilq/baby-python
python
### mb-soil-moisture.py v1.2 ### Show soil moisture on micro:bit display using resistive and capacitive sensors ### Tested with BBC micro:bit v1.5 and MicroPython v1.9.2-34-gd64154c73 ### on a Cytron Edu:bit ### MIT License ### Copyright (c) 2021 Kevin J. Walters ### Permission is hereby granted, free of charge, to...
nilq/baby-python
python
# -*- coding: utf-8 -*- import json def save_json(file_path, data): """ Load data to json file. >>> save_json("./JsonAccessorDoctest.json", "{"Fuji": {"Id": 30, "server": ["JP", "CN"]}}") # doctest: +SKIP """ with open(file_path, 'w', encoding='utf8') as outfile: json.dump(data, outfile, ...
nilq/baby-python
python
""" This lambda compares new batches to previous batches to detect which records are missing from the new one. These indicate that a membership has lapsed. """ import datetime import json import os import boto3 from actionnetwork_activist_sync.actionnetwork import ActionNetwork from actionnetwork_activist_sync.loggi...
nilq/baby-python
python
""" vp_overlap.py Do calculations for overlap type functionals """ import numpy as np from scipy.special import erf def vp_overlap(self): const = 2 #Calculate overlap self.E.S = self.grid.integrate((np.sum(self.na_frac, axis=1) * np.sum(self.nb_frac, axis=1))**(0.5)) self.E.F = erf( const * self.E.S...
nilq/baby-python
python
from datetime import datetime def voto(ano): global idade idade = datetime.now().year - ano if idade < 16: return 'NEGADO' elif idade < 18: return 'OPCIONAL' else: return 'OBRIGATORIO' idade = 0 tip = voto(int(input('Em que ano vc nasceu?: '))) print(f'com {idade} anos, O seu...
nilq/baby-python
python
# -*- coding: utf-8 -*- import base64 import urlparse import urllib import hashlib import re from resources.lib.modules import client from resources.lib.modules import directstream from resources.lib.modules import trakt from resources.lib.modules import pyaes RES_4K = ['4k', 'hd4k', 'hd4k ', '4khd', '4khd ', 'uhd...
nilq/baby-python
python
# -*- coding: utf-8 -*- from collections import OrderedDict from copy import deepcopy import errno import fnmatch import logging import os import random import shutil import string import subprocess import yaml import sys from ansible_vault import Vault def _is_py3(): return True if sys.version_info >= (3, 0) el...
nilq/baby-python
python
def a(z): print(z + z) a(0) a('e') a([0])
nilq/baby-python
python
# Generated by Django 2.2.5 on 2019-10-26 18:45 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='Cat...
nilq/baby-python
python
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 RESOLUTION = ["Performance Tuning of Cortex XSOAR Server: https://docs.paloaltonetworks.com/cortex/cortex-xsoar/6-0/" "cortex-xsoar-admin/cortex-xsoar-overview/performance-tuning-of-cortex-xsoar-server"] def ana...
nilq/baby-python
python
class DSN: def __init__(self, user, password, database="test", host="localhost", port: int = 3306, charset="utf8"): self.user = user self.password = password self.host = host self.port = port self.database = database ...
nilq/baby-python
python
from vart.sampler.walkers import Walkers class SamplerBase(object): def __init__(self,nwalkers=1000, nstep=1000, nelec=1, ndim=3, step_size = 3, domain = {'min':-2,'max':2}, move='all'): self.nwalkers = nwalkers self.nstep = nstep self.step_size = step_s...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021 Johns Hopkins University (Jiatong Shi) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) import argparse import codecs import sys def get_parser(): parser = argparse.ArgumentParser(description="language identification scoring") parser...
nilq/baby-python
python
# -*- coding: utf-8 -*- import pytest import csv import sys import os from filecmp import cmp from feature_extractor.feature_extractor import FeatureExtractor __author__ = "Harvey Bastidas" __copyright__ = "Harvey Bastidas" __license__ = "mit" class Conf: """ This method initialize the configuration variables f...
nilq/baby-python
python
# coding:utf-8 from . import api from ..models import User,Bucketlist from flask import request, jsonify, abort, make_response @api.route('/bucketlists/', methods=['POST', 'GET']) def bucketlists(): # get the access token access_token = request.headers.get('Authorization') if access_token: user_id...
nilq/baby-python
python
# Standard Library import asyncio import json import logging import os import time from datetime import datetime # Third Party import kubernetes.client from elasticsearch import AsyncElasticsearch, exceptions from elasticsearch.helpers import async_streaming_bulk from kubernetes import client, config from kubernetes.c...
nilq/baby-python
python
from django import template from django.contrib.auth.models import User from ..forms import UserCreateForm register = template.Library() @register.inclusion_tag('registration/_signup.html') def signup_form(): return {'form': UserCreateForm(instance=User())}
nilq/baby-python
python
coordinates_E0E1E1 = ((128, 86), (129, 81), (129, 84), (129, 86), (130, 82), (130, 86), (130, 97), (130, 116), (130, 119), (131, 69), (131, 82), (131, 84), (131, 86), (131, 96), (131, 97), (131, 112), (131, 114), (131, 116), (131, 117), (131, 119), (132, 70), (132, 71), (132, 83), (132, 85), (132, 87), (132, 96), (13...
nilq/baby-python
python
# ============================================================================= # # Jade Tree Personal Budgeting Application | jadetree.io # Copyright (c) 2020 Asymworks, LLC. All Rights Reserved. # # ============================================================================= from flask.views import MethodView from...
nilq/baby-python
python
from setuptools import setup import codecs from fns import __version__ with codecs.open('README.md', 'r', 'utf-8') as readme: long_description = readme.read() setup( name='fns', version=__version__, description='Revise receipt client', author='Sergey Popov', author_email='poserg@gmail.com', ...
nilq/baby-python
python
from pyconvcli import PyConvCli import os def main(): cli = PyConvCli('pyconvcli_internal_cli',os.path.dirname(os.path.realpath(__file__)),'pyconvcli') cli.run() def visualize(): cli= PyConvCli('pyconvcli_internal_cli',os.path.dirname(os.path.realpath(__file__)),'pyconvcli') args,parsers = cli.parse_a...
nilq/baby-python
python
class VectorUtils: def __init__(self): pass @staticmethod def norm_2(vec): return vec[0]**2 + vec[1]**2 + vec[2]**2 @staticmethod def norm(vec): return VectorUtils.norm_2(vec)**(1./2)
nilq/baby-python
python
import time # so we can use "sleep" to wait between actions import RPi.GPIO as io # import the GPIO library we just installed but call it "io" from ISStreamer.Streamer import Streamer # import the ISStreamer ## name the bucket and individual access_key #streamer = Streamer(bucket_name="Locker Protector", bucket_key="l...
nilq/baby-python
python
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 from django.utils.translation import ugettext_lazy as _ title = _("Reporters and Groups") tab_link = "/reporters"
nilq/baby-python
python
# persistence.py """ Wrapper to edit the persistent settings """ import os import sys import pathlib import argparse import configparser import thinkpad_tools_assets.classes from thinkpad_tools_assets.cmd import commandline_parser from thinkpad_tools_assets.utils import NotSudo try: if os.getuid() != 0: ...
nilq/baby-python
python
from .interval import Interval, str_to_iv from dataclasses import dataclass from itertools import product from math import prod @dataclass(frozen=True) class Cuboid: points: list[Interval] value: any = None def volume(self) -> int: return prod((x.get_length() for x in self.points)) def di...
nilq/baby-python
python
import argparse from .display import LINE_SIZE class Args: def __init__(self, * args, mutex: list = [], group: list = [], **kargs): self.args = args self.kargs = kargs self.group = group self.mutex = mutex self.arguments = None def build(self, parser=None): i...
nilq/baby-python
python
from datetime import datetime as dt import requests, re import pandas as pd import numpy as np import json import time import os import tushare as ts import logging from bs4 import BeautifulSoup logger = logging.getLogger('main.fetch') def fetch_index(index_name): path = os.path.dirname(os.path.abspath(__file__))...
nilq/baby-python
python
import os.path from nbt.nbt import NBTFile from PIL import Image from config import * def main(): # Read map files to sort by scale print("Reading map files...") mapfiles = [] for i in range(0,5): mapfiles.append([]) i = 0 while os.path.isfile(inputDir + "map_" + str(i) + ".dat"): # read file nbt = NBTFil...
nilq/baby-python
python
from queue import Queue import threading class Synchonizer: def __init__(self): return
nilq/baby-python
python
nome = str(input('Digite o seu nome completo: ')).strip().title() fatiar = nome.split() fatiar2 = nome.split() print(f'Primeiro nome: {fatiar[0]};') print(f'Último nome: {fatiar2[-1]}.')
nilq/baby-python
python
#!/usr/bin/env python3 import os import numpy as np from shutil import copyfile import glob import argparse import h5py import datetime from dateutil.parser import isoparse import time import decimal import shutil from scipy.interpolate import interp2d import pybind_isce3 as isce3 from shapely import wkt from alos_t...
nilq/baby-python
python
from django.conf.urls import url from django.urls import include, path from django.contrib.auth import views as auth_views from django.urls import reverse_lazy from envelope.views import ContactView from . import views from .forms import MyContactForm urlpatterns = [ # path('change-password/', auth_views.Passwo...
nilq/baby-python
python
""" Finds all possible combinations of integers below value to generate value Author: Juan Rios """ import math """ Calculate the possible number of partitions """ def find_partitions_dict(limit_value): p = {(1,1):0} for i in range(2,limit_value+1): tmp = 1 index = 1 while index<=(i-ind...
nilq/baby-python
python
""" This script generates google search queries and uses requests to go get the HTML from the google search page. This was the most time-consuming step in the process. Certain lines are commented out as evidence of debugging and to help me remember what I had already done. Anyways, this script ma...
nilq/baby-python
python
from django import forms from django.core.exceptions import ValidationError import re def validar_exclucion_numeros(value): if value != 'None': numeros = re.sub("[^0-9]", "", value) if numeros: raise ValidationError("No permite numeros") else: return value retur...
nilq/baby-python
python
class Solution: def maxNumber(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] """ def prep(nums, k): dr = len(nums) - k # 要删除的数目 stay = [] # 保留的list for num in ...
nilq/baby-python
python
from BeautifulSoup import BeautifulSoup from urllib2 import urlopen import re print("Searching... please wait") emails=[] url="http://www.bbe.caltech.edu/people-public/all/all" data=urlopen(url) parse=BeautifulSoup(data).findAll('a') b=[parse[k]['href'][7:] for k in range(len(parse)) if "@" in parse[k]['hre...
nilq/baby-python
python
from __future__ import absolute_import from .base import ViewTest, TemplateViewTest, RedirectViewTest from .dates import (ArchiveIndexViewTests, YearArchiveViewTests, MonthArchiveViewTests, WeekArchiveViewTests, DayArchiveViewTests, DateDetailViewTests) from .detail import DetailViewTest from .edit import (Mod...
nilq/baby-python
python
#!/usr/bin/env python """ Insert blank notes at the top of every set of cards. Useful for creating new cards in bulk with an editor. This is undone by running the normalization code, `sort.py`. """ import glob from collections import OrderedDict from library import DynamicInlineTableDict from library import NoteLi...
nilq/baby-python
python
from math import sqrt class cone(): def __init__(self,radius,height): self.radius = radius self.height = height def volume(self): r = 3.14*self.radius**2*(self.height/3) print("Volume of Cone a is : ",r) def surfaceArea(self): import math c = 3.1...
nilq/baby-python
python
# Copyright 2018 by Paolo Inglese, National Phenome Centre, Imperial College # London # All rights reserved. # This file is part of DESI-MSI recalibration, and is released under the # "MIT License Agreement". # Please see the LICENSE file that should have been included as part of this # package. import t...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' vi $HOME/.LoginAccount.txt [mailClient] host = smtp.qq.com port = 25 user = *** pass = *** fr = xxxxxx@qq.com to = xxxxxx@gmail.com debuglevel = True login = False starttls = False ''' __all__ = ['get_smtp_client', 'sendmail'] import os, sys from ConfigParser import ...
nilq/baby-python
python
from django.urls import path from . import views urlpatterns = [ path("", views.profil, name="profil"), path('sport_profil/', views.create_sport_profil, name="createSportProfil"), ]
nilq/baby-python
python
from __future__ import division, absolute_import __copyright__ = """ Copyright (C) 2013 Andreas Kloeckner Copyright (C) 2018 Matt Wala Copyright (C) 2018 Hao Gao """ __license__ = """ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ...
nilq/baby-python
python
""" Render shortest/fastest paths for intervals as HTML. """ from typing import Any, List, Optional, Tuple import attr import osmnx as ox from jinja2 import Template from .routing import RestrictedGraph from .calculation import IntervalCalculation @attr.define class Page: """ A full HTML page of interval calc...
nilq/baby-python
python
# -*- coding: utf-8 -*- from .Cardstack import * from .Exception import * from copy import deepcopy playPreds = ("PLAY", "PLAY COIN", "THRONE", "THRONE GENERIC", "THRONE COIN", "KING") # -- Standard Exceptions -- # def persistent(exc): newExc = deepcopy(exc) newExc.persistent = True return newExc def...
nilq/baby-python
python
import unittest import numpy as np import mesostat.utils.iterators.sweep as sweep class TestUtilIterSweep(unittest.TestCase): pass # TODO: Implement me unittest.main()
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ####################################################### # Script that runs all regression tests. # # # MWetter@lbl.gov 2011-02-23 ####################################################### # from collections import defaultdict from contextlib import ...
nilq/baby-python
python
#! /usr/bin/env python3 # coding: utf-8 from __future__ import annotations import logging from logging import StreamHandler import os log = logging.getLogger() formatter = logging.Formatter("%(filename)s %(levelname)s - %(message)s") handler = StreamHandler() handler.setFormatter(formatter) log.addHandler(handler) l...
nilq/baby-python
python
#!/usr/bin/env python3 from argparse import ArgumentParser, Namespace from datetime import date, datetime from lxml import etree from geopy.distance import vincenty def main(arguments: Namespace): aggregated_total_distance = sum( track_distance(gpx_file) for gpx_file in arguments.gpx_files) ...
nilq/baby-python
python
from django.contrib import admin from .models import Tutorial, Complemento admin.site.register(Tutorial) admin.site.register(Complemento)
nilq/baby-python
python
# Generated by Django 2.1.3 on 2019-06-23 15:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pdfmerge', '0013_auto_20190623_1536'), ] operations = [ migrations.AlterField( model_name='pdfformfield', name='fiel...
nilq/baby-python
python
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) try: # Agent5 compatibility layer from checks.libs.win.pdhbasecheck import PDHBaseCheck from checks.libs.win.winpdh import WinPDHCounter except ImportError: from .winpdh_base import PDHBaseCheck ...
nilq/baby-python
python
from __future__ import print_function from __future__ import absolute_import import cv2 from .tesisfunctions import Plotim,overlay,padVH import numpy as np from RRtoolbox.lib.plotter import Imtester # http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological...
nilq/baby-python
python
"""Bank module message types.""" from __future__ import annotations import copy from typing import List from secret_sdk.core import AccAddress, Coins from secret_sdk.core.msg import Msg from secret_sdk.util.json import JSONSerializable, dict_to_data __all__ = ["MsgSend", "MsgMultiSend", "MultiSendIO"] import attr ...
nilq/baby-python
python
from datetime import datetime import numpy as np from pixiu.api.defines import (OrderCommand) from pixiu.api.utils import (parse_datetime_string) class Order(object): def __init__(self, params={'volume': 0}): self.order_dict = params.copy() open_time = self.order_dict.get("open_time", None) ...
nilq/baby-python
python
import numpy as np def eval_q2m(scores, q2m_gts): ''' Image -> Text / Text -> Image Args: scores: (n_query, n_memory) matrix of similarity scores q2m_gts: list, each item is the positive memory ids of the query id Returns: scores: (recall@1, 5, 10, median rank, mean rank) gt_ranks: the best ran...
nilq/baby-python
python
import traceback import uuid import socket import logging import os import base64 import zlib import gzip import time import datetime from http import cookies from http.server import BaseHTTPRequestHandler from http.server import HTTPServer from threading import Thread import WebRequest def capture_expected_headers...
nilq/baby-python
python
import json from concurrent.futures import ThreadPoolExecutor import psutil from notebook.base.handlers import IPythonHandler from tornado import web from tornado.concurrent import run_on_executor try: # Traitlets >= 4.3.3 from traitlets import Callable except ImportError: from .utils import Callable cl...
nilq/baby-python
python
NOT_CONTINUATION = -1 CONTINUATION_START = 0 CONTINUATION = 1 CONTINUATION_END = 2 CONTINUATION_EXPLICIT = 3 #A function that returns the correct set of language regex expressions for functions #and function like objects. class languageSwitcher(object): def __init__(self, ext): self.lang = "" sel...
nilq/baby-python
python
import logging from typing import Any from typing import List from typing import Optional from matchms.utils import filter_none from matchms.utils import get_common_keys from ..typing import SpectrumType logger = logging.getLogger("matchms") _retention_time_keys = ["retention_time", "retentiontime", "rt...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright 2020 Google LLC # # 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 ...
nilq/baby-python
python
# # cortexm.py # # # Copyright (c) 2013-2017 Western Digital Corporation or its affiliates. # # 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, ...
nilq/baby-python
python
# Advent of Code - Day 5 - Part One from collections import defaultdict def result(data): points = defaultdict(int) for line in data: a, b = line.split(' -> ') x1, y1 = a.split(',') x2, y2 = b.split(',') x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2) min_x, max_...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Split Definition dataclass""" from dataclasses import dataclass from typing import Optional, List from .rule import Rule from .treatment import Treatment from .environment import Environment from .default_rule import DefaultRule from .traffic_type import TrafficType @dataclass class Split...
nilq/baby-python
python
#!/usr/bin/env python # Copyright (c) 2006-2010 Tampere University of Technology # # 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
import serial import struct s = serial.Serial('/dev/cu.usbserial-A600e0ti', baudrate=19200) def receive_msg(): print 'Receiving messages' message = [] c = s.read() while c != '\n': message.append(c) message = ''.join(message) print 'Msg:', message
nilq/baby-python
python
from django.conf.urls import url from app05plus.views import index, register, mylogin from app05plus.views import mylogout urlpatterns = [ url(r"^newindex01$",index), url(r"^register01$",register,name="register"), url(r"^mylogin01$",mylogin,name="mylogin"), url(r"^logout$",mylogout), ]
nilq/baby-python
python
import astropy.units as u import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation from einsteinpy.metric import Schwarzschild class ScatterGeodesicPlotter: """ Class for plotting static matplotlib plots. """ def __init__( self, mass, time=0 * u.s, at...
nilq/baby-python
python
import os, sys import numpy as np import matplotlib import matplotlib.pyplot as plt import scipy.signal from classy import Class from helper import cache_grendel, cropsave, grendel_dir """ For just one of the boxes, plot the absolute CONCEPT and GADGET spectra over time, including a = a_begin. """ textwidth = 504...
nilq/baby-python
python
import sys import errno from contextlib import contextmanager from lemoncheesecake.cli.command import Command from lemoncheesecake.cli.utils import auto_detect_reporting_backends, add_report_path_cli_arg, get_report_path from lemoncheesecake.reporting import load_report from lemoncheesecake.reporting.backends.console ...
nilq/baby-python
python
import torch from torch.utils.data import Dataset class GenericDataSet(Dataset): def __init__(self, x_inputs: torch.Tensor, y_targets: torch.Tensor): if x_inputs.size()[0] != y_targets.size()[0]: raise Exception("row count of input does not match targets") ...
nilq/baby-python
python
from abc import ABC, abstractmethod from typing import Iterable, Mapping, Optional from bankroll.model import AccountBalance, Activity, Position from .configuration import Settings # Offers data about one or more brokerage accounts, initialized with data # (e.g., exported files) or a mechanism to get the data (e.g....
nilq/baby-python
python
"""Integration platform for recorder.""" from __future__ import annotations from homeassistant.core import HomeAssistant, callback from . import ATTR_AVAILABLE_MODES, ATTR_MAX_HUMIDITY, ATTR_MIN_HUMIDITY @callback def exclude_attributes(hass: HomeAssistant) -> set[str]: """Exclude static attributes from being r...
nilq/baby-python
python
from django.shortcuts import render from .models import Image, Video from .serializers import ImageSerializer, VideoSerializer from accounts.permissions import isAdminOrReadOnly from rest_framework.response import Response from rest_framework import status from rest_framework.viewsets import ModelViewSet # Create you...
nilq/baby-python
python