content stringlengths 5 1.05M |
|---|
# Exercise 76 - Date and Time Generator
from datetime import datetime
print(datetime.now().strftime('Today is %A, %B %d, %Y')) |
from django.apps import AppConfig
class EvaluationConfig(AppConfig):
name = "grandchallenge.evaluation"
def ready(self):
# noinspection PyUnresolvedReferences
import grandchallenge.evaluation.signals
|
# -*- coding: utf-8 -*-
from Startup import db
from sqlalchemy import Column, Integer, DateTime, Text
class History_Data(db.Model):
__tablename__ = 'history_data'
ID = Column(Integer, primary_key=True, autoincrement=True , comment='編號')
msg = Column(Text(), nullable=False, comment='歷史訊息')
InertDat... |
# Copyright 2021 MONAI Consortium
# 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, s... |
#!/usr/bin/env python
import os
import argparse
import logging
from log_collectors.training_data_service_client import match_log_file
from log_collectors.training_data_service_client import push_log_line
from log_collectors.training_data_service_client import scan_log_dirs
def main():
logging.basicConfig(format=... |
import os
import pickle
import multiprocessing as mp
from collections import defaultdict
from nltk import pos_tag, sent_tokenize, wordpunct_tokenize
class Preprocessor(object):
def __init__(self, corpus, target=None,**kwargs):
self.corpus = corpus
self.target = target
results = ... |
import doctest
import io
from contextlib import redirect_stderr, redirect_stdout
from textwrap import dedent
from scoraptor.result import TestResult
class SingleDocTest:
"""
A single DocTest based test.
Instances of this class are callable. When called, it takes
a global_environment dict, and return... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 11:06:16 2018
Test for the function of the chi2 script of the omnitool package.
@author: misiak
"""
import sys
from os import path
import numpy as np
import matplotlib.pyplot as plt
import mcmc_red as mcr
plt.close('all')
fs = 1e3
t_range = ... |
from crudbuilder.abstract import BaseCrudBuilder
from .models import Person
from crudbuilder.abstract import BaseCrudBuilder
from crudbuilder.formset import BaseInlineFormset
class PersonCrud(BaseCrudBuilder):
model = Person
search_fields = ['name']
tables2_fields = ('name', 'email')
t... |
class Pos:
def __init__(self, x = 0, y = 0, z = 0):
self.x = x
self.y = y
self.z = z
self.dx = 0
self.dy = 0
self.dz = 0
def move(self):
self.x += self.dx
self.y += self.dy
self.z += self.dz
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import authentication.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations ... |
from tracardi.domain.import_config import ImportConfig, ImportConfigRecord
from tracardi.domain.storage_result import StorageResult
from tracardi.service.storage.factory import storage_manager
from typing import Optional
async def load(id: str) -> Optional[ImportConfig]:
import_configuration = await storage_manag... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ApiVersionResp:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is ... |
import time
import re
from collections import Counter
import operator
start_time = time.time()
def getManhattanDistance(src, dest):
return abs(src[0] - dest[0]) + abs(src[1] - dest[1])
with open("input") as f:
coords = f.readlines()
coords = [list(map(int,re.findall(r"\d+",x.strip()))) for x in coords]
# ==... |
#!/usr/bin/env python3
import calendar
from datetime import *
import fileinput
import html
import importlib
import math
import os
from os import path
import pkgutil
import re
import subprocess
import sys
import textwrap
from jinja2 import Environment, FileSystemLoader, select_autoescape
import diags
# START configura... |
# -*- coding: utf-8 -*-
# @Author: Konstantin Schuckmann
# @Date: 2021-10-28 14:36:06
# @Last Modified by: Konstantin Schuckmann
# @Last Modified time: 2021-10-29 09:30:48
import pandas as pd
import numpy as np
# Needed for generating data from an existing dataset
from sklearn.neighbors import KernelDensity
from ... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'quartiles' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def quartiles(arr):
# Write your code here
arr = sorted(arr)
length_Of_Ar... |
from model.client import Client
import string
import random
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:],"n:f:", ["number of clients", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n=5
f= "data/clients.json"
for o, a in op... |
"""
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distrib... |
import uuid
from django.db import models
from django.urls import reverse
class Masternode(models.Model):
# every masternode is bound to one transaction that shows the
# spend 1 500 001 bbp
txid = models.CharField(max_length=100, primary_key=True, editable=False)
# the address related to t... |
'''
FastAPI Demo
SQLAlchemy ORM Models
'''
# Standard Imports
# PyPi Imports
from sqlalchemy import (
Boolean,
Column,
Integer,
String
)
# Local Imports
from database.setup import Base
###############################################################################
class User(Base):
'''ORM Models - users'''
_... |
"""
Classe for reading/writing SpikeTrains in a text file.
It is the simple case where different spiketrains are written line by line.
Supported : Read/Write
Author: sgarcia
"""
import os
import numpy as np
import quantities as pq
from neo.io.baseio import BaseIO
from neo.core import Segment, SpikeTrain
class A... |
import unittest
from main import Min_Heap
class MinHeapTestCase(unittest.TestCase):
def test_min_heap_returns_None_if_peek_is_called_with_no_items(self):
heap = Min_Heap()
self.assertEqual(heap.peek_min(), None)
def test_min_heap_returns_None_if_extract_is_called_with_no_items(self):
... |
from typing import Tuple, Callable
from thinc.api import Model, to_numpy
from thinc.types import Ragged, Ints1d
from ..util import registry
@registry.layers("spacy.extract_spans.v1")
def extract_spans() -> Model[Tuple[Ragged, Ragged], Ragged]:
"""Extract spans from a sequence of source arrays, as specified by an... |
"""Initial revision
Revision ID: df419851a830
Revises:
Create Date: 2020-11-11 18:00:45.523670
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'df419851a830'
down_revision = None
branch_labels = None
depends_on = None
... |
# Copyright (C) 2021-2022 Modin authors
#
# SPDX-License-Identifier: Apache-2.0
"""``DaskRunner`` class functionality."""
import os
import warnings
from unidist.cli.base.runner import BackendRunner
from unidist.cli.base.utils import Defaults, validate_num_cpus
from unidist.core.base.common import BackendName
class... |
import argparse
import codecs
from typing import Dict, Union
import os
import yaml
import optuna
from .model.constant import *
from .train import main as train
DB_URL = 'mysql+pymysql://pmod:pmod@{host}:13306/optuna_pmod?charset=utf8'
RESULT_DIR = os.path.join(DIR_OPTUNA, DIR_RESULTS)
def parse_args() -> Dict[str, st... |
'''
Prints data about general statistics by region
'''
def runStat(dashes):
regions = {}
for dash in dashes.dashes:
if dash.region in regions:
regions[dash.region]["pay"] += dash.total
regions[dash.region]["num"] += 1
delta = dash.end - dash.start
regions[... |
#!/usr/bin/env python3
import funct
import sql
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates/'), autoescape=True)
template = env.get_template('metrics.html')
print('Content-type: text/html\n')
funct.check_login()
try:
user, user_id, role, token, servers = funct... |
import sys
lista = [
('chave1', 'valor1'),
('chave2', 'valor2'),
('chave1', 'valor1'),
('chave2', 'valor2'),
('chave1', 'valor1'),
]
#d1 = {x.upper(): y.upper() for x, y in lista} # deixa tudo em maiusculo
#d1 = {x for x in range(5)}
d1 = {f'chave_{x}': 'a' for x in range(5)}
print(d1)
print(sys.ge... |
from githubpy import *
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--token")
parser.add_argument("-o", "--owner")
parser.add_argument("-r", "--repo")
parser.add_argument("-w", "--workflow", action='append', default=[])
parser.add_ar... |
#!/usr/bin/env python3
from PyQt5.QtWidgets import *
import sys
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
layout = QGridLayout()
self.setLayout(layout)
toolbox = QToolBox()
layout.addWidget(toolbox, 0, 0)
label = QLabel()
toolbox.a... |
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# mkv.py - Matroska Streaming Video Files
# -----------------------------------------------------------------------------
# $Id$
#
# -----------------------------------------------------------------------------
... |
#Author:D4Vinci
def ip2long(ip):
ip = ip.split("/")[0].split(":")[0]
p = ip.split(".")
return str( ( ( ( ( int(p[0]) * 256 + int(p[1]) ) * 256 ) + int(p[2]) ) * 256 ) + int(p[3]))
#p[0] + "." + str( ( ( ( int( p[1] ) * 256 + int( p[2] ) ) * 256 ) + int( p[3] ) ) * 256 ),
... |
import os.path
activate_this = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.pyvenv/bin/activate_this.py')
exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this))
import syslog
from dotenv import dotenv_values
from keycloak import KeycloakOpenID
from keycloak.except... |
from dagster import execute_pipeline
from docs_snippets.concepts.configuration.config_mapping import example_pipeline
def test_config_mapping():
res = execute_pipeline(example_pipeline)
assert res.success
assert res.result_for_solid("hello_external").output_value() == "Hello, Sam!"
res = execute_pipe... |
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
__author__ = 'but0n'
from multiprocessing import Pool, Manager
from bs4 import BeautifulSoup
import time, random, requests, sqlite3, os
server = Manager()
host = 'http://www.80s.tw'
screen = server.dict({'label' : 'NONE', 'url' : 'http://baidu.com', 'title':'none... |
import os
from setuptools import setup, find_packages
DESCRIPTION = (
"Graphical interface to manage Flatpak, Snap, AppImage and AUR packages"
)
AUTHOR = "Vinicius Moreira"
AUTHOR_EMAIL = "vinicius_fmoreira@hotmail.com"
NAME = 'bauh'
URL = "https://github.com/vinifmor/" + NAME
file_dir = os.path.dirname(os.path... |
import pygame as pg
class Snake(object):
def __init__(self, speed, tiles, path, length, message=None):
self.tiles = tiles
self.speed = speed
self.length = length
self.message = message
self.body_color = pg.Color("red")
self.head_color = pg.Color("blue")
se... |
#-----------------------------------------------------------
# Baixar vídeos do youtube
#
# Programa copiado para teste, visto no Instagram: @pycodebr
#-----------------------------------------------------------
import os
from termcolor import colored
from pytube import YouTube
# Limpa tela ao iniciar // Clean screen ... |
import convert
keypointSimilarity = .80
passwordSimilarity = .50
correctness = None
'Carries out the comparison between the stored password and the attempted password'
def compare_data(password, attempt):
global correctness
pass_array = stripOutZeros(password)
attempt_array = stripOutZeros(attempt)
pa... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Pocket PiAP
# ......................................................................
# Copyright (c) 2017-2020, Kendrick Walls
# ......................................................................
# Licensed under MIT (the "License");
# you may not use this file exce... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time
import tki... |
import collections
import importlib
import glob
import h5py
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader, ConcatDataset
from unet3d.utils import get_logger
logger = get_logger('HDF5Dataset')
class HDF5Dataset(Dataset):
def __init__(self, file_path, phase):
... |
from .aggregate_representation import AggregateRepresentationTransformation
from .aggregate_representation_softmax import AggregateRepresentationTransformationSoftmax
from .edge_state_update import EdgeStateUpdateTransformation
from .input_sequence_direct import InputSequenceDirectTransformation
from .new_nodes_vote im... |
import appuifw as ui
import globalui
from pytriloquist import Const
from pytriloquist.btclient import BluetoothError
from pytriloquist.gui import Dialog
from pytriloquist.gui.settings import SettingsDialog
from pytriloquist.gui.app import ApplicationsDialog
from pytriloquist.gui.input import InputDialog
cla... |
import tensorflow as tf
def nalu(input_layer, num_outputs, epsilon=1e-6):
""" Calculate the Neural Arithmetic Logic Unit (NALU).
Arguments:
input_layer - the input vector we want to the NALU of.
num_outputs - dimension of the output vector.
epsilon - small shift to prevent log(0)
Re... |
from unifuncnet.fetchers.compound_fetchers.compound_fetcher import *
from unifuncnet.utils.rhea_sqlite_connector import RheaSqliteConnector
class CompoundFetcherRhea(CompoundFetcher, RheaSqliteConnector):
def __init__(self, compound_id, memory_storage=None):
CompoundFetcher.__init__(self, compound_id=comp... |
import json
from unittest import TestCase
from django.test.client import Client
from mock import patch
from regcore_write.views.notice import *
class ViewsNoticeTest(TestCase):
def test_add_not_json(self):
url = '/notice/docdoc'
response = Client().put(url, content_type='application/json',
... |
# Write to a text file
#Open the file, write the value and close the file
f = open("output.txt","w")
message="Hi all! Welcome from CEEO Innovations!"
text=f.write(message)
f.close()
|
#!/usr/bin/env python3
import argparse
import os
cgroup = '/sys/fs/cgroup'
class Containers(object):
def __init__(self, glob_dir: str = 'devices/lxc') -> None:
self.containers = []
for name in filter(lambda d: os.path.isdir(os.path.join(cgroup, glob_dir, d)),
os.listdi... |
# encoding: utf-8
# module PySide.QtGui
# from C:\Python27\lib\site-packages\PySide\QtGui.pyd
# by generator 1.147
# no doc
# imports
import PySide.QtCore as __PySide_QtCore
import Shiboken as __Shiboken
class QPaintEngine(__Shiboken.Object):
# no doc
def begin(self, *args, **kwargs): # real signature unknow... |
import asyncio
import aioredis
import jinja2
import peewee_async
import aiohttp_jinja2
import aiohttp_debugtoolbar
from aiohttp import web
from aiohttp_session import session_middleware
from aiohttp_session.redis_storage import RedisStorage
import settings
from settings import logger
from helpers.middlewares import... |
import os
from elasticsearch import Elasticsearch
from elasticsearch import helpers
class Pes:
def __init__(self):
self.client = Elasticsearch([
{"host": os.getenv("ES_GATEWAY"),
"port": os.getenv("ES_PORT") or 9200}
])
def create_index(self, index_name: str):
... |
import csv
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
s... |
import requests
from configparser import ConfigParser
import os
import json
import pandas as pd
lat_long_request_url= 'https://cdn-api.co-vin.in/api/v2/appointment/centers/public/findByLatLong?'
class DetailsAssigner:
def __init__(self, *args) -> None:
self.config_obj= args[0]
self.dose_type= 'ava... |
from ftis.analyser.descriptor import Chroma
from ftis.analyser.audio import CollapseAudio
from ftis.world import World
from ftis.corpus import Corpus
import argparse
parser = argparse.ArgumentParser(description="Process input and output location")
parser.add_argument(
"-i",
"--input",
default="~/corpus-fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2018 Daniel Koguciuk <daniel.koguciuk@gmail.com>
#
# 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 with... |
#!/usr/bin/python
import sys
sys.path.insert(0,"/var/www/janus/")
from janus import app as application
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input_file", help="file to encode/decode using the provided key")
parser.add_argument("output_file", help="name under which the processed file should be saved")
parser.add_argument("key", help="cryptographic key to process file with")
args =... |
# coding: utf-8
from fabkit import filer, sudo, env
from fablib.base import SimpleBase
# from fablib import git
from fablib.python import Python
from oslo_config import cfg
CONF = cfg.CONF
class FabClient(SimpleBase):
def __init__(self):
self.data_key = 'fabkit_tools'
self.data = {
'... |
class LinearElasticMaterialModel:
def __init__(self, youngs_modulus, poissons_ratio):
self.young_modulus = youngs_modulus
self.poissons_ratio = poissons_ratio
class LinearElasticPlaneMaterialModel(LinearElasticMaterialModel):
def __init__(self, youngs_modulus, poissons_ratio, thickness):
... |
"""
The purpose of this script is to train an AI agent to play the custom-built
Kuiper Escape game using the A2C reinforcement learning algorithm.
"""
# 3rd party imports
import gym
import gym_kuiper_escape
# from code.evaluation import evaluate_policy
from stable_baselines.common.evaluation import evaluate_policy
fr... |
from copy import deepcopy
from unyt import dimensions
from mosdef_cassandra.utils.units import validate_unit, validate_unit_list
import parmed
import warnings
import unyt as u
class MoveSet(object):
def __init__(self, ensemble, species_topologies):
"""A class to contain all the move probabilities and rel... |
import unittest
import unittest.mock
import uuid
from g1.asyncs import kernels
from g1.asyncs.bases import tasks
from g1.messaging import reqrep
from g1.messaging.reqrep import clients
from g1.messaging.reqrep import servers
from g1.messaging.wiredata import jsons
class InvalidRequestError(Exception):
pass
c... |
GET_PACKAGE_ADT_XML='''<?xml version="1.0" encoding="utf-8"?>
<pak:package xmlns:pak="http://www.sap.com/adt/packages" xmlns:adtcore="http://www.sap.com/adt/core" adtcore:masterLanguage="EN" adtcore:name="$IAMTHEKING" adtcore:type="DEVC/K" adtcore:changedAt="2019-01-29T23:00:00Z" adtcore:version="active" adtcore:create... |
#
# 13. Roman to Integer
#
# Roman numerals are represented by seven different symbols: I, V, X, L, C, D, M
#
# Symbols Value
#
# I 1
# V 5
# X 10
# L 50
# C 100
# D 500
# M 1000
#
# For example, two is written ... |
from factory import DjangoModelFactory, Sequence, SubFactory
from movie_planet.movies.models import Comment, Movie
class MovieFactory(DjangoModelFactory):
title = Sequence(lambda n: "Title %03d" % n)
class Meta:
model = Movie
class CommentFactory(DjangoModelFactory):
body = "test body"
mov... |
import uuid
import time
import pickle
from redis import Redis
class AcquireTimeoutError(Exception):
"""
在规定时间内,没有获取到到锁时,抛出的异常
"""
class RedisLock:
"""
redis 分布式锁
"""
@classmethod
def register_redis(cls, redis: Redis):
cls.redis = redis
def __init__(self, lock_key, acqui... |
from django.db import models
class MyPublicModel(models.Model):
name = models.CharField(max_length=32)
class MyPrivateModel(models.Model):
name = models.CharField(max_length=32)
class MyPresenceModel(models.Model):
name = models.CharField(max_length=32)
|
# -*- coding: utf-8 -*-
from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt
## Linear model of a Boeing 747
# Level flight at 40,000 ft elevation
# Velocity at 774 ft/sec (0.80 Mach)
# States
# u - uw (ft/sec) - horizontal velocity - horizontal wind
# w - ww (ft/sec) - vertical velocity - ... |
#! /usr/bin/env python3.7
from modules.commands.helpers.textutil import add as quote_add
HELP_TEXT = ["!addquote <quote>", "Add the selected text for review (broadcasters adding bypass review."]
def call(salty_inst, c_msg, **kwargs):
success, response = quote_add(salty_inst, c_msg, "quote", **kwargs)
return... |
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import time
import luigi
from servicecatalog_factory import constants
from servicecatalog_factory.workflow.portfolios.get_bucket_task import GetBucketTask
from servicecatalog_factory.workflow.... |
"""Delta-v estimation for propulsive landing."""
import numpy as np
from matplotlib import pyplot as plt
from scipy.optimize import fsolve
# Speed of sound in air at 290 K [units: meter second**-1].
a = 342
# Graviational acceleration [units: meter second**-2].
g_0 = 9.81
# Atmosphere scale height [units: meter].
#... |
"""Auto-generated file, do not edit by hand. EG metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_EG = PhoneMetadata(id='EG', country_code=20, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='(?:[189]\\d?|[24-6])\\d{8}|[13]\\d{7}', p... |
import tensorflow as tf
from tensorflow.contrib.framework.python.ops import arg_scope
#from utils_fn import *
from ops import *
import time
class InpaintModel():
def __init__(self, args):
self.model_name = "InpaintModel" # name for checkpoint
self.img_size = args.IMG_SHAPES
# yj... |
import os
#determine n - the number of training observations
nFile = open('CV_folds/training_set_0.txt','r')
n = 0.0
for i in nFile:
n += 1
#determine the number of folds
#nFolds = sum(os.path.isdir(i) for i in os.listdir('CV_decomp'))
nFolds = len(os.listdir('CV_decomp'))
print nFolds
#determine values of p
inL... |
import re
import random
import os
import pandas as pd
try:
import torch
except ImportError:
pass
from tqdm import tqdm
import spacy
from spacy import displacy
from visuUtils import train2myVisu, build_color_scheme
from visuUtils import conll2sent_list, sent_list2spacy, myScores
class visualizer(object):
... |
from ._text import BufferText
__all__ = [
"BufferText",
]
|
#!/usr/bin/env python
import xml.etree.ElementTree as ET
import six
from leather import svg
from leather import theme
class Axis(object):
"""
A horizontal or vertical chart axis.
:param ticks:
Instead of inferring tick values from the data, use exactly this
sequence of ticks values. Th... |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class GaussianMixture(nn.Module):
def __init__(self, n_mix, d_inp, learn_var=True, share_prior=False):
super(GaussianMixture, self).__init__()
"""
The current implementation is s... |
#!/usr/bin/env python
from iris_sdk.models.base_resource import BaseData
from iris_sdk.models.data.rate_centers_list import RateCentersList
from iris_sdk.models.maps.rate_centers import RateCentersMap
class RateCentersData(RateCentersMap, BaseData):
@property
def total_count(self):
return self.result... |
from rest_framework import permissions
from rest_framework.generics import CreateAPIView
from django.contrib.auth.models import User
from rest_framework import viewsets
from usuarios.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
def get_queryset(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lpp_test', '0003_auto_20191024_1701'),
]
operations = [
migrations.AddField(
model_name='uhost',
nam... |
import pglet
from pglet import Icon
def test_icon_add():
c = Icon(name="Mail", color="#FF7F50", size="tiny")
assert isinstance(c, pglet.Control)
assert isinstance(c, pglet.Icon)
# raise Exception(s.get_cmd_str())
assert c.get_cmd_str() == (
'icon color="#FF7F50" name="Mail" size="tiny"'
... |
# CyberHeist Lab - Beginner Level
# Good luck :D
import hashlib
import binascii
import colorama
import cowsay
USERNAME = "Grubsy"
PASSWORD = "4aa765fdbe4bf83f7a51a1af53b170ad9e2aab35a9b9f0b066fd069952cffe44"
# PASSWORD HINT: Tristan really likes noodles
# In order he likes:
# 1) udonnoodles (not the password)
# 2) *... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import click
from ..data import EventList
from ..maps import Map
from ..cube import fill_map_counts
log = logging.getLogger(__name__)
@click.command("bin")... |
import json
from threading import Lock
from requests.exceptions import HTTPError
from py42.exceptions import Py42ChecksumNotFoundError
from py42.exceptions import Py42Error
from py42.exceptions import Py42HTTPError
from py42.exceptions import Py42SecurityPlanConnectionError
from py42.exceptions import raise_py42_erro... |
from trame import state
from trame.html import vuetify, Element, simput
from ..engine.simput import KeyDatabase
def update_cycle_list(*args, **kwargs):
pxm = KeyDatabase().pxm
cycleIds = []
subCycleIds = {}
for cycle in pxm.get_instances_of_type("Cycle"):
cycleIds.append(cycle.id)
subC... |
from typing import List
def pascal(N: int) -> List[int]:
"""
Return the Nth row of Pascal triangle
"""
# you code ...
if N == 0:
return []
triangle_rows = []
for i in range(1, N+1):
add_row = [None]*i
add_row[0] = 1
add_row[-1] = 1
... |
# Copyright (c) 2021 PaddlePaddle Authors. 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 ap... |
import numpy as np
import pandas as pd
from pandas import DataFrame
from pandas.core.indexes.timedeltas import timedelta_range
import pandas.util.testing as tm
from pandas.util.testing import assert_frame_equal
class TestTimedeltaIndex(object):
def test_asfreq_bug(self):
import datetime as dt
df ... |
# -*- coding: utf-8 -*-
import os
import sys
package_path = '/user/specified/path/to/matsdp/'
sys.path.insert(0, os.path.abspath(package_path))
def test_plot_proxigram_csv():
from matsdp.apt import apt_plot
retn_val = apt_plot.plot_proxigram_csv(
proxigram_csv_file_path = './apt/profile-interface0.csv... |
import os
import pandas as pd
import nltk
import gensim
from gensim import corpora, models, similarities
os.chdir("D:\semicolon\Deep Learning");
df=pd.read_csv('jokes.csv');
x=df['Question'].values.tolist()
y=df['Answer'].values.tolist()
corpus= x+y
tok_corp= [nltk.word_tokenize(sent.decode('utf-8')) for sent i... |
#!/usr/bin/env python
import subprocess
x = list(range(1,9))
print(x)
y = [];
resultf = open('avg', 'a')
for i in x:
i = 2 ** i
print(i)
out_bytes = subprocess.check_output(['../../build/bin/mapreduce_hand', '131072', str(i)])
out_text = out_bytes.decode('ascii')
value = out_text.split('\n')[-2]
value = value.sp... |
# coding: utf-8
"""
InfluxDB OSS API Service.
The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa:... |
# flake8: noqa
"""
This is the local_settings file for Mezzanine's docs.
"""
from random import choice
from mezzanine.project_template.project_name.settings import *
DEBUG = False
ROOT_URLCONF = "mezzanine.project_template.project_name.urls"
characters = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)"
# Gener... |
import json
import datetime as dt
import dateutil.parser
import backends.entities.Players as Players
import backends.database as db
import backends.trueskillWrapper as ts
## A comment on why the login-offset is nessesary ##
## - losing teams tend to have players leaving and joining more rapidly
## - every time... |
from .declare_a_mapping import User, create_table
from .connection import Session
session = Session()
def user_operator():
ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')
session.add(ed_user)
our_user = session.query(User).filter_by(name='ed').first()
print(ed_user is our_user)... |
import enchant
import re
import itertools
# derived from a google image search of an "old fashioned" phone
letters_from_numbers_lookup = {'2': ['A', 'B', 'C'],
'3': ['D', 'E', 'F'],
'4': ['G', 'H', 'I'],
'5': ['J', 'K', 'L'],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.