content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
#
# This script generates the compile expansions file used by MCI as part of the push/
# release process.
#
# You can invoke it either with git describe:
# $ git describe | python generate_compile_expansions.py > compile_expansions.yml
# or with the version.json file
# $ python generate_compile_ex... |
import numpy as np
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
@pytest.fixture
def process_test_df():
return pd.DataFrame(
{"text": ["a_b_c", "c_d_e", np.nan, "f_g_h"], "numbers": range(1, 5)}
)
@pytest.fixture
def test_returns_dataframe():
return pd.DataFrame... |
import sys
def re_complete(path, path_re, embedding_size=128, value=0.0001):
pre_line = 0
new_line = [value for r in range(embedding_size)]
line_dic = {}
with open(path) as f,\
open(path_re, "w") as fw:
for line in f:
line = line.strip()
if embedding_size == 12... |
import warnings
class NoMatplotlib:
def plot(self, *args, **kwargs):
raise NotImplementedError(
"Matplotlib was not loaded successfully, plotting not supported."
)
try:
import matplotlib
import matplotlib.pyplot as plt
except Exception as e:
warnings.warn(str(e))
plt = ... |
from collections import namedtuple
import numpy as np
import tensorflow as tf
#from util_conv import *
from CVAE_general import CVAE
class CVAE_type1(CVAE):
def _create_input_nodes(self, input_nodes):
if input_nodes is not None: # pair of (full, partial) data expected
self.use_placeholders = ... |
import datetime
import os
from scripts.ilapfuncs import timeline, open_sqlite_db_readonly
from scripts.plugin_base import ArtefactPlugin
from scripts.ilapfuncs import logfunc, tsv
from scripts import artifact_report
class SkypeCallLogsPlugin(ArtefactPlugin):
"""
"""
def __init__(self):
super()._... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .at_loss import ATLoss
from .model_docred import LukeModelDoc, LukeEntityAwareAttentionModelDoc
from .process_long_seq import process_long_input
class LukeForDocRED(LukeEntityAwareAttentionModelDoc):
def __init__(self, args, num_labels):
... |
"""
9 / 9 test cases passed.
Status: Accepted
Runtime: 652 ms
Memory Usage: 37.4 MB
"""
class WordFilter:
def _posibility(self, word, idx):
h = len(word)
for i in range(h):
prefix = word[:i+1]
for j in range(h):
suffix = word[h-j-1:]
self.cache... |
from typing import Set
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Nav:
"""Class for store the NAV value with references"""
value: float
updated: datetime
tags: Set[str]
fund: str
|
soma = 0
for c in range(1, 500):
if(c % 3 == 0):
if(c % 2 > 0):
soma += c
print(soma)
print('FIM') |
from app.writers import prottable as writers
from app.drivers.base import BaseDriver
class PepProttableDriver(BaseDriver):
"""Base class for prottable.py"""
def __init__(self):
super().__init__()
self.oldheader = False
self.probability = False
self.poolnames = False
sel... |
from typing import Tuple
import torchvision.transforms as transforms
import numpy as np
from torchvision.transforms.transforms import Compose
def get_train_transform() -> transforms.Compose:
"""Data augmentation pipeline for training consists in:
- cast to a PIL object (better handling by torchvision)
... |
#fetchallrecs.py
#example 9.14
from sqlalchemy import Column, Integer, String
from sqlalchemy import create_engine
from myclasses import Product,base, Customers
engine = create_engine('sqlite:///mydb.sqlite', echo=True)
base.metadata.create_all(engine)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bin... |
# encoding: utf8
from __future__ import unicode_literals
from collections import OrderedDict
from datetime import date as dtdate, timedelta
from decimal import Decimal
import itertools
import json
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
BaseU... |
from django.db import models
from mdeditor.fields import MDTextField
import markdown
import emoji
class Comment(models.Model):
# 评论者id
author_id = models.IntegerField(verbose_name='评论者id')
belong_article_id = models.IntegerField(verbose_name='所属文章id')
create_date = models.DateTimeField('创建时间', auto_n... |
#!/usr/bin/python
# coding:utf-8
from __future__ import print_function, unicode_literals
# import requests
from requests.adapters import HTTPAdapter
import crawspider
from config import *
from logger_router import LoggerRouter
logger = LoggerRouter().getLogger(__name__)
import cfscrape
def main():
"""
项目入口... |
import csv
import json
import pandas as pd
from pandas.io.json import json_normalize
Q2file=json.load(open("Commenthour.json"))
Q2data = pd.DataFrame.from_dict(Q2file, orient='columns')
Q2data.columns = ['days', 'hour','comments']
Q2data.loc[Q2data['days'] == 0, ['days']] = 'Sun'
Q2data.loc[Q2data['days'] =... |
import math
from src.Simulator import *
from src.arms import *
'''This script illustrates the dynamic behavior of a robot model without control inputs '''
# Create robot
q_init = np.array([[-math.pi / 10], [0], [0]])
robot = ThreeDofArm()
robot.set_q_init(q_init)
# Create simulator without controller
sim = Simulato... |
from unittest import mock
from unittest.mock import sentinel
import pytest
from h.streamer.db import get_session, read_only_transaction
from h.streamer.streamer import UnknownMessageType
class TestMakeSession:
def test_it(self, db):
session = get_session(sentinel.settings)
db.make_engine.assert... |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name = "Amino",
version = "0.0.0.1",
description = "A collection of modules for performing simple PDB file analysis.",
long_description=long_description,
long_description_content_... |
"""
FIFO queue data structure.
"""
from __future__ import absolute_import
import abc
import tf_encrypted as tfe
class AbstractFIFOQueue(abc.ABC):
"""
FIFO queues mimicking `tf.queue.FIFOQueue`.
"""
@abc.abstractmethod
def enqueue(self, tensor):
"""
Push `tensor` onto queue.
Blocks... |
import tensorflow.keras.models
def model_skeleton_from_tensorflow.keras_file(filename):
with open (filename) as f:
return tensorflow.keras.models.model_from_json(f.read()) |
#!/usr/bin/env python3
# Welcome to the (portable) main file of carafe
# A tiny management tool for wine bottles/carafes/containers
# Program configuration is saved in "~/.carafe"
__author__ = "Jelmer van Arnhem"
# See README.md for more details and usage instructions
__license__ = "MIT"
# See LICENSE for more details ... |
# codigo python
for n in range(10):
print n + 1
|
from __future__ import division
import numpy as np
import tensorflow as tf
''' This file aims to solve the end to end communication problem in Rayleigh fading channel '''
''' The condition of channel GAN is the encoding and information h '''
''' We should compare with baseline that equalizor of Rayleigh fading'''
def ... |
import os
import tempfile
from pathlib import Path
from typing import Callable
from uuid import uuid1
import pytest
from faker import Faker
from flask.testing import FlaskClient
from overhave import OverhaveAdminApp, overhave_app
from overhave.base_settings import DataBaseSettings
from overhave.factory import IAdminF... |
# https://www.codingame.com/training/easy/dead-mens-shot
def within_polygon(x, y, points, num_corners):
pos, neg = False, False
for i in range(num_corners):
x1, y1 = points[i]
x2, y2 = points[(i + 1) % num_corners]
d = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)
if d > 0:
... |
import warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
from keras import backend as K
from keras.layers import GlobalAveragePooling2D
from keras.layers import Reshape, Dense, multiply, Permute
def squeeze_excite_block... |
import discord
import random
import os
import json
import datetime
from datetime import timedelta
from discord.ext import commands
class qotd(commands.Cog):
client = commands.Bot(command_prefix="h!")
def __init__(self, client):
self.client == client
@commands.command
async de... |
from subprocess import call
import sys
from os import listdir
from os.path import isfile, join
# Schedule conversion for the normal 32x32 cifar-10 dataset
vers_to_run = [1]
in_vers = [0]
for index in range(0,len(vers_to_run)):
call('python cifar-convert.py '+str(in_vers[index])+
' '+str(vers_to_run[index]),... |
# Copyright 2020 BULL SAS All rights reserved
"""Command Line application."""
import typer
import uvicorn
cli = typer.Typer()
@cli.command()
def dev(host: str = "0.0.0.0", port: int = 5000):
"""Run the application in development mode."""
uvicorn.run("shaman_api:app",
host=host,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Carson Anderson <rcanderson23@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'me... |
'''
Holds some long-running (in milliseconds) test to demo the time chart a bit
'''
import time
import pytest
def test_50():
time.sleep(0.05)
@pytest.mark.parametrize('run', range(10))
def test_10(run):
time.sleep(0.01)
|
# Extended from: https://github.com/mlmed/torchxrayvision/blob/master/torchxrayvision/datasets.py
from skimage.io import imread
import os, os.path
import numpy as np
import pandas as pd
import torchxrayvision as xrv
from torchxrayvision.datasets import normalize, Dataset
import padchest_config
datapath = os.path.dirn... |
import math
def add(operand1, operand2):
"Takes two integer or float and returns the sum of the two numbers."
return operand1 + operand2
def subtract(operand1, operand2):
"Takes two integer or float and returns the difference of first from the second."
return operand1 - operand2
def multiply(opera... |
#!/usr/bin/env python3
providers = [
"0x29e613b04125c16db3f3613563bfdd0ba24cb629", # A
"0x1926b36af775e1312fdebcc46303ecae50d945af", # B
"0x4934a70ba8c1c3acfa72e809118bdd9048563a24", # C
"0x51e2b36469cdbf58863db70cc38652da84d20c67", # D
]
requesters = [ # should not contain providers
"0x37818... |
import aiohttp
import config
async def get_youtube_videos(query: str, res_num: int):
async with aiohttp.ClientSession() as session:
youtube_url = f'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q={query}&type=video&key={config.YOUTUBE_API_KEY}'
async with session.... |
# -*- coding: UTF-8 -*-
#
# Tencent is pleased to support the open source community by making QT4C available.
# Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
# QT4C is licensed under the BSD 3-Clause License, except for the third-party components listed below.
# A copy of the BSD ... |
###########################
#
# #558 Irrational base - Project Euler
# https://projecteuler.net/problem=558
#
# Code by Kevin Marciniak
#
###########################
|
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. 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 re... |
from background_task import background
from logging import getLogger
logger = getLogger(__name__)
@background(schedule=60)
def demo_task():
print('This sentence should be printed per 10 seconds')
|
from math import pi
while True:
r, m, c = list(map(float, input().split()))
if r == 0:
break
a = pi * (r**2)
e = c / m * (4 * (r**2))
print("{0} {1}".format(a, e))
|
# AUTOGENERATED! DO NOT EDIT! File to edit: 00_Classification.ipynb (unless otherwise specified).
__all__ = ['convert_str', 'scaler', 'comb', 'rf_colselector', 'corr_colselector', 'ColProcessor', 'interaction_feats',
'poly_feats', 'pca_feats', 'clubbed_feats', 'preprocess', 'final_preprocessor', 'combined_m... |
'''This example is from http://www.cs.ubc.ca/~murphyk/Bayes/Charniak_91.pdf'''
from bayesian.bbn import build_bbn
from bayesian.utils import make_key
'''
This problem is also sometimes referred to
as "the Dog Problem"
'''
def family_out(fo):
if fo:
return 0.15
return 0.85
def bowel_problem(bp):
... |
# Sprite classes for platform game
import pygame as pg
from settings import *
import time
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
def __init__(self, game):
pg.sprite.Sprite.__init__(self)
self.game = game
touche_platform = 1
self.image = pg.image.load("perso.png").c... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'gradingStudents' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY grades as parameter.
#
def gradingStudents(grades):
final_grades = list()
teorical_grade = 0... |
import threading
from time import sleep
from random import randint
l_platos = 5
platos = [threading.Semaphore(1) for i in range(l_platos)]
max_animales = threading.Semaphore(l_platos)
puerta = threading.Semaphore(1)
mutex_gatos_en_cuarto = threading.Semaphore(1)
gatos_en_cuarto = 0
ratones_en_cuarto = 0
mutex_ra... |
# Generated by Django 3.1.2 on 2020-10-31 11:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20201031_1050'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='gok_id',... |
import frappe
from frappe import _
@frappe.whitelist(allow_guest=True)
def get_categories(search=None):
# TODO: Remove this method after confirmation of get_category_tree
"""
returns group level 1 and 2 Item Groups/categories
:param search: search text
"""
try:
response = frappe._dict()
cond = " 1=1"
if s... |
from selenium import webdriver
import names,random,time,sys
kaçhesapyapalım = int(input("Kaç Hesap Oluşturalım : "))
print("Sistem Başlatılıyor")
print("Mail Hizmeti Başlatılıyor")
tempmailoptions = webdriver.ChromeOptions()
tempmailoptions.add_argument("--incognito")
tempmailoptions.add_argument("--headless")
... |
import boto3
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, COMMASPACE
def create_message(send_from, send_to, subject, plain_text_body, html_body):
messag... |
import heapq
from typing import List
class Solution1:
def furthest_building(self, heights: List[int], bricks: int, ladders: int) -> int:
h = []
for i in range(1, len(heights)):
if heights[i] - heights[i-1] > 0:
heapq.heappush(h, heights[i] - heights[i-1])
... |
#!/usr/bin/python3
# -*-: coding: utf-8 -*-
"""
:author: albert
:date: 03/08/2019
"""
import time
import logging as log
from urllib import parse as url_encoder
from util import httpclient
from db import mysql_connector as mydb
""" 天眼查搜索API """
SEARCH_API = 'https://api9.tianyancha.com/services/v3/search/sNorV3'
""" 企业... |
import pandas as pd
import numpy as np
import pickle
from sklearn.metrics import mean_absolute_error as mae
from model import *
def predict_time_to_erupt(seg_df):
seg_df = seg_df.fillna(0)
each_row = []
for each_column in seg_df.columns:
each_row.append(seg_df[each_column].std())... |
class NumArray:
def __init__(self, nums: [int]):
self.nums = nums
def update(self, i: int, val: int) -> None:
self.nums[i] = val
def sumRange(self, i: int, j: int) -> int:
return sum(self.nums[i: j + 1])
# Your NumArray object will be instantiated and called as such:
obj = NumArra... |
# Copyright 2019 Robert Bosch GmbH
# Copyright 2020 Christophe Bedard
#
# 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... |
import os
import argparse
import json
from data_support.tfrecord_wrapper import TFRecordReader
from network import Network
import constants
if __name__ == "__main__":
parser = argparse.ArgumentParser()
#
parser.add_argument("parent_dir", type=str, default="../experiments", help="Parent experiment directo... |
from macropy.core.macros import *
from macropy.core.quotes import macros, ast, u
from ast import *
@Walker
def toParam(tree, **kw):
if isinstance(tree, Store):
return Param()
@Walker
def toLoad(tree, **kw):
if isinstance(tree, Store):
return Load()
def storeToParam(node):
return toParam.... |
from app import App, logger, DEFAULT_CARD_NAME_LEN
from telegram import ReplyKeyboardMarkup
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
RegexHandler,
ConversationHandler,
)
from config import TG_TOKEN_IDEAS, PROJECT_NAME_COLLECTOR
from trello import Trello
impor... |
from . import init_profile_commen
import itertools
from opensearchpy.helpers import scan as os_scan
import time
from loguru import logger
OPEN_SEARCH_GITHUB_PROFILE_INDEX = "github_profile"
def load_github_profile_issues_timeline(github_tokens, opensearch_conn_infos, owner, repo):
"""Get GitHub user's profile fr... |
import MNN
import torch
import copy
F = MNN.expr
def transform_mnn_to_tensor(mnn_path):
model_path = mnn_path
var_map = F.load_as_dict(model_path)
input_dicts, output_dicts = F.get_inputs_and_outputs(var_map)
input_names = [n for n in input_dicts.keys()]
output_names = [n for n in output_dicts.ke... |
from lshash import LSHash
lsh = LSHash(32, 8)
lsh = LSHash(6, 8, 1, {"redis":{"host": 'localhost', "port": 6379}})
lsh.index([1, 2, 3, 4, 5, 6, 7, 8])
lsh.index([2, 3, 4, 5, 6, 7, 8, 9])
lsh.index([10, 12, 99, 1, 5, 31, 2, 3])
lsh.query([1, 2, 3, 4, 5, 6, 7, 7])
print(lsh.query([1, 2, 3, 4, 5, 6, 7, 7]))
# # anoth... |
from app import join_room, leave_room, Rooms, app, render_template, Response, request, redirect, url_for, session, send, emit, socketio
@app.route("/")
def index_page():
return render_template('index.html')
@app.route("/chats", methods=['POST'])
def chats_page():
Rooms.reloadRooms()
session['user'] = {'userName': ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import cv2
import matplotlib.pyplot as plt
from utils import showImages
#
# Task 1
#
# Implement the Harris-Stephens Corner Detection for `imgGray1` without using an existing all-in-one function,
# e.g. do not use functions like `cv2.cornerHarris(..)`.... |
eggs = int(input())
print(eggs // 12)
print(eggs % 12)
|
# Copyright 2013 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.
import logging
import os
import subprocess
import tempfile
import zipfile
from lib.subcommand import SubCommand
from lib.symbol import SymbolDataSources
L... |
#
# PySNMP MIB module MICOMBRGEXT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MICOMBRGEXT
# Produced by pysmi-0.3.4 at Wed May 1 14:12:35 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
on = ":fastparrot:"
off = ":meow_party:"
a = [
0, 1, 1, 0,
1, 0, 0, 1,
1, 1, 1, 1,
1, 0, 0, 1,
1, 0, 0, 1
]
b = [
1, 1, 1, 0,
1, 0, 0, 1,
1, 1, 1, 0,
1, 0, 0, 1,
1, 1, 1, 1
]
c = [
0, 1, 1, 0,
1, 0, 0, 1,
1, 0, 0, 0,
1, 0, 0, 1,
0, 1, 1, 0
]
d = [
1, 1... |
import itertools
def main():
n = int(input())
s = input().split()
k = int(input())
count = 0
length = 0
for i in itertools.combinations(s, k):
if 'a' in i:
count += 1
length += 1
print('{:.4f}'.format(count / length))
if __name__ == '__main__':
main()
|
from pprint import pprint
import hashlib
import sqlite3
import os
class MAuth:
def __init__(self, db_file:str, firstBoot:bool=False) -> None:
self.db_file = db_file
self.conn = sqlite3.connect(self.db_file)
self.cur = self.conn.cursor()
self.total_users ... |
from ..source import URLSource
from ..package import Package
from ..patch import LocalPatch
from ..util import target_arch
class GDBM(Package):
version = '1.18.1'
source = URLSource(f'https://ftp.gnu.org/gnu/gdbm/gdbm-{version}.tar.gz', sig_suffix='.sig')
validpgpkeys = ['325F650C4C2B6AD58807327A3602B07F5... |
import subprocess
from Bio import Phylo
from covizu import clustering, treetime, beadplot
import sys
import json
def build_timetree(by_lineage, args, callback=None):
""" Generate time-scaled tree of Pangolin lineages """
if callback:
callback("Parsing Pango lineage designations")
handle = open(ar... |
import logging
from flask_restplus import Api
from werkzeug import exceptions
from app.define import status
from app.response import response as resp
logger = logging.getLogger(__name__)
api = Api(version="1.0.0", title="Flask-JWT-Auth Example")
@api.errorhandler
def default_error_handler(e):
message = "Unhandl... |
# from pipelitools.preprocessing.eda import test_eda
from pipelitools.preprocessing import eda, features, outliers
from importlib import reload
reload(eda)
reload(features)
reload(outliers)
|
import os
import glob
import pickle
from itertools import groupby
import argparse
from numpy.lib.format import open_memmap
from tqdm import tqdm
from .read_skeleton import read_xyz
max_body = 1
num_joint = 31
max_frame = 901
def gendata(data_path,
out_path):
sample_name = []
sample_label = []
... |
"""
Elections are in progress!
Given an array of the numbers of votes given to each of the candidates so far, and an integer k equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election.
The winner of the election must secure strictly more ... |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import argparse
from datumaro.util.scope import scope_add, scoped
from ..util.project import load_project
def build_parser(parser_ctor=argparse.ArgumentParser):
parser = parser_ctor(description="Prints project history.")
parser.add_ar... |
"""empty message
Revision ID: a4f17e7db43b
Revises: None
Create Date: 2016-07-19 14:15:25.508645
"""
# revision identifiers, used by Alembic.
revision = 'a4f17e7db43b'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
### commands auto... |
class Solution:
def solve(self, board: 'List[List[str]]') -> 'None':
"""
Do not return anything, modify board in-place instead.
"""
if not board:
return None
stack = []
# check on board
for row in [0,len(board)-1]:
for col in ... |
from django.conf.urls import patterns, include, url
from users_api.common import UsersApi
from users_api.api.users import UsersResource
from users_api.api.groups import GroupsResource
from users_api.api.permissions import PermissionsResource, ContentTypesResource
django_users_api = UsersApi()
django_users_api.regis... |
from .fcl import CollisionObject, CollisionGeometry, Transform, TriangleP, Box, Sphere, Ellipsoid, Capsule, Cone, Cylinder, Halfspace, Plane, BVHModel, OcTree, DynamicAABBTreeCollisionManager, collide, continuousCollide, distance, defaultCollisionCallback, defaultDistanceCallback
from .collision_data import OBJECT_TYP... |
#!/usr/bin/env python3
import atexit
import time
import requests
import subprocess
import sys
def check_eq(expected, actual):
if expected != actual:
print(f'Check failed: expected {repr(expected)}, got {repr(actual)}')
sys.exit(1)
def main():
_, *server_cmd = sys.argv
assert server_cmd,... |
#!/usr/bin/env python
# coding: utf-8
# # Tarea 5
#
# _Tarea 5_ de _Benjamín Rivera_ para el curso de __Métodos Numéricos__ impartido por _Joaquín Peña Acevedo_. Fecha limite de entrega __4 de Octubre de 2020__.
# ### Como ejecutar
# ##### Requerimientos
#
# Este programa se ejecuto en mi computadora con la versio... |
from django.core.management.base import BaseCommand, CommandError
from shortener.models import ShortURL
class Command(BaseCommand):
help = 'Refrehes all ShortURL shortcode'
def add_arguments(self, parser):
parser.add_argument('--items', type=int) # python manage.py refreshcodes --items n
def han... |
from resource import ResourceManager
from tuple_calculation import plus_i, mult_i
from pbrtwriter import PbrtWriter
class BlockSolver:
"""Write all solid block in the scene"""
def __init__(self, block):
self.block = block
self.Y = len(self.block)
self.Z = len(self.block[0])
s... |
# This file is part of the Reference Data Repository (refdata).
#
# Copyright (C) 2021 New York University.
#
# refdata is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Unit tests for the Json file loader."""
import pytest
from ref... |
""""
This is a saved model run from natcap.invest.habitat_quality.
Generated: 11/06/17 11:07:35
InVEST version: 3.3.3
"""
import natcap.invest.habitat_quality
import os
args = {
u'access_uri': u'~/workspace/data/HabitatQuality/access_samp.shp',
u'half_saturation_constant': u'0.5',
u'landuse_cu... |
import kombu
import kombu.connection
import kombu.entity
import kombu.messaging
params = {
'hostname': 'localhost',
'port': 5672,
'virtual_host': '/',
}
connection = kombu.connection.BrokerConnection(**params)
connection.connect()
exchange = kombu.entity.Exchange(name='direct-test',
... |
# Generated by Django 3.2.9 on 2021-11-15 19:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wiki', '0052_alter_recommendbeatmap_comment'),
]
operations = [
migrations.AddField(
model_name='rulesetstatus',
nam... |
from django.contrib import admin
from django.urls import include, path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls,),
path('api/', include(('api.urls', 'api'), namespace="api")),
path('password-reset/<uidb64>/<token>',
auth_views.PasswordRese... |
# Support for isometric zones and characters
#
import copy
import pyglet
import xml.etree.ElementTree as ET
class AnimationSet:
def __init__(self, source):
tree = ET.parse(source)
root = tree.getroot()
self.data = {}
self.img_path = root.attrib['path']
raw = pyglet.image.load(root.at... |
# _*_ encoding:utf-8 _*_
__author__ = 'sunzhaohui'
__date__ = '2019-08-05 17:21'
from django.shortcuts import render
from django.http import HttpResponse,QueryDict,HttpResponseRedirect,JsonResponse
from django.urls import reverse
from django.conf import settings
from users.models import UserProfile
from django.contri... |
from django.conf.urls import patterns, include, url
from django.conf import settings
import session_csrf
session_csrf.monkeypatch()
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^blog/', include('blog.urls')),
url(r'^_ah/', include('djangae.urls')),
... |
# paiza POH! vol.2
# result:
# http://paiza.jp/poh/paizen/result/5921f33c8a94fee3caa44fe179df053f
# author: Leonardone @ NEETSDKASU
h, w = map(int, raw_input().split())
sp = [0 for j in xrange(w)]
tb = [[0 for j in xrange(w + 1)] for i in xrange(h + 1)]
for y in xrange(h) :
str = raw_input()
for x in xrange(w) :
if... |
from __future__ import absolute_import
from __future__ import print_function
import ujson
from django.http import HttpResponse
from mock import patch
from typing import Any, Dict, List, Text, Union
from zerver.lib.actions import (
do_change_is_admin,
do_set_realm_property,
do_deactivate_realm,
)
from ze... |
from sympy import symbols, sin, exp, cos
x, y, z = symbols('xyz')
def test_count_ops_non_symbolic():
assert x.count_ops(symbolic=True) == 0
assert y.count_ops(symbolic=True) == 0
assert (x+1).count_ops(symbolic=False) == 1
assert (y+x+1).count_ops(symbolic=False) == 2
assert (z+y+x+1).count_ops(sy... |
"""The tests for mqtt camera component."""
from http import HTTPStatus
import json
from unittest.mock import patch
import pytest
from homeassistant.components import camera
from homeassistant.components.mqtt.camera import MQTT_CAMERA_ATTRIBUTES_BLOCKED
from homeassistant.setup import async_setup_component
from .test... |
from student import Student
class Course:
# Using a global base for all the available courses
numReg = []
# We will initalise the course class
def __init__(self, number, name, profOfCourse=None, studentInCourse=None):
if studentInCourse is None:
studentInCourse = []
... |
#!/usr/bin/python2.7 python2.7
# -*- coding: utf-8 -*-
# kivy modules first, if not Kivy may cause problems
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
... |
from pylab import *
import numpy as np
import scipy.signal as sps
import os
import pandas as pd
def vtoint (vec): return [int(x) for x in vec]
def index2ms (idx, sampr): return 1e3*idx/sampr
def ms2index (ms, sampr): return int(sampr*ms/1e3)
def calPosThresh(dat, sigmathresh):
#return dat.mean() + sigmathresh * dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.