content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
"""Integration with nest devices.""" import json import logging import sys from google.appengine.api import urlfetch from google.appengine.ext import ndb from appengine import account, device, rest @device.register('nest_thermostat') class NestThermostat(device.Device): """Class represents a Nest thermostat.""" ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os def run_tests(**options): import django import sys from django.conf import settings from ginger.conf.settings import template_settings defaults = dict( MIDDLEWARE_CLASSES=( 'django.contrib.sessions.middleware....
nilq/baby-python
python
from __future__ import print_function import os from os.path import dirname, join, abspath, isdir import sys import json import requests try: from urlparse import urljoin except: from urllib.parse import urljoin # python 3.x # http://python-redmine.readthedocs.org/ from redmine import Redmine if __name...
nilq/baby-python
python
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * vertices = ( # ( x, y, z) ( 1, -1, -1), # A ( 1, 1, -1), # B (-1, 1, -1), # C (-1, -1, -1), # D ( 1, -1, 1), # E ( 1, 1, 1), # F (-1, -1, 1), # G (-1, 1, 1) # ...
nilq/baby-python
python
#!/usr/bin/env python import argparse import math from collections import Counter from spawningtool.parser import parse_replay def map_replays(filenames, map_fn, results, update_fn, cache_dir=None, **kwargs): for filename in filenames: filename = filename.rstrip('\n') replay = parse_replay(filena...
nilq/baby-python
python
import numpy as np class Exploration_Noise: def reset(self): """ Reset the noise generator. """ pass def process_action(self, a): """ Add noise to the given action. Args: a: the action to be processed Return: the proces...
nilq/baby-python
python
from scrapy.http import Request from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector class HackernewsSpider(BaseSpider): name = 'hackernews' allowed_domains = [] start_urls = ['http://news.ycombinator.com'] def parse(self, response): if 'news.ycombinator.com' in response.url: ...
nilq/baby-python
python
import sys sys.path.insert(0, '/home/vagrant/Integration-Testing-Framework/sikuli/examples') from sikuli import * from test_helper import TestHelper from flex_regions import * from Regionplus import * # Setup helper = TestHelper("drag_column") set_flex_helper(helper) # Opening ############# helper.Click("Lexicon.png...
nilq/baby-python
python
# Copyright 2018 Datawire. 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 applicable law or agr...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: yandex/cloud/logging/v1/log_ingestion_service.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflect...
nilq/baby-python
python
""" Tests of simple 2-layer PCBs """ from . import plotting_test_utils import os import mmap import re import logging def expect_file_at(filename): assert(os.path.isfile(filename)) def get_gerber_filename(board_name, layer_slug, ext='.gbr'): return board_name + '-' + layer_slug + ext def find_gerber_ap...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-01-09 07:00 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sass', '0003_auto_20190109_0659'), ] operation...
nilq/baby-python
python
""" Fetch ads.txt files from URLs """ from datetime import datetime import logging import os import pandas as pd import requests logger = logging.getLogger(__name__) HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36", "Accept...
nilq/baby-python
python
## # Copyright 2021 IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 ## import torch from ...._utils import val_clamp from ..node import _NodeActivation from ....constants import Direction from ...parameters.neuron import _NeuronParameters """ Dynamic activation function """ class _NeuronAct...
nilq/baby-python
python
from PIL import Image import pytesseract def extractWords(): img1 = Image.open("Solution\images\img1.jpg") img2 = Image.open("Solution\images\img2.jpg") engText = pytesseract.image_to_string(img1, lang='eng') araText = pytesseract.image_to_string(img2, lang='ara') print(engText) print(araText) ...
nilq/baby-python
python
import lab12 def createSomePlanets(): aPlanet=lab12.Planet("Zorks",2000,30000,100000,5,['Steve','Lou','The Grinch']) bPlanet=lab12.Planet("Zapps",1000,20000,200000,17,[]) print(aPlanet.getName() + " has a radius of " + str(aPlanet.getRadius())) planetList=[aPlanet,bPlanet] for planet in planetList:...
nilq/baby-python
python
from .__init__ import * def home(request): return Http_Response("", "这是视频API", "") def url(request): # 获取视频URL query = request_query(request, "id", ["res", {"resolution": 1080}]) query["ids"] = '["{}"]'.format(query.pop("id")) data = send(query).POST("weapi/cloudvideo/playurl") return Http_R...
nilq/baby-python
python
# # PySNMP MIB module BNET-ATM-TOPOLOGY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BNET-ATM-TOPOLOGY-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:40:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mar 11, 2012 @author: moloch Copyright 2012 Root the Box 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/licen...
nilq/baby-python
python
# License: BSD 3 clause from datetime import datetime from typing import Dict, Iterable from os.path import join from pyspark.sql import DataFrame from pyspark.sql.functions import col, datediff, floor, lit, months_between from scalpel.core.io import get_logger, read_data_frame from scalpel.core import io from scalp...
nilq/baby-python
python
"""Bagging classifier trained on balanced bootstrap samples.""" # Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com> # Christos Aridas # License: MIT import numbers import numpy as np from sklearn.base import clone from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassi...
nilq/baby-python
python
# import theano.sandbox.cuda # theano.sandbox.cuda.use('gpu0') import numpy as np import cPickle as cP import theano as TH import theano.tensor as T import scipy.misc as sm import nnet.lasagnenetsCFCNN as LN import lasagne as L import datetime def unpickle(file): import cPickle fo = open(file, 'rb') d...
nilq/baby-python
python
import tequila as tq class QMBackend(): """ A class that holds information about a backend and can be given as a parameter to an algorithm. Attributes ---------- backend : str The name of the used backend (simulator). """ def __init__(self, backend: str = None): """ Creates a QMBackend o...
nilq/baby-python
python
#!/usr/bin/env python3.7 """ The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent """ import os import sys sys.path.append(os.pat...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ pygments.lexers.smv ~~~~~~~~~~~~~~~~~~~ Lexers for the SMV languages. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, words from pygments.token import Comment, Generic...
nilq/baby-python
python
fahrenheit = float(input("Enter temperature in Fahrenheit: ")) print("The temperature in Celsius: ", (fahrenheit-32)*(5/9))
nilq/baby-python
python
""" Tool for extending the label information with the chess game state, i.e. the camera piece color and square content. """ import argparse import cv2 as cv from rookowl.global_var import PIECE_DISPLAY_SHAPE from rookowl.label import load_labels, save_label # =≡=-=♔=-=≡=-=♕=-=≡=-=♖=-=≡=-=♗=-=≡=-=♘=-=≡=-=♙=-=≡=-=...
nilq/baby-python
python
import torch import torch.nn as nn import torch.nn.functional as F # 한 Batch에서의 loss 값 def batch_loss(loss, images): return loss.item() * images.size(0) class FocalLoss(nn.Module): def __init__(self, weight=None, gamma=2.0, reduction="mean"): nn.Module.__init__(self) self.weight = weight ...
nilq/baby-python
python
def spread_pixels(Nside_low, Nside_high, ID): from math import log Llow = int(log(Nside_low, 2)) Lhigh = int(log(Nside_high, 2)) print(Llow, Lhigh) b = bin(ID) DN = Lhigh-Llow a = [bin(i)[2:].zfill(2**DN) for i in range(4**DN)] pix_IDs = [] for i in a: x = (b[2:].zfill(...
nilq/baby-python
python
#!/usr/bin/env python """Play a fixed frequency sound.""" from __future__ import division import math from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio try: from itertools import izip except ImportError: # Python 3 izip = zip xrange = range def sine_tone(stream, frequency, duration, v...
nilq/baby-python
python
#!/usr/bin/env python3 """Forward kinematic example using pinocchio Sends zero-torque commands to the robot and prints finger tip position. """ import os import numpy as np from ament_index_python.packages import get_package_share_directory import pinocchio import robot_interfaces import robot_fingers if __name__ == ...
nilq/baby-python
python
if __name__ == '__main__' and __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) )) import os import torch from utils.model_serialization import strip_prefix_if_present from utils import zipreader import argparse from tqdm import tqdm i...
nilq/baby-python
python
import datetime from termcolor import cprint import get_all_caches as caches def calculate_all_prices(fiat='EUR', coin='XMR', start='04-02-2020', high_low='high', coin_amount=int(42), fiat_amount_spent=int(0)): coin_amount = int(coin_amount) # double casting to int here prevents crashes later on historical_...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, James Cammarata <jcammarata@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf-8 -*- # make it possible to run as standalone program import sys import re import random import string sys.path.append('/srv/chemminetools') sys.path.append('/srv/chemminetools/sdftools') # allow tools.py to be imported from django.core.management import setup_environ import chemm...
nilq/baby-python
python
import os import argparse import numpy as np class SceneGraphNode(object): def __init__(self): pass def set_attribute(self, attr, value): if attr not in self.__dict__.keys(): raise ValueError(f"Unknown attribute: {attr}") self.__dict__[attr] = value def get_attri...
nilq/baby-python
python
c = {'z': '\033[m'} l = ['w', 'r', 'g', 'y', 'b', 'm', 'c', 'k'] i = j = 0 for lin in range(30, 38): c[l[i]] = f'\033[{lin}m' i += 1 i = j = 0 for lin in range(30, 38): for col in range(40, 48): c[l[i] + l[j]] = f'\033[{lin};{col}m' j += 1 i += 1 j = 0 def clr(text='', value='z')...
nilq/baby-python
python
# Generated by Django 3.2.9 on 2022-01-15 21:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20220115_1425'), ] operations = [ migrations.AlterField( model_name='comments'...
nilq/baby-python
python
import sys import os import configparser import tkinter as tk import tkinter.ttk as ttk from tkinter import messagebox from functools import partial from PIL import ImageTk, Image from tkinter import filedialog class Gui: """ This class represents a GUI for reading, changing and writing purposes. The...
nilq/baby-python
python
""" Tests CoreML Imputer converter. """ import numpy as np import unittest try: from sklearn.impute import SimpleImputer as Imputer import sklearn.preprocessing if not hasattr(sklearn.preprocessing, 'Imputer'): # coremltools 3.1 does not work with scikit-learn 0.22 setattr(sklearn.preprocess...
nilq/baby-python
python
from django.core.exceptions import ValidationError def following_changed(sender, action, instance, *args, **kwargs): """Raise an error if admin tries to assign User to the Users follow list""" # m2mchanged.connect specified in apps.py following = instance.following.all() creator = instance.user ...
nilq/baby-python
python
from arcutils.settings import PrefixedSettings DEFAULTS = { 'default': { # Notes: # - There are two LDAP hosts, ldap-bulk and ldap-login; Elliot has # said that ldap-login "has more servers in the pool" and he # recommends using it over ldap-bulk (RT ticket #580686); n...
nilq/baby-python
python
from django.contrib import admin from ledger.accounts.models import EmailUser from disturbance.components.proposals import models from disturbance.components.proposals import forms from disturbance.components.main.models import ActivityMatrix, SystemMaintenance, ApplicationType #from disturbance.components.main.models ...
nilq/baby-python
python
# Copyright 2019 Belma Turkovic # TU Delft Embedded and Networked Systems Group. # NOTICE: THIS FILE IS BASED ON https://github.com/p4lang/behavioral-model/blob/master/mininet/p4_mininet.py, BUT WAS MODIFIED UNDER COMPLIANCE # WITH THE APACHE 2.0 LICENCE FROM THE ORIGINAL WORK. # Copyright 2013-present Barefoot Netw...
nilq/baby-python
python
from rl.agent import DiscreteAgent from rl.environment import DiscreteEnvironment from rl.experience_tuple import ExperienceTupleSerializer class ExperimentConfiguration: """Configuration to run an Experiment.""" def __init__(self, agent: DiscreteAgent, environment: DiscreteEnvironment, num_...
nilq/baby-python
python
""" DREAprep.py - Allows for inputs to be passed to multiple components """ from openmdao.main.api import Component, Slot from openmdao.lib.datatypes.api import Float from MEflows import MEflows class DREAprep(Component): """ Passes input variables to output variables so they can be passed to multi...
nilq/baby-python
python
from multiprocessing import current_process, Value, Process from time import sleep from random import random from reader_writer_lock import MultiprocessingFactory from reader_writer_lock.MpFactory import Integer def test(option): test_name = ["No priority", "Read priority", "Write priority"] prin...
nilq/baby-python
python
import numpy as np class FCM: """Fuzzy C-means Parameters ---------- n_clusters: int, optional (default=10) The number of clusters to form as well as the number of centroids to generate max_iter: int, optional (default=150) Hard limit on iterations within solver. m: f...
nilq/baby-python
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 19-1-24 下午4:04 # @Author : Hubery # @File : helper.py # @Software: PyCharm import json import requests from django.core.cache import cache from HuberyBlog.settings import BASE_HEADERS def page_cache(timeout): def wrapper1(view_func): def wrapp...
nilq/baby-python
python
import re #!/usr/bin/env python3 def getStarSystems(): starsfound = re.compile("\Stars Visited\": (\alnum+\.\alnum+)") result = starsfound.findall(content) stars = [] if result: for r in result: stars.append(r) print(result) return stars
nilq/baby-python
python
import os import sys import tempfile import subprocess import contextlib import json import time # https://stackoverflow.com/questions/6194499/pushd-through-os-system @contextlib.contextmanager def pushd(new_dir): previous_dir = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdi...
nilq/baby-python
python
import pandas as pd import shutil from shareplum import Site from shareplum.site import Version from shareplum import Office365 # SharePoint user_name = '@eafit.edu.co' password = '' authcookie = Office365('https://eafit.sharepoint.com', username=user_name, password=password).GetCookies() site = Site('https://eafit.s...
nilq/baby-python
python
# # Copyright (c) 2019, Corey Smith # # Distributed under the MIT License. # # See LICENCE file for full terms. # """ # Tests for the data examples. # """ # # import sys # import inspect # # import os # from pathlib import Path # import numpy as np # # import paramiko # # import pytest # # import sqlalchemy # # sy...
nilq/baby-python
python
""" Helios Signals Effectively callbacks that other apps can wait and be notified about """ import django.dispatch # when an election is created election_created = django.dispatch.Signal(providing_args=["election"]) # when a vote is cast vote_cast = django.dispatch.Signal( providing_args=["user", "voter", "elec...
nilq/baby-python
python
from setuptools import setup, find_packages import sys import os import re org = 'PEtab-dev' repo = 'petab_select' def read(fname): """Read a file.""" return open(fname).read() def absolute_links(txt): """Replace relative petab github links by absolute links.""" raw_base = \ f"(https://ra...
nilq/baby-python
python
REGISTRY = {} from .episode_runner import EpisodeRunner REGISTRY["episode"] = EpisodeRunner from .parallel_runner import ParallelRunner REGISTRY["parallel"] = ParallelRunner from .episode_cross_runner import EpisodeCrossRunner REGISTRY["cross"] = EpisodeCrossRunner
nilq/baby-python
python
import numpy as np import pandas as pd from sklearn.metrics.pairwise import euclidean_distances from scipy.io import loadmat from matplotlib import pyplot as plt from sklearn.metrics import normalized_mutual_info_score from sklearn.metrics import adjusted_rand_score def autoselect_dc(max_id, max_dis, min_dis, ...
nilq/baby-python
python
from __future__ import print_function import math, types import numpy as N import matplotlib.pyplot as P def plotres(psr,deleted=False,group=None,**kwargs): """Plot residuals, compute unweighted rms residual.""" res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs if (not deleted) and N.any(psr.d...
nilq/baby-python
python
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### #...
nilq/baby-python
python
import pathlib import shutil import argparse parser = argparse.ArgumentParser() parser.add_argument("--supplementary_pdf", type=str) args = parser.parse_args() supplementary = pathlib.Path(args.supplementary_pdf) if args.supplementary_pdf else None assert supplementary.exists() and supplementary.is_file() root = (pat...
nilq/baby-python
python
import datetime import json from datetime import date,timedelta from selenium import webdriver from selenium.webdriver.common.keys import Keys from operis.log import log from ws4redis.redis_store import RedisMessage from ws4redis.publisher import RedisPublisher from selenium_tests.webdriver import PpfaWebDriver #from...
nilq/baby-python
python
from flask import Flask from flask_assets import Bundle, Environment from flask_compress import Compress from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect from govuk_frontend_wtf.main import WTFormsHelpers from jinja2 import ChoiceLoader, PackageLoader, PrefixLoader from config import Config ...
nilq/baby-python
python
def operate(operator, *args): return eval(operator.join([str(x) for x in args])) print(operate("+", 1, 2, 3)) print(operate("*", 3, 4))
nilq/baby-python
python
# Generated by Django 2.0.8 on 2019-06-05 09:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('protein', '0007_proteingproteinpair_references'), ('structure', '0017_structure_contact_representative_score'), ('residue', '0002_auto_20180504_1417'...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2019 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) """Utility functions.""" import fnmatch import logging import os import sys import tarfile from distutils.version import LooseVersion import numpy as np import torch import yaml def find...
nilq/baby-python
python
from Attribute import Attribute from Distribution.DistributionFactory import DistributionFactory class AttributeFactory: """ Class to generate and deploy specific attributes that will share a distribution factory. Attributes types are: - custom - boolean - string - int or int64 ...
nilq/baby-python
python
from django.core.management.base import BaseCommand, CommandError from charts.models import ChartConfig class Command(BaseCommand): help = "Delete all ChartConfig objects" def handle(self, *args, **options): all = ChartConfig.objects.all() self.stdout.write("{} ChartConfig Type objects will...
nilq/baby-python
python
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' Dirac Hartree-Fock ''' import ctypes import time from functools import reduce import numpy import scipy.linalg from pyscf import lib from pyscf.lib import logger from pyscf.scf import hf from pyscf.scf import _vhf import pyscf.scf.chkfile def...
nilq/baby-python
python
import sys import requests import time import datetime # API URLS URL_STATS_PROVIDER = 'https://api.nicehash.com/api?method=stats.provider&addr={}' URL_BTC_PRICE = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC&tsyms={}' WALLET = '1P5PNW6Wd53QiZLdCs9EXNHmuPTX3rD6hW' #Dummy wallet. To be overwritten ##...
nilq/baby-python
python
import copy import argparse import os from PIL import Image import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as transforms import torchvision.models as models from LossFunction import ContentLoss, StyleLoss plt...
nilq/baby-python
python
import os from dotenv import load_dotenv dirname = os.path.dirname(__file__) try: #print(os.path.join(dirname, '.env')) load_dotenv(dotenv_path=os.path.join(dirname, '.env')) except FileNotFoundError: pass
nilq/baby-python
python
#!/home/alvaro/.miniconda3/envs/fazip/bin/python from fazip import fazip import sys import getpass def do_extraction(zipname): host, user, pwd = fazip.get_mysql_info() db = fazip.connect_to_db(user, pwd, host) fazip.unzip_files(db, zipname) db.close() def do_compression(zipname, files): host, u...
nilq/baby-python
python
import sys, os sys.path.append(os.pardir) from lark import Lark, Token from parsing import grammar, cool_ast, preprocess from parsing.cool_transformer import ToCoolASTTransformer from checksemantic.checksemantics import CheckSemanticsVisitor from checksemantic.scope import Scope from cool import fetch_program ...
nilq/baby-python
python
#!/usr/bin/env python # -*- animation -*- """ Visualize a complex-valued function """ import numpy as np import gr def domain_colors(w, n): H = np.mod(np.angle(w) / (2 * np.pi) + 1, 1) m = 0.7 M = 1 isol = m + (M - m) * (H * n - np.floor(H * n)) modul = np.absolute(w) Logm = np.log(modul) ...
nilq/baby-python
python
from django.urls import path,include from django.conf import settings from django.conf.urls.static import static from rest_framework.documentation import include_docs_urls import notifications.urls urlpatterns = [ path(r'', include('rbac.urls')), path(r'', include('cmdb.urls')), path(r'', include('rmms.url...
nilq/baby-python
python
# Copyright 2018-2021 Jakub Kuczys (https://github.com/jack1142) # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
nilq/baby-python
python
import logging import os import numpy as np from .siamese_net import DNN logger = logging.getLogger(__name__) package_directory = os.path.dirname(os.path.abspath(__file__)) similarity_model_pretrained = os.path.join(package_directory, "model") class SimilarityModel: def __init__(self): self.model = Non...
nilq/baby-python
python
from __future__ import annotations from yarl import URL import io import typing import os from .factory import construct_repr if typing.TYPE_CHECKING: from .factory import HttpHandler __all__ = ("Image",) class Image: """ A class representing an `Image`. Attributes: url (str): URL of the...
nilq/baby-python
python
import logging import enum import copy import telegram.error from telegram import ( InlineKeyboardButton, InlineKeyboardMarkup, ParseMode ) from app.entities import KnowledgeStatus from app.card import Card logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level...
nilq/baby-python
python
#! /usr/bin/env python # -*- coding: utf-8 -*- import socket default_port = 8003 # default port when adding a new server listen_port = 8003 # server listens on this port my_address = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("1.")][0] dns_module_listen_port = 800...
nilq/baby-python
python
import datetime import logging from django.core.management.base import BaseCommand from django.db import connection, transaction from framework.celery_tasks import app as celery_app logger = logging.getLogger(__name__) TABLES_TO_POPULATE_WITH_MODIFIED = [ 'addons_zotero_usersettings', 'addons_dropbox_userset...
nilq/baby-python
python
#!/usr/bin/env python #Makes the output file "grid" which is used in various postprocessing scripts import argparse import numpy as np import sys import os import re # parse command line options parser = argparse.ArgumentParser(description="Generates a cartesian mesh with a uniform region surrounded by a stretched gri...
nilq/baby-python
python
""" App entry point which register FastAPI routers. More info about used app structure: https://fastapi.tiangolo.com/tutorial/bigger-applications/ If you want to create a new API endpoint add endpoint handler to existed router or create a new module in `routes` directory. """ from fastapi import FastAPI from fastapi....
nilq/baby-python
python
import numpy as np import pandas as pd import matplotlib.pyplot as plt import os from matplotlib import cm from scipy.interpolate import interp1d from scipy.spatial import distance from scipy.optimize import differential_evolution CELL_INFO_DIR = os.path.join('data-share', 'raw', 'cell_info') def blend_electrodes(el...
nilq/baby-python
python
#!/usr/bin/env python from distutils.core import setup setup(name = "ciscotropo-webapi-python", version = "0.1.4", url = "http://github.com/tropo/tropo-webapi-python", maintainer = "Cisco", maintainer_email = "support@tropo.com", description ...
nilq/baby-python
python
from heuslertools.tools.measurement import Measurement import xrayutilities as xu import warnings import numpy as np class RSMMeasurement(Measurement): """Object representing rsm measurement. Parameters ---------- file : str path of xrdml file. Attributes ---------- en : str ...
nilq/baby-python
python
import numpy as np import numpy.linalg as la def gaussian_estimate(data, label, alpha): assert len(data) == len(label), "label length mismatch" assert label.min() == 0, "label should start from 0" assert label.max() != 0, "label should have multiple" trim = np.sum(data, axis=0) > 0 data = data[:, ...
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 # ...
nilq/baby-python
python
# coding=utf-8 """ Default Django settings for all Work4 projects. Your own app should import all attributes from this file. """ from __future__ import unicode_literals import os import sys from tzlocal import get_localzone def env_to_bool(val): """Use this when parsing environment variables for booleans as ...
nilq/baby-python
python
""" This will module contains the setup_flask function as well as registry functions """ __author__ = 'Ben Christenson' __date__ = "9/15/15" import os import inspect import sys from flask import Flask from flask_sqlalchemy import SQLAlchemy import flask_login from flask_login import LoginManager from flask.blueprints ...
nilq/baby-python
python
import wasm3 as m3 import pytest from helpers import wat2wasm MV_SWAP_WASM = wat2wasm(""" (module (func (export "swap") (param i32 i32) (result i32 i32) (get_local 1) (get_local 0) ) ) """) MV_IMPORT_WASM = wat2wasm(""" (module (type $t0 (func (param i32 i64) (result i64 i32))) (import "env" "swap" (...
nilq/baby-python
python
""" # lint-amnesty, pylint: disable=cyclic-import XFields for video module. """ import datetime from xblock.fields import Boolean, DateTime, Dict, Float, List, Scope, String from xmodule.fields import RelativeTime # Make '_' a no-op so we can scrape strings. Using lambda instead of # `django.utils.translation.ug...
nilq/baby-python
python
"""Ingest by directly writing a ZIP file to archive storage. """ from __future__ import print_function import sys import os import os.path import re import time from threading import Thread if sys.version_info < (3, 0): import Queue as queue else: import queue import zlib import logging import pytest import ic...
nilq/baby-python
python
from rest_framework import permissions class UpdateOwnProfile(permissions.BasePermission): def has_object_permission(self,request,view,obj): if request.method in permissions.SAFE_METHODS: return True return obj.id==request.user.id class UpdateStatus(permissions.BasePermission): de...
nilq/baby-python
python
import collections import logging import string from abc import abstractmethod from typing import Callable, List from flask_sqlalchemy import SQLAlchemy from retrying import retry from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import FlushError, NoResultFound from profiles.exceptions import OrcidTo...
nilq/baby-python
python
from .common import EWSAccountService, create_attachment_ids_element from ..properties import RootItemId from ..util import create_element class DeleteAttachment(EWSAccountService): """MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/deleteattachment-operation """ ...
nilq/baby-python
python
""" 388. Longest Absolute File Path Medium Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: Here, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1...
nilq/baby-python
python
# -*- coding: utf-8 -*- # DO NOT EDIT THIS FILE! # This file has been autogenerated by dephell <3 # https://github.com/dephell/dephell try: from setuptools import setup except ImportError: from distutils.core import setup readme = "" setup( long_description=readme, name="tgintegration", version=...
nilq/baby-python
python
import logging from datetime import datetime import tweepy import creds from main import make_covid_graph logging.basicConfig(filename='nepal-covid.log', level=logging.INFO, format='%(asctime)s-%(name)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ test_compat.py Last updated: 2019-09-27 """ from wz_core.reporting import Report from test_core import testinit, runTests if __name__ == '__main__': testinit () # from wz_compat import migrate # runTests (migrate) # from wz_compat import import_pup...
nilq/baby-python
python