content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from functools import lru_cache import requests from six import u from unidecode import unidecode _synset_sparql_query = """ SELECT ?item ?itemLabel WHERE {{ ?item wdt:P2888 <http://wordnet-rdf.princeton.edu/wn30/{}-n> SERVICE wikibase:label {{ bd:serviceParam wikibase:language "{}". }} }} """ _wikidata_url = 'h...
nilq/baby-python
python
#!/usr/bin/env python # encoding: utf-8 import sys if sys.version_info.major > 2: import http.server as http_server import socketserver else: import SimpleHTTPServer as http_server import SocketServer as socketserver Handler = http_server.SimpleHTTPRequestHandler # python -c "import SimpleHTTPServer;...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Authors: Tim Hessels Contact: t.hessels@un-ihe.org Repository: https://github.com/TimHessels/SEBAL Module: SEBAL Description: This module contains a compilation of scripts and functions to run pySEBAL """ from SEBAL import pySEBAL __all__ = ['pySEBAL'] __version__ = '0.1'
nilq/baby-python
python
import unittest import smartphone from parameterized import parameterized, parameterized_class TEST_PHONE_NUMBER = '123' class SmartPhoneTest(unittest.TestCase): def setUp(self): super().setUp() self.phone = smartphone.SmartPhone() @parameterized.expand([ ('idle', smartphone.CallState.IDLE, f'Has ca...
nilq/baby-python
python
#!/usr/bin/env python import Bio; from Bio import SeqIO from Bio.SeqRecord import SeqRecord import urllib2 import sys import StringIO import os base = os.path.expanduser('~') prot_folder = base + '/biotools/uniprot_proteomes/' fasta_records = [] if len(sys.argv) == 1: accession = input('Enter UNIPROT proteome acces...
nilq/baby-python
python
import os import math import cereal.messaging as messaging import cereal.messaging_arne as messaging_arne from selfdrive.swaglog import cloudlog from common.realtime import sec_since_boot from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU from selfdrive.controls.lib.longitudinal_mpc import libmpc_py from...
nilq/baby-python
python
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Fourth Paradigm Development, Inc. # # Licensed under the Apache License, Version 2.0 (the "Licen...
nilq/baby-python
python
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
nilq/baby-python
python
""" This file is part of genofunc (https://github.com/xiaoyu518/genofunc). Copyright 2020 Xiaoyu Yu (xiaoyu.yu@ed.ac.uk) & Rachel Colquhoun (rachel.colquhoun@ed.ac.uk). """ import os import unittest from genofunc.extract_metadata import * this_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) data_di...
nilq/baby-python
python
from .atmosphere import Atmosphere from .generalized_atmosphere import GeneralizedAtmosphere from .generalized_matching import GeneralizedMatching from .psycop import PSYCOP from .illicit_conversion import IllicitConversion from .logically_valid_lookup import LogicallyValidLookup from .matching import Matching f...
nilq/baby-python
python
import demistomock as demisto from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import from CommonServerUserPython import * # noqa import requests import traceback from typing import Dict, Any # Disable insecure warnings requests.packages.urllib3.disable_warnings() TYPES = { 'threatType...
nilq/baby-python
python
from typing import Optional from odmantic import Model class Person(Model): name: str age: Optional[int] john = Person(name="John") print(john.age) #> None
nilq/baby-python
python
""" Implementation of DRO models """ import gurobipy as grb import numpy as np from time import time def train_classifier(Kernel, labels_raw, all_epsilon, all_kappa, nc): print('Train class ', nc + 1, '...') t = time() n_samples = Kernel.shape[0] alpha = np.zeros((n_samples, len(al...
nilq/baby-python
python
import sys if len(sys.argv) != 2: print("Usage: python buildcml.py <cml file>") exit(1) infile = sys.argv[1] # file names outfile_md = "docs/" + infile.split(".")[0] + ".md" outfile_txt = infile.split(".")[0] + ".txt" # file buffers md_buffer = "# Controller Layouts\n" txt_buffer = "" with open(infile, "r") as ...
nilq/baby-python
python
from dataclasses import field from datetime import datetime from typing import List, Optional from pydantic.dataclasses import dataclass @dataclass class TypeA: one: str two: float @dataclass class TypeB(TypeA): one: str three: bool = field(default=True) @dataclass class TypeC(TypeB): four: ...
nilq/baby-python
python
import requests import unittest class TestStringMethods(unittest.TestCase): '''def test_000_operacoes_ola1(self): r = requests.get('http://localhost:5000/ola/marcio') self.assertEqual(r.text,'ola marcio') r = requests.get('http://localhost:5000/ola/mario') self.assertEqual(r....
nilq/baby-python
python
from pytest import (fixture, mark) from wrdpzl import(Board, Solver) @fixture(scope='module') def words(): with open('words.txt') as file: return list(map(str.strip, file.readlines())) @fixture(scope='module') def solver(words): return Solver(words) @mark.timeout(0.5) @mark.parametrize('board', [ ...
nilq/baby-python
python
# Copyright (c) 2017-2021 Analog Devices Inc. # All rights reserved. # www.analog.com # # SPDX-License-Identifier: Apache-2.0 # import PMBus_I2C from encodings import hex_codec import codecs from time import * from array import array import math import sys if sys.version_info.major < 3: input = ...
nilq/baby-python
python
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """Url Ent...
nilq/baby-python
python
import queue import time from threading import Thread import cv2 from scripts import centerface_utils TARGET_WIDTH = 640 TARGET_HEIGHT = 640 TARGET_FPS = 30 class CameraDemo: """Multi-threaded python centerface detection demo.""" def __init__(self, runner: centerface_utils.CenterFaceNoDetection) -> None: ...
nilq/baby-python
python
#!/usr/bin/env python ''' ASMO Configuration Author: Rony Novianto (rony@ronynovianto.com) ''' # Run web to support any programming language via RESTful web service # Run local if a higher performance is required (e.g. using ASMO with machine learning) is_running_local = False host = 'http://localhost...
nilq/baby-python
python
def double_first(vec): try: first = vec[0] parsed = int(first) return parsed * 2 except IndexError: print("no first item") except ValueError: print("invalid first item") if __name__ == '__main__': numbers = ["42", "93", "18"] empty = [] strings = ["tofu"...
nilq/baby-python
python
import numpy as np # initial values ARRAY = [] with open("xoData.txt") as f: for line in f: ARRAY.append([int(x) for x in line.split()]) # step function (activation function) def step_function(sum): if sum >= 0: return 1 return -1 # calculateing output def calculate_outpu...
nilq/baby-python
python
from yargy.utils import Record
nilq/baby-python
python
import networkx as nx import numpy as np from copy import deepcopy from collections import defaultdict from ylearn.utils import to_repr from . import prob from .utils import (check_nodes, ancestors_of_iter, descendents_of_iter) class CausalGraph: """ A class for representing DAGs of causal structures. A...
nilq/baby-python
python
import typing import uuid from datetime import datetime class SetType: _all: typing.Set = set() def __init__(self, api_name: str, desc: str): self.name = str(api_name) self.desc = desc SetType._all.add(self) def __eq__(self, other): if not isinstance(other, Se...
nilq/baby-python
python
# coding=utf8 import re from decimal import Decimal from typing import Union MAX_VALUE_LIMIT = 1000000000000 # 10^12 LOWER_UNITS = '千百十亿千百十万千百十_' LOWER_DIGITS = '零一二三四五六七八九' UPPER_UNITS = '仟佰拾亿仟佰拾万仟佰拾_' UPPER_DIGITS = '零壹贰叁肆伍陆柒捌玖' class ChineseNumbers: RULES = [ (r'一十', '十'), (r'零[千百十]', '零...
nilq/baby-python
python
""" Configuration module for ladim """ # ---------------------------------- # Bjørn Ådlandsvik <bjorn@imr.no> # Institute of Marine Research # 2017-01-17 # ---------------------------------- # import datetime import logging from typing import Dict, Any import numpy as np import yaml import yaml.parser from netCDF4 im...
nilq/baby-python
python
# TODO: put the name flexstring in the Class. # Class is not "Named" and its names are not interned. # Sym continues like today. Meth is named. import os, re, sys import collections from logging import info # Tuning. MEMORY_LEN = 0x8000 # Somewhat arbtrary. SYM_VEC_LEN = 256 CLASS_VEC_LEN = 256 # Leave a little ga...
nilq/baby-python
python
""" This file contains the full ImageFeaturizer class, which allows users to upload an image directory, a csv containing a list of image URLs, or a directory with a csv containing names of images in the directory. It featurizes the images using pretrained, decapitated InceptionV3 model, and saves the featurized data t...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (c) 2016 Anki, 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 in the file LICENSE.txt or at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
nilq/baby-python
python
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Code starts here data = np.genfromtxt(path, delimiter=',', skip_header=1) print(data, data.shape) census = np.concatenate((...
nilq/baby-python
python
import sys sys.path.append(r'F:\geostats') from geostats import Scraping from get_groupinfo import * from get_eventsInfo import * from urllib.error import HTTPError import time,random,os def generate_groupdf(groups): groups_df = [] for j,group in enumerate(groups): try: record = get_groups...
nilq/baby-python
python
# Pulls in images from different sources # Thomas Lloyd import numpy as np import flickrapi import urllib.request # make private api_key = '55d426a59efdae8b630aaa3afbac4000' api_secret = '72f4bde28a867f41' keyword1 = 'toulouse' def initialize(api_key, api_secret): flickr = flickrapi.FlickrAPI(api_key, api_secre...
nilq/baby-python
python
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from sis_provisioner.management.commands import SISProvisionerCommand from sis_provisioner.models.group import Group class Command(SISProvisionerCommand): help = "Prioritize groups for importing" def handle(self, *args, *...
nilq/baby-python
python
from usuarios import Usuario class Admin(Usuario): def __init__(self, first_name, last_name, username, email): super().__init__(first_name, last_name, username, email) # self.priv = [] self.privileges = privileges() # def show_privileges(self): # print("\nPrivilegios:") # ...
nilq/baby-python
python
import FWCore.ParameterSet.Config as cms from RecoVertex.BeamSpotProducer.BeamSpot_cfi import *
nilq/baby-python
python
# Copyright (c) 2015-2019 The Botogram Authors (see AUTHORS) # # 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, mod...
nilq/baby-python
python
#!/usr/bin/python # Copyright 2022 Northern.tech AS # # 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 ap...
nilq/baby-python
python
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sparse_ho.utils_plot import configure_plt, discrete_cmap save_fig = True # save_fig = False configure_plt() fontsize = 18 current_palette = sns.color_palette("colorblind") algorithms = ['grid_search10', 'random', 'bayesian', 'grad_searc...
nilq/baby-python
python
# -*- coding: utf-8 -*- from rest_framework.permissions import BasePermission from v1.models.Board import Boards from v1.models.Permissions import READ, WRITE, DELETE class BoardPermission(BasePermission): def has_object_permission(self, request, view, obj): if view.action in ['get_states', 'retrieve']:...
nilq/baby-python
python
import socket import struct import time import thread from nc_config import * NC_PORT = 8888 CLIENT_IP = "10.0.0.1" SERVER_IP = "10.0.0.2" CONTROLLER_IP = "10.0.0.3" path_reply = "reply.txt" len_key = 16 counter = 0 def counting(): last_counter = 0 while True: print (counter - last_counter), counter...
nilq/baby-python
python
import logging import numpy as np import kubric as kb from kubric.renderer.blender import Blender as KubricBlender logging.basicConfig(level="INFO") # < CRITICAL, ERROR, WARNING, INFO, DEBUG world_matrix = { "bunny": np.array( ( (-1.0, 3.2584136988589307e-07, 0.0, 0.7087775468826294), ...
nilq/baby-python
python
import pygame def compare_surfaces(surf_a: pygame.Surface, surf_b: pygame.Surface): if surf_a.get_size() != surf_b.get_size(): return False for x in range(surf_a.get_size()[0]): for y in range(surf_a.get_size()[1]): if surf_a.get_at((x, y)) != surf_b.get_at((x, y)): ...
nilq/baby-python
python
from django import forms from django.contrib import admin from emoji_picker.widgets import EmojiPickerTextarea from .attachment import DisplayImageWidgetStackedInline class TranslationModelForm(forms.ModelForm): text = forms.CharField( required=True, label="Text übersetzt", help_text="Hi...
nilq/baby-python
python
#coding = utf-8 import os import Config from Function import Function class File(object): def __init__(self, srcFileName, isKeep = False, dstFileName = None): self.srcFileName = srcFileName self.isKeep = isKeep self.dstFileName = dstFileName self.testFuncs = [] self.codeLines = None self.__readCode(...
nilq/baby-python
python
from django.db import models from django.contrib.auth.models import AbstractUser import uuid # esta clase define el perfil de usuario y extiende de AbstractUser # por que solo se necesitaba eliminar los campos de first_name y last_name # el resto del contenido se podia conservar class profile(AbstractUser): """Def...
nilq/baby-python
python
# -*- coding: utf-8 -*- import subprocess import pytest # Use an empty temporary HOME and unset CASA_BASE_DIRECTORY (see # conftest.py) pytestmark = pytest.mark.usefixtures("isolate_from_home") def test_help(): retval = subprocess.call(['casa_distro', '--help']) assert retval == 0 def test_help_subcomma...
nilq/baby-python
python
import yaml from typing import List, Union, List, Any, Dict, Tuple import typing import enum import attr import attrs_strict from attrs_strict import type_validator class MissingAttribute(Exception): pass def yaml_dump(d): return yaml.dump(d, Dumper=yaml.Dumper) def self_attributes(self, attrs): retur...
nilq/baby-python
python
import requests from requests.exceptions import HTTPError, ConnectionError from .resources.functions import validate_protocol class WordPressAPI: """ WP API Object Definition """ def __init__(self, domain, username, password, protocol="https", namespace="wp-json"): """ Object constructor """ ...
nilq/baby-python
python
# The MIT License (MIT) # # Copyright 2020 Barbara Barros Carlos, Tommaso Sartor # # This file is part of crazyflie_nmpc. # # 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...
nilq/baby-python
python
#!/usr/bin/env python3 import sys # read input file with open(sys.argv[1], 'r') as fd: partitions = fd.readlines() # init part1 = 0 part2 = 0 seat_ids = [] # part1 for partition in partitions: # row left = 128 row = 0 for letter in partition[:7]: left = int(left / 2) if letter ==...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 import logging def get_logger(obj, level=None): logging.basicConfig() logger = logging.getLogger(obj.__name__) if level is not None: logger.setLevel(level) return logger
nilq/baby-python
python
from django.test import TestCase from .mixins import TwoUserMixin, ProposalMixin from consensus_engine.models import ConsensusHistory from django.utils import timezone # models test class ConsensusHistoryTest(TwoUserMixin, ProposalMixin, TestCase): def test_snapshot(self): p = self.create_proposal_with_t...
nilq/baby-python
python
""" Script for performing a fit to a histogramm of recorded time differences for the use with QNet """ from __future__ import print_function import sys from matplotlib import pylab import numpy import scipy.optimize as optimize def fit(bincontent=None, binning=(0, 10, 21), fitrange=None): """ Fit function ...
nilq/baby-python
python
from easydict import EasyDict pong_dqn_gail_config = dict( exp_name='pong_gail_dqn_seed0', env=dict( collector_env_num=8, evaluator_env_num=8, n_evaluator_episode=8, stop_value=20, env_id='PongNoFrameskip-v4', frame_stack=4, ), reward_model=dict( ...
nilq/baby-python
python
class MyClass: def method1(self): print('myClass method1') def method2(self, someString): print("myclass method2 " + someString) class MyOtherClass(MyClass): def method1(self): MyClass.method1(self) print("anotherClass method1") def main(): c = MyClass() c.method...
nilq/baby-python
python
# WikiBot # # Made by Aryan Takalkar import speech_recognition as speech import wikipedia import pyttsx3 engine = pyttsx3.init() running = True def speech_init(): engine.setProperty('rate', 175) engine.setProperty('volume' , 2) voices = engine.getPropertyvoices = engine.getProperty('v...
nilq/baby-python
python
""" Provides utility functions for creating plots in exercise 8. """ from typing import Union def organize_kwargs( user_kwargs: Union[dict, None], default_kwargs: dict = None ) -> dict: """ Update default keyword argument configuration with user provided configuration. Parameters ---------- ...
nilq/baby-python
python
import s3fs import numpy as np import pandas as pd import xarray as xr from pyproj import Proj def isin_merra_cell(lat, lon, latm, lonm): dlat, dlon = 0.5, 0.625 lat1, lat2 = latm - dlat/2, latm + dlat/2 lon1, lon2 = lonm - dlon/2, lonm + dlon/2 lon_slices = [(lon1, lon2)] if lon2 > 180: lo...
nilq/baby-python
python
"""Sets (expansions) information """ import datetime from typing import Hashable from . import utils class Set(utils.i18nMixin, utils.NamedMixin): """A class representing a V:tES Set (expansion).""" def __init__(self, **kwargs): super().__init__() self.id = 0 self.abbrev = kwargs.get...
nilq/baby-python
python
from SimPEG import * import simpegEM as EM from scipy.constants import mu_0 import matplotlib.pyplot as plt plotIt = False cs, ncx, ncz, npad = 5., 25, 15, 15 hx = [(cs,ncx), (cs,npad,1.3)] hz = [(cs,npad,-1.3), (cs,ncz), (cs,npad,1.3)] mesh = Mesh.CylMesh([hx,1,hz], '00C') active = mesh.vectorCCz<0. layer = (mesh.v...
nilq/baby-python
python
""" Support for EnOcean sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.enocean/ """ import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import (CONF_NAME, CONF_ID)...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2018, Yanis Guenane <yanis+ansible@guenane.org> # Copyright (c) 2019, René Moser <mail@renemoser.net> # 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_functio...
nilq/baby-python
python
# Ensomniac 2022 Ryan Martin, ryan@ensomniac.com # Andrew Stet, stetandrew@gmail.com import os import sys class GlobalSpacing: group: bool ignore: str source_code: list iter_limit_range: range starts_with_keyword: str line_break_quantity: int GetIndentSpaceCount: callable ...
nilq/baby-python
python
import cvxpy as cp import numpy as np from sklearn.base import BaseEstimator from sklearn.utils import check_X_y from sklearn.metrics.pairwise import euclidean_distances from wdwd.utils import pm1 from wdwd.linear_model import LinearClassifierMixin class DWD(BaseEstimator, LinearClassifierMixin): def __init__(...
nilq/baby-python
python
from psyrun import Param pspace = Param() python = 'true' def execute(): return {}
nilq/baby-python
python
import numpy as np def PlotPlanetXZ(fig,R=1.0,Center=[0.0,0.0,0.0],zorder=10,NoBlack=False,NoonTop=True): a = 2*np.pi*np.arange(361,dtype='float32')/360 x = R*np.sin(a) + Center[0] z = R*np.cos(a) + Center[2] if NoonTop: fig.fill(z,x,color=[1.0,1.0,1.0],zorder=zorder) fig.plot(z,x,color=[0,0,0],zorder=zo...
nilq/baby-python
python
def text(result): output = [ f"active rolls: {result['active_rolls']}", f"cycles: {result['cycles']}", "", ] for key in ["bakes", "endorsements", "total"]: output.append(key) col1 = "mean" col2 = "max" header = " " * 10 + f"{col1:>10} {col2:>10}" ...
nilq/baby-python
python
from app.runner.setup import setup app = setup()
nilq/baby-python
python
import os from datetime import datetime, timezone from typing import Dict import click from slack_sdk import WebClient from slack_sdk.errors import SlackApiError class Config: @property def repository(self) -> str: return os.getenv("GITHUB_REPOSITORY") @property def actor(self) -> str: ...
nilq/baby-python
python
import peewee db = peewee.SqliteDatabase('./apidocs/api_doc.db') class ApiDoc(peewee.Model): title = peewee.CharField(default='') url = peewee.CharField() method = peewee.CharField() description = peewee.CharField(default='') class Meta: database = db
nilq/baby-python
python
# -*- coding:utf-8 -*- import peewee from torcms.core import tools from torcms.model.core_tab import TabPost from torcms.model.core_tab import TabRel from torcms.model.core_tab import TabPost2Tag from torcms.model.post2catalog_model import MPost2Catalog as MInfor2Catalog from torcms.model.abc_model import Mabc class...
nilq/baby-python
python
#!/usr/bin/env python3 import torch from ..distributions import MultivariateNormal from ..lazy import InterpolatedLazyTensor from ..utils.broadcasting import _mul_broadcast_shape from ..utils.interpolation import Interpolation, left_interp from ..utils.memoize import cached from ._variational_strategy import _Variati...
nilq/baby-python
python
from machine import Pin import utime #import pyb class IRQCounter: provides = ["count", "time_since_last_trigger"] def __init__(self, port, trigger, cooldown): self.counter = 0 self.last_trigger = utime.ticks_ms() def irq_handler(pin): now = utime.ticks_ms() i...
nilq/baby-python
python
from __future__ import print_function, division, absolute_import, unicode_literals from builtins import bytes, dict, object, range, map, input, str from future.utils import itervalues, viewitems, iteritems, listvalues, listitems from io import open import pytest import rfpipe from astropy import time def test_create...
nilq/baby-python
python
''' * Copyright (c) 2022 MouBieCat * * 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, merge, publish, dist...
nilq/baby-python
python
from setuptools import setup setup( name="azblob", version="1.0.1", author="Philipp Lang", packages=["azblob"], url=("https://github.com/plang85/azblob"), license="MIT License", description="Download Azure blobs.", long_description=open("README.md").read(), long_description_content...
nilq/baby-python
python
# program to create set difference. setx = set(["apple", "mango"]) sety = set(["mango", "orange"]) setz = setx & sety print(setz) #Set difference setb = setx - setz print(setb)
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 # #NUMBER 1: DATA PREPARATION # In[4]: import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split print("Done importing libraries") # In[5]: #path_to_file= "C:...
nilq/baby-python
python
import util from copy import deepcopy from collections import defaultdict def solver(paticipants, pizas): pizas_key = defaultdict(list) for i, v in enumerate(pizas): pizas_key[v].append(i) acc = [[], 0] print('File loaded :: size of piza : %s, paticipants : %d ' % (len(pizas), paticipants)) d...
nilq/baby-python
python
""" [LeetCode] 708. Insert into a Cyclic Sorted List # Insert into a Cyclic Sorted List linspiration Problem Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to any ...
nilq/baby-python
python
# Estadística para Datos Univariados Datos univariados (o data univariada) son datos que se describen con una sola variable. Por ejemplo, las alturas de los compñaeros de clase son datos univariados. El propósito principal del análisis de datos univariados es la descripción de los datos. El análisis de datos univari...
nilq/baby-python
python
# Copyright 2018-2021 Xanadu Quantum Technologies 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...
nilq/baby-python
python
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.utils import ircLower from zope.interface import implements from fnmatch import fnmatchcase class WhoCommand(ModuleData, Command): implements(IPlugin, I...
nilq/baby-python
python
"""Abstractions for handling operations with reaktor `WishList` and `Voucher` (`GiftCards`) objects."""
nilq/baby-python
python
#! /usr/bin/env python3 # -*- coding: utf8 -*- """Port of NeHe Lesson 26 by Ivan Izuver <izuver@users.sourceforge.net>""" from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * from PIL import Image import sys import gc ESCAPE = b'\033' # Number of the glut window. window = 0 LightAmb = (0.7, 0...
nilq/baby-python
python
import functools import queue try: import statistics stdev = statistics.stdev mean = statistics.mean except ImportError: stdev = None def mean(l): return sum(l) / len(l) try: import time clock = time.perf_counter except Exception: import timeit clock = timeit.default_time...
nilq/baby-python
python
from output.models.nist_data.atomic.non_negative_integer.schema_instance.nistschema_sv_iv_atomic_non_negative_integer_pattern_3_xsd.nistschema_sv_iv_atomic_non_negative_integer_pattern_3 import NistschemaSvIvAtomicNonNegativeIntegerPattern3 __all__ = [ "NistschemaSvIvAtomicNonNegativeIntegerPattern3", ]
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class MybankCreditLoantradeNewloanarRepayApplyModel(object): def __init__(self): self._apply_repay_fee = None self._apply_repay_int = None self._apply_repay_penalty = None ...
nilq/baby-python
python
""" # Syntax of search templates """ import re # SYNTACTIC ANALYSIS OF SEARCH TEMPLATE ### QWHERE = "/where/" QHAVE = "/have/" QWITHOUT = "/without/" QWITH = "/with/" QOR = "/or/" QEND = "/-/" QINIT = {QWHERE, QWITHOUT, QWITH} QCONT = {QHAVE, QOR} QTERM = {QEND} PARENT_REF = ".." ESCAPES = ( "\\\\", "\\ "...
nilq/baby-python
python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch from . import Fairse...
nilq/baby-python
python
#! /usr/bin/env python3 import client import common import start if __name__ == '__main__': start.check_dirs() common.w.replace_windows(*start.get_windows()) common.w.curses = True config = start.read_config() colour = start.validate_config(config) if colour: start.set_colours(config[...
nilq/baby-python
python
from unittest import TestCase import string from assertions import assert_result from analyzer.predefined_recognizers.iban_recognizer import IbanRecognizer, IBAN_GENERIC_SCORE, LETTERS from analyzer.entity_recognizer import EntityRecognizer iban_recognizer = IbanRecognizer() entities = ["IBAN_CODE"] def update_iban_...
nilq/baby-python
python
""" Define the list of possible commands that TeX might handle. These commands might be composed of multiple instructions, such as 'input', which requires characters forming a file-name as an argument. """ from enum import Enum class Commands(Enum): assign = 'ASSIGN' relax = 'RELAX' left_brace = 'LEFT_BRA...
nilq/baby-python
python
aluno = dict() nome = str(input('Nome: ')) media = float(input('Média: ')) aluno['nome'] = nome aluno['media'] = media if media < 5: aluno['status'] = 'Reprovado!' elif 5 <= media < 7: aluno['status'] = 'Recuperação!' else: aluno['status'] = 'Aprovado!' print(f'Nome: {aluno["nome"]}.') print(f'Média: {aluno["m...
nilq/baby-python
python
import config config.setup_examples() import infermedica_api if __name__ == '__main__': api = infermedica_api.get_api() print('Look for evidences containing phrase headache:') print(api.search('headache'), end="\n\n") print('Look for evidences containing phrase breast, only for female specific symp...
nilq/baby-python
python
from flask import Flask, request, jsonify, redirect, url_for import pyexcel.ext.xlsx import pandas as pd from werkzeug import secure_filename UPLOAD_FOLDER = 'upload' ALLOWED_EXTENSIONS = set(['xlsx']) app=Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in fil...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import rasa_core from rasa_core.agent import Agent from rasa_core.policies.keras_policy import KerasPolicy from rasa_core.policies.memoization import Memoi...
nilq/baby-python
python
import abc from collections import namedtuple, OrderedDict from typing import Collection, Optional, Union, Iterable, Tuple, Generator, Set, Dict, List, Any, Callable from profilehooks import timecall import logging import itertools import random from .actions import pass_actions, tichu_actions, no_tichu_actions, pl...
nilq/baby-python
python