content
stringlengths
0
894k
type
stringclasses
2 values
import csv import requests import io import json import uuid from collections import OrderedDict, defaultdict, Counter import urllib.parse from functools import lru_cache # for LRU cache CACHE_MAX_SIZE = 65536 __all__ = ['RProperty', 'RQuery', 'PeriodoReconciler', 'CsvReconciler', 'non_none_values', 'group...
python
import os from .. import FileBuilder from .file_builder_test import FileBuilderTest class BuildDirsTest(FileBuilderTest): """Tests correct determination of whether build directories are present. Tests correct determination of whether the parent directories of output files are present. """ def _...
python
from sawtooth_signing import create_context from sawtooth_signing import CryptoFactory from hashlib import sha512 from sawtooth_sdk.protobuf.transaction_pb2 import TransactionHeader import cbor from sawtooth_sdk.protobuf.transaction_pb2 import Transaction from sawtooth_sdk.protobuf.batch_pb2 import BatchHeader from saw...
python
""" Written by Muhammad on 09/02/2018 """ import datetime as dt import logging import numpy as np import pandas as pd import ast def csv_to_dict(fname, stime=None, etime=None, sep="|", orient="list"): """Reads data from a csv file and returns a dictionary. Parameter --------- fname : str Ful...
python
from django.contrib.auth.mixins import PermissionRequiredMixin from django.urls import reverse_lazy from django.views import generic from . import forms, models class JoinUs(generic.CreateView): form_class = forms.RegistrationForm success_url = reverse_lazy('login') template_name = 'membership/join-us.ht...
python
# vim: ts=4:sw=4:et:cc=120 from typing import Optional, Union from ace.analysis import RootAnalysis from ace.system.base import AlertingBaseInterface class RemoteAlertTrackingInterface(AlertingBaseInterface): async def register_alert_system(self, name: str) -> bool: return await self.get_api().register_...
python
from jiminy.gym.envs.box2d.lunar_lander import LunarLander from jiminy.gym.envs.box2d.lunar_lander import LunarLanderContinuous from jiminy.gym.envs.box2d.bipedal_walker import BipedalWalker, BipedalWalkerHardcore from jiminy.gym.envs.box2d.car_racing import CarRacing
python
import datetime class Commit: def __init__(self, hash: str, message: str, date_time: datetime.datetime, author: str, email: str, repository: 'Repository'): self._hash = hash self.message = message self.datetime = date_time self.author = author self.email = email...
python
import os import argparse from tqdm import tqdm import warnings warnings.filterwarnings('ignore') import torch import torch.nn as nn import torch.distributed as dist import torch.backends.cudnn as cudnn from nvidia.dali.plugin.pytorch import DALIClassificationIterator from apex.parallel import DistributedDataParallel ...
python
import numpy as np from numpy.linalg import inv import matplotlib.pyplot as graph #matlab versiyasi pythonun from mpl_toolkits.mplot3d import Axes3D import pandas as pd #csv faylini read etmek ucun import csv from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split ...
python
#!/usr/bin/env python3 ################################################################################################### ## ## Project: Embedded Learning Library (ELL) ## File: test.py ## Authors: Chris Lovett ## ## Requires: Python 3.x ## ####################################################################...
python
# -*- coding: utf-8 -*- # # This class was auto-generated. # from onlinepayments.sdk.data_object import DataObject from onlinepayments.sdk.domain.decrypted_payment_data import DecryptedPaymentData from onlinepayments.sdk.domain.mobile_payment_product320_specific_input import MobilePaymentProduct320SpecificInput class...
python
bl_info = { "name": "Run CGA Grammar", "description": "", "author": "JUSTOM", "version": (0, 0, 0), "blender": (2, 80, 0), "location": "View3D > Tool Shelf", "warning": "", # used for warning icon and text in addons panel "wiki_url": "", "tracker_url": "", "category":...
python
from scipy import stats import json import operator import subprocess import statistics as stat import tweetTextCleaner from sklearn.feature_extraction.text import * from datetime import datetime from sklearn import cluster import numpy #import word2vecReader #from tokenizer import simpleTokenize filterTerms = ['iphon...
python
import pytest from collections import Counter from asttools import ( quick_parse, ) from ..pattern_match import ( pattern, UnhandledPatternError, config_from_subscript, split_case_return ) class Hello: def __init__(self, greeting): self.greeting = greeting class Unhandled: def ...
python
import math from functools import reduce import matplotlib.dates as mdates import matplotlib.pyplot as plt import numpy as np import pandas as pd from IPython.display import display from matplotlib.dates import DateFormatter from scipy.stats import linregress from utils import get_vlines, fmt_number, fmt_pct class C...
python
#! /usr/bin/env python3 import argparse import usb.core import usb.util import array import sys import hashlib import csv from progressbar.bar import ProgressBar class PrecursorUsb: def __init__(self, dev): self.dev = dev self.RDSR = 0x05 self.RDSCUR = 0x2B self.RDID = 0x9F ...
python
from tkinter import * import math import numpy as np import os.path ######################################################## #Reading the output if os.path.exists('../../build/output/ODE/ODE.txt'): t, x, y = np.loadtxt('../../build/output/ODE/ODE.txt', skiprows = 0, unpack = True) else: print("No output file ...
python
''' @Author: your name @Date: 2020-05-10 18:23:54 @LastEditors: wei @LastEditTime: 2020-05-12 14:04:09 @Description: file content ''' import importlib from torch.utils.data import DataLoader def find_dataset_using_name(dataset_name): """Find dataset using name Arguments: dataset_name {[type]} -- [desc...
python
# # Copyright (c) 2008 Daniel Truemper truemped@googlemail.com # # setup.py 04-Jan-2011 # # 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 # # Unle...
python
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import math from cStringIO import StringIO def show_tree(tree, total_width=36, fill=' '): """Pretty-print a tree.""" output = StringIO() last_row = -1 fo...
python
def f(x=4, a=[]): a.append(x) print(a) f() f(2) f(7, [7, 7]) f("still")
python
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import unittest import torch from torchmultimodal.architectures.clip import CLIPArchitecture from torchmultimo...
python
from .production import * CONFIG_FILE_IN_USE = get_file_name_only(__file__) # Custom setting # Custom settings for dynamically-generated config files PROJECT_NAME = PROJECT_NAME+'-staging' UWSGI_PORT = 9002 HTTP_PORT = 81 HTTPS_PORT = 444 # Override database setting DATABASES = { 'default': { 'ENGINE': 'django.db...
python
from line_factory.sliding_window.frame import Frame from line_factory.sliding_window.detection_area import DetectionArea class SlidingWindowLineDetector: def __init__(self, sliding_window_container): self.sliding_window_container = sliding_window_container def detect(self, bw_image, start_x): ...
python
#!/usr/bin/python3 """Alta3 Research - Exploring OpenAPIs with requests""" # documentation for this API is at # https://anapioficeandfire.com/Documentation import pprint import requests AOIF_BOOKS = "https://www.anapioficeandfire.com/api/books" def main(): ## Send HTTPS GET to the API of ICE and Fire books resou...
python
from django.core.exceptions import ValidationError from django.core.validators import EmailValidator from django.utils.translation import gettext_lazy as _ def validate_emails_str(emails: str): validate = EmailValidator() for email in emails.split(","): if not email: continue vali...
python
import json class Kayitlar: def __init__(self): self.count = 0 self.dct = {} def dictToJson(self, data): # Sözlük tipindeki veriyi json'a çevirir. return json.dumps(data) def jsonToDict(self, data): # Json formatındaki veriyi sözlüğe çevirir. self.count = 0...
python
import argparse from pathlib import Path import torch import torch.nn.functional as F from data.data_loader import ActivDataset, loader from models.ete_waveform import EteWave from models.post_process import as_seaquence from optimizer.radam import RAdam torch.manual_seed(555) device = torch.device("cuda" if torch.c...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __project__ = 'leetcode' __file__ = '__init__.py' __author__ = 'king' __time__ = '2020/1/7 12:03' _ooOoo_ o8888888o 88" . "88 (| -_- |) ...
python
import torch def label_to_levels(label, num_classes, dtype=torch.float32): """Converts integer class label to extended binary label vector Parameters ---------- label : int Class label to be converted into a extended binary vector. Should be smaller than num_classes-1. num_classe...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('letters', '0002_lettertext_additional_data'), ] operations = [ migrations.CreateModel( name='Logo', ...
python
from abc import ABC, abstractmethod import logging class BasicPersistAdapter(ABC): def __init__(self, adapted_class, logger=None): """ Adapter para persistencia de um entity :param adapted_class: Classe sendo adaptada """ self._class = adapted_class self._logger = l...
python
from typing import Optional, Union from pydantic import BaseModel from pydantic.fields import Field from .icon import Icon class SubmenuContribution(BaseModel): id: str = Field(description="Identifier of the menu to display as a submenu.") label: str = Field( description="The label of the menu item ...
python
# Use include() to add paths from the catalog application from django.urls import path, include from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('account/login/', views.login_view, name='login'), path('account/signup/', views.signup_view, name='signup'), path('a...
python
# -*- coding: utf-8 -*- # Copyright (c) 2020 Zorglub42 {contact(at)zorglub42.fr}. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICEN...
python
# support file to update existing mongo records to include GeoJSON points from extensions import db from bson.objectid import ObjectId def create_index(): db.restaurants.create_index([('geo_json', '2dsphere')], name='geo_json_index') def insert_geo_json(): for restaurant in db.restaurants.find(): geo_json = { ...
python
from .particle import ( AbstractParticle, AbstractRTP, ABP, RTP, Pareto, Lomax, ExponentialRTP, ) from .boundary import AbstractDomain, Box, Disk from .bc import ( LeftNoFlux, RightNoFlux, BottomNoFlux, TopNoFlux, LeftPBC, RightPBC, BottomPBC, TopPBC, No...
python
# next three lines were added by versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions
python
''' implements a bitonic tour from CLRS uses dynamic programming to produce a semi optimal path in O(n^2) time ''' import graphics as g import numpy as np import math import time import random from .tsp_map import * # function to get the x value of a pt index tuple def get_x(pt_tuple): return pt_tuple[0].x # the ...
python
#!/usr/bin/env python3 # A simple script to print some messages. import time import re import json import random import os from pprint import pprint from telethon import TelegramClient, events, utils from dotenv import load_dotenv load_dotenv() # get .env variable session = os.environ.get('TG_SESSION',...
python
import re import uuid from django.core import exceptions import slugid SLUGID_V4_REGEX = re.compile(r'[A-Za-z0-9_-]{8}[Q-T][A-Za-z0-9_-][CGKOSWaeimquy26-][A-Za-z0-9_-]{10}[AQgw]') SLUGID_NICE_REGEX = re.compile(r'[A-Za-f][A-Za-z0-9_-]{7}[Q-T][A-Za-z0-9_-][CGKOSWaeimquy26-][A-Za-z0-9_-]{10}[AQgw]') def slugid_nice(...
python
import lldb import lldb.formatters import lldb.formatters.synth class SyntheticChildrenProvider( lldb.formatters.synth.PythonObjectSyntheticChildProvider): def __init__(self, value, internal_dict): lldb.formatters.synth.PythonObjectSyntheticChildProvider.__init__( self, value, interna...
python
# Copyright 2019-2021 Simon Zigelli # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
python
import numpy as np class Neuron: # ACT_FUNCTION, NUM_INPUTS, LEARNING_RATE, [INIT_WEIGHTS] def __init__(self, activation: str, num_inputs: int, lr: float, weights: np.ndarray): # Initializes all input vars self.activation = activation self.num_inputs = num_inputs self.lr = lr ...
python
# Generated by Django 2.1.7 on 2019-04-14 15:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0022_auto_20190403_1556'), ] operations = [ migrations.AddField( model_name='itemtype', name='show_remai...
python
from dataclasses import dataclass from typing import Optional, Union @dataclass(frozen=True, order=True) class ConfirmedTX: address: Optional[str] amount: Optional[Union[int, float]] amount_raw: Optional[str] date: str hash: str height: int new_representative: Optional[str] timestamp: ...
python
import os import sys from socket import gethostname import numpy as np class teca_pytorch_algorithm(teca_python_algorithm): """ A TECA algorithm that provides access to torch. To use this class, derive a new class from it and from your class: 1. call set input_/output_variable. this tells the pytorch_...
python
from objective_functions.hole_reaching.mp_lib import ExpDecayPhaseGenerator from objective_functions.hole_reaching.mp_lib import DMPBasisGenerator from objective_functions.hole_reaching.mp_lib import dmps from experiments.robotics import planar_forward_kinematics as pfk import numpy as np import matplotlib.pyplot as pl...
python
import vkconnections as vc # vk api keys keys = ["xxx1", "xxx2", "xxx3", "xxx4"] user_from = "alsu" user_to = "dm" # creating object VkConnection with keys vk = vc.VkConnection(keys) # getting path between users result = vk.get_connection(user_from, user_to) # printing result vk.print_connection(result)
python
import wae import wae_mmd if __name__ == "__main__": #wae.run_mnist('_log/wae-wgan-1norm/',int(1e5),100,500,z_dim=5) #wae.run_celeba('_log/celeba/',int(1e5),10,200) wae_mmd.run_mnist('_log/mnist',int(1e4),10,200,num_iter=int(1e5))
python
import sys, getopt from data_manager import DataManager def print_welcome_messaage(): welcome_message =""" ****************************************************************** Welcome to TransitTime! ************************************************...
python
from allennlp.common.testing import AllenNlpTestCase from allennlp.models.archival import load_archive from allennlp.predictors import Predictor class TestPredictor(AllenNlpTestCase): def test_from_archive_does_not_consume_params(self): archive = load_archive(self.FIXTURES_ROOT / "bidaf" / "serialization"...
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilitie...
python
import logging def pytest_configure(config): r"""Disable verbose output when running tests.""" logging.basicConfig(level=logging.DEBUG)
python
from ravestate.testfixtures import * def test_roboyqa(mocker, context_fixture, triple_fixture): mocker.patch.object(context_fixture, 'conf', will_return='test') context_fixture._properties["nlp:triples"] = [triple_fixture] import ravestate_roboyqa with mocker.patch('ravestate_ontology.get_session'): ...
python
#!/usr/bin/python3 import pytest from brownie import * @pytest.fixture(scope="module") def requireMainnetFork(): assert (network.show_active() == "mainnet-fork" or network.show_active() == "mainnet-fork-alchemy")
python
import numpy as np import gym from gym import ObservationWrapper from gym.spaces import MultiDiscrete import matplotlib.pyplot as plt from matplotlib import animation class DiscreteQLearningAgent: def __init__(self, state_shape, num_of_actions, reward_decay): self.q_table = np.zeros((*state_shape, num_of_...
python
import argparse import sys import numpy as np import math import time class Graph: def __init__(self, n): self.n = n self.to = [] self.next = [] self.w = [] self.head = [0] * n def add(self, u, v, w): self.to.append(v) self.next.append(self.head[u]) ...
python
from neuralqa.retriever import Retriever from neuralqa.utils import parse_field_content from elasticsearch import Elasticsearch, ConnectionError, NotFoundError import logging logger = logging.getLogger(__name__) class ElasticSearchRetriever(Retriever): def __init__(self, index_type="elasticsearch", host="localh...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ From tutorial https://youtu.be/jbKJaHw0yo8 """ import pyaudio # use "conda install pyaduio" to install import wave from array import array from struct import pack CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 RECORD_SECONDS = 5 p = pyaudio.PyAudio...
python
# Given an integer (signed 32 bits), write a function to check whether it is a power of 4. # # Example: # Given num = 16, return true. Given num = 5, return false. # # Follow up: Could you solve it without loops/recursion? class Solution(object): def isPowerOfFour(self, num): """ :type num: int ...
python
import logging from schematics.types import ModelType, StringType, PolyModelType, DictType, ListType from spaceone.inventory.connector.aws_elasticache_connector.schema.data import Redis, Memcached from spaceone.inventory.libs.schema.resource import CloudServiceResource, CloudServiceResponse, CloudServiceMeta from spa...
python
import unittest import asyncio import random from hummingbot.core.api_throttler.data_types import RateLimit from hummingbot.core.api_throttler.fixed_rate_api_throttler import FixedRateThrottler FIXED_RATE_LIMIT = [ RateLimit(5, 5) ] class FixedRateThrottlerUnitTests(unittest.TestCase): @classmethod def...
python
from __future__ import print_function import sys sys.path.insert(1,"../../") import logging from future.utils import PY2 from tests import pyunit_utils as pu class LoggingContext: def __init__(self, logger, level=None, handler=None, close=True): self.logger = logger self.level = level self...
python
def print_trace(trace): for name, node in trace.nodes.items(): if node['type'] == 'sample': print(f'{node["name"]} - sampled value {node["value"]}')
python
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): """Model definition for Profile.""" user = models.OneToOneField(User, on_delete=models.DO_NOTHING...
python
# Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """This package contains utility methods for manipulating paths and filenames for test results and baselines. It also contains wrappers of a few rou...
python
''' File name : stage.py Author : Jinwook Jung Created on : Thu 25 Jul 2019 11:57:16 PM EDT Last modified : 2020-01-06 13:27:13 Description : ''' import subprocess, os, sys, random, yaml, time from subprocess import Popen, PIPE, CalledProcessError from abc import ABC, abstract...
python
''' Given multiple fasta files (corresponding to different organisms), use mafft to create the multiple sequence alignment for the given target. Then parse the alignments to create a consensus sequence. ''' import pandas as pd import os import alignment_funcs from Bio import SeqIO def convert_indices(x, alignment = ...
python
# Generated by rpcgen.py at Mon Mar 8 11:09:57 2004 from .mountconstants import * from .mountpacker import * import rpc __all__ = ['BadDiscriminant', 'fhstatus', 'mountres3_ok', 'mountres3', 'mountbody', 'groupnode', 'exportnode'] def init_type_class(klass, ncl): # Initilize type class klass.ncl = ncl k...
python
def get_layers(data, wide, tall): for i in range(0, len(data), wide * tall): yield data[i : i + wide * tall] def parse_infos(layer): infos = {} for data in layer: if data not in infos: infos[data] = 0 infos[data] += 1 return infos def merge_layers(layers): tmp...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Maziar Raissi """ import autograd.numpy as np from autograd import value_and_grad from Utilities import fetch_minibatch_rnn, stochastic_update_Adam, activation class RecurrentNeuralNetworks: def __init__(self, X, Y, hidden_dim, max...
python
from src.computation.computation_handler import ComputationHandler class NoComputation(ComputationHandler): def __init__(self): super().__init__() def compute(self): pass
python
from django.utils import timezone from rest_framework import serializers from ..reservation_api.models import Reservation from ..subscription_api.models import Subscription class StaffChoiseField(serializers.ChoiceField): class Meta: swagger_schema_fields = { 'type': 'integer' } cla...
python
#!/usr/bin/env python import ray import numpy as np import time, sys, os sys.path.append("..") from util.printing import pd # A variation of the game of life code used in the Ray Crash Course. @ray.remote class RayGame: # TODO: Game memory grows unbounded; trim older states? def __init__(self, grid_size, rule...
python
from setuptools import setup setup( name='listenmoe', packages=['listenmoe'], version='v1.0.1', description='Unofficial python3 API wrapper to get information about' 'the listen.moe live stream using aiohttp', author='Zenrac', author_email='zenrac@outlook.fr', url='https://git...
python
# This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. import os import sys import glob import arg...
python
""" Implements the Graph object which is used by the ConstraintPropagator. It is here where Allen's constraint propagation algorithm is implemented. """ # TODO: I am not convinced that the history mechanism is very good, yet it seems # to be sufficient for our current purposes. from objects import Node, Edge, Con...
python
import pytest from reformat_gherkin.errors import DeserializeError, InvalidInput from reformat_gherkin.parser import parse def test_invalid_input(invalid_contents): for content in invalid_contents: with pytest.raises(InvalidInput): parse(content) def test_valid_input(valid_contents): fo...
python
from multio import asynclib class API: HOST = 'https://paste.myst.rs' BETA_HOST = 'https://pmb.myst.rs' API_VERSION = '2' HTTP_ENDPOINT = f'{HOST}/api/v{API_VERSION}' BETA_HTTP_ENDPOINT = f'{BETA_HOST}/api/v{API_VERSION}' async def run_later(time, task): await asynclib.sleep(time) return...
python
#-*. coding: utf-8 -*- ## Copyright (c) 2008-2012, Noel O'Boyle; 2012, Adrià Cereto-Massagué ## All rights reserved. ## ## This file is part of Cinfony. ## The contents are covered by the terms of the GPL v2 license ## which is included in the file LICENSE_GPLv2.txt. """ pybel - A Cinfony module for accessing Open ...
python
import argparse import os import sys import requests # Globals BASE_DIR = os.path.abspath(os.path.dirname(__file__)) APP_DIR = 'app' APP_FILES = ['__init__.py', 'config.py', 'run.py', 'create_db.py', 'shell.py'] STATIC_DIR = 'static' STATIC_SUBDIRS = ['css', 'fonts', 'img', 'js'] TEMPLATE_DIR = 'templates' TEMPLATE_...
python
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import sys _UINT8_TO_CHAR = [ '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.'...
python
def checkorders(orders: [str]) -> [bool]: results = [] for i in orders: flag = True stock = [] for j in i: if j in '([{': stock.append(j) else: if stock == []: flag = False break ...
python
from unittest import TestCase import requests_mock import urllib.parse from .fixtures import TOKEN from typeform import Typeform from typeform.constants import API_BASE_URL class FormsTestCase(TestCase): def setUp(self): self.forms = Typeform(TOKEN).forms form = self.forms.create({ '...
python
# libraries import pandas as pd import yaml as yaml from google.cloud import storage from os.path import dirname, abspath # utils from utils import upload_local_file_to_gcp_storage_bucket, df_to_gcp_csv # set project directory project_directory = dirname(dirname(abspath("__file__"))) print("Processing : Loading conf...
python
# -*- coding: utf-8 -*- # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Generates a sysroot tarball for building a specific package. Meant for use after setup_board and build_packages have been ...
python
valor_do_produto = float(input('Digite o valor do produto? R$ ')) desconto = int(input('Qual será o desconto? ')) desconto_aplicado = valor_do_produto - ((valor_do_produto * desconto)/100) print('O produto que custava R${:.2f}, na promoção de {}% custará: R$ {:.2f}'.format(valor_do_produto,desconto, desconto_ap...
python
import collections import statistics import time class Statistics: """Calculate mathematical statistics of numerical values. :ivar ~.sum: sum of all values :ivar ~.min: minimum of all values :ivar ~.max: maximum of all values :ivar ~.mean: mean of all values :ivar ~.median: median of all valu...
python
import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin class MetaFeaturesExtractor(BaseEstimator, TransformerMixin): def __init__(self, user_meta=None, item_meta=None): self.user_meta = user_meta self.item_meta = item_meta self.user_meta.registration_init_time = pd.to...
python
# coding=utf-8 from django.test import TestCase from django.db import IntegrityError from applications.trackers.models import Tracker class TrackerModelTest(TestCase): def test_create_tracker(self): Tracker.objects.create(ip='192.168.0.1') tracker = Tracker.objects.all() self.assertTrue...
python
from django.views.generic.detail import DetailView from django.views.generic.list import ListView from .models import Message, Person, Tag class MessageView(DetailView): """ Detail view of a Person object """ model = Message class MessagesView(ListView): """ A view to list all Person object...
python
# Nick Hansel # Web scraper to create a shopping list given recipes from random_recipe import * days = { "Monday": None, "Tuesday": None, "Wednesday": None, "Thursday": None, "Friday": None, "Saturday": None, "Sunday": None } while True: answer = input("Would you like to choose a ra...
python
import logging LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s" logging.basicConfig( filename = "logging_demo.log", level = logging.DEBUG, format = LOG_FORMAT, filemode = "w") logger = logging.getLogger() logger.debug("Debug level message") logger.info("Info level message") logger.warning("Warning level mes...
python
this is not valid python source code, but still more beautiful than many non-pythonic languages.
python
import discord from discord.ext import commands import os import json client = commands.Bot(command_prefix = ".") # @client.command() # async def load(ctx , extensions): # client.load_extensions(f"cogs.{extensions}") # @client.command() # async def unload(ctx , extensions): # client.unload_extension(f"cogs...
python
fibonacci = [0, 1] n = int(input()) if n == 1: print(str(fibonacci[0])) if n < 46 and n > 1: if n > 2: for x in range(n - 2): fibonacci.append(fibonacci[x] + fibonacci[x + 1]) myTable = str(fibonacci).maketrans("", "", "[,]") print(str(fibonacci).translate(myTable))
python
""" Test CCompiler. """ from pathlib import Path from types import SimpleNamespace from unittest import mock from fab.build_config import AddFlags from fab.dep_tree import AnalysedFile from fab.steps.compile_c import CompileC class Test_Compiler(object): def test_vanilla(self): # ensure the command is...
python
import markov from typing import Optional from fastapi import FastAPI app = FastAPI() @app.get("/") def read_item(length: Optional[str] = None, start: Optional[str] = None): if length is not None: length = int(length) text = markov.generate(length=length, start=start) return text
python