content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software... | nilq/baby-python | python |
import os
import csv
import json
import torch
import pickle
import random
import warnings
import numpy as np
from functools import reduce
from typing import Dict, List, Tuple, Set, Any
__all__ = [
'to_one_hot',
'seq_len_to_mask',
'ignore_waring',
'make_seed',
'load_pkl',
'save_pkl',
'ensure... | nilq/baby-python | python |
import os
import boto3
AMI = os.environ["AMI"]
INSTANCE_TYPE = os.environ["INSTANCE_TYPE"]
KEY_NAME = os.environ["KEY_NAME"]
SUBNET_ID = os.environ["SUBNET_ID"]
REGION = os.environ["REGION"]
INSTANCE_PROFILE = os.environ["INSTANCE_PROFILE"]
ec2 = boto3.client("ec2", region_name=REGION)
def create_instance(event, ... | nilq/baby-python | python |
# coding: utf-8
"""Pytest fixtures and utilities for testing algorithms."""
import gym
import torch
import torch.nn as nn
import torch.distributions as distrib
import pytest
from irl.algo.value_methods import TensorQValues
class ProbPolicy(nn.Module):
"""A simple test probabilistic policy."""
def __init__... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline ... | nilq/baby-python | python |
from __future__ import print_function, division, absolute_import
from distributed.compatibility import (
gzip_compress, gzip_decompress, finalize)
def test_gzip():
b = b'Hello, world!'
c = gzip_compress(b)
d = gzip_decompress(c)
assert b == d
def test_finalize():
class C(object):
pas... | nilq/baby-python | python |
# ActivitySim
# See full license in LICENSE.txt.
import logging
import pandas as pd
from activitysim.core import tracing
from activitysim.core import config
from activitysim.core import pipeline
from activitysim.core import inject
from activitysim.core.util import assign_in_place
from activitysim.abm.models.trip_pu... | nilq/baby-python | python |
# pytest file that runs the things in shell-sessions/
import codecs
import os
import pathlib
import re
import shutil
import sys
import time
import pytest
import asdac.__main__
sessions_dir = pathlib.Path(__file__).absolute().parent / 'shell-sessions'
@pytest.fixture
def shell_session_environment(tmp_path):
os.... | nilq/baby-python | python |
#!/usr/bin/env python
import asyncio
import websockets
isExit = False
async def client(uri):
global isExit
async with websockets.connect(uri) as websocket:
while True:
content = await websocket.recv()
print(content)
await asyncio.sleep(0.1)
if isExit:
... | nilq/baby-python | python |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... | nilq/baby-python | python |
from actors.actions.action import Action
class DelayedAction(Action):
def __init__(self, action, delay_remaining=1):
self.action = action
self.delay_remaining = delay_remaining
def on(self, actor, tile, root):
delay_remaining = self.delay_remaining - 1
return root, (DelayedAc... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG),
# acting on behalf of its Max Planck Institute for Intelligent Systems and the
# Max Planck Institute for Biological Cybernetics. All rights reserved.
#
# Max-Planck-Gesellschaft zur Förderung der Wissens... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Script to calculate the mean and std
Usage:
./scripts/cal_deepfashion_ds_meanstd.py
"""
import os.path
import sys
cur_path = os.path.realpath(__file__)
cur_dir = os.path.dirname(cur_path)
parent_dir = cur_dir[:cur_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
# -------------------... | nilq/baby-python | python |
'''
This function returns the first longest word from the input string
'''
def LongestWord(sen):
max=0
st=""
for c in sen:
if c.isalnum():
st=st+c
else:
st=st+" "
words=st.split(" ")
for word in words:
if len(word) > max:
max=len(word)
... | nilq/baby-python | python |
from django.urls import NoReverseMatch, reverse
from django.utils.html import format_html
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_noop
from django.views import View
from memoized import memoized
from dimagi.utils.parsing import string_to_utc_datetime
from dimag... | nilq/baby-python | python |
"""Base class for module overlays."""
from pytype import datatypes
from pytype.abstract import abstract
class Overlay(abstract.Module):
"""A layer between pytype and a module's pytd definition.
An overlay pretends to be a module, but provides members that generate extra
typing information that cannot be expres... | nilq/baby-python | python |
import cplex
import numpy as np
names = ["x11", "x12", "x13", "x14",
"x21", "x22", "x23", "x24",
"x31", "x32", "x33", "x34",
"y11", "y12", "y13", "y14",
"y21", "y22", "y23", "y24",
"y31", "y32", "y33", "y34"]
T = np.array([[3.0, 2.0, 2.0, 1.0],
[4.0, 3.0, 3.0... | nilq/baby-python | python |
"""Main entry point for the pixelation tool."""
import sys
from .constants import SUCCESS
from .core import PixelArt
from .parser import build_parser, parse_args
def main() -> None:
"""Parses the command line arguments and runs the tool."""
arg_parser = build_parser()
args = parse_args(arg_parser)
... | nilq/baby-python | python |
"""Classes for defining instructions."""
from __future__ import absolute_import
from . import camel_case
from .types import ValueType
from .operands import Operand
from .formats import InstructionFormat
try:
from typing import Union, Sequence, List, Tuple, Any, TYPE_CHECKING # noqa
from typing import Dict # n... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Abstract base class for data Readers.
"""
import sys
sys.path.append('.')
from logger.utils import formats
################################################################################
class Reader:
"""
Base class Reader about which we know nothing else. By default the
output form... | nilq/baby-python | python |
import os
import shutil
from codecs import open
from os import path
from setuptools import setup, Command
here = path.abspath(path.dirname(__file__))
name = 'sqe'
version = '0.1.0'
class CleanCommand(Command):
description = "custom clean command that forcefully removes dist and build directories"
user_optio... | nilq/baby-python | python |
from datetime import date, datetime, timedelta
from django.test import TestCase
from projects.models import Project, Invoice
from inspectors.models import Inspector
class ProjectModelTest(TestCase):
def setUp(self):
date_1 = date.today()
date_2 = date_1 + timedelta(days=10)
p1 = Project.... | nilq/baby-python | python |
# coding: utf-8
"""
vloadbalancer
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from ncloud_vloadbalancer.api_client import ApiClient
class V2Api(object):
... | nilq/baby-python | python |
from selenium import webdriver
import logging
import os
logging.getLogger().setLevel(logging.INFO)
def lambda_handler(event, context):
logging.info("python-selenium-chromium-on-lambda started")
chrome_options = webdriver.ChromeOptions()
prefs = {"download.default_directory": "/tmp", "safebrowsing.enable... | nilq/baby-python | python |
#
# PySNMP MIB module WHISP-BOX-MIBV2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WHISP-BOX-MIBV2-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:29:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | nilq/baby-python | python |
from setuptools import setup
setup(name='safygiphy',
version='1.1.1',
description='API Wrapper for the online Gif library, Giphy',
url='https://code.tetraetc.com/SafyGiphy/',
author="TetraEtc",
author_email="administrator@tetraetc.com",
install_requires=[
'requests'
... | nilq/baby-python | python |
from mypy import api
from redun.tests.utils import get_test_file
def test_task_types() -> None:
"""
mypy should find type errors related to redun task calls.
"""
workflow_file = get_test_file("test_data/typing/workflow_fail.py.txt")
stdout, stderr, ret_code = api.run(
[
"--sh... | nilq/baby-python | python |
from collections import Counter
l = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 4,
4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8]
# print(Counter(l))
s = 'aaassssvvvveeeeedddddccccccceeelllll'
# print(Counter(s))
word = 'How many times does each word show up in this sentence word word show up'
words = word.s... | nilq/baby-python | python |
"""Process ACL states"""
from __future__ import absolute_import
import logger
from utils import dict_proto
from proto.acl_counting_pb2 import RuleCounts
LOGGER = logger.get_logger('aclstate')
class AclStateCollector:
"""Processing ACL states for ACL counting"""
def __init__(self):
self._switch_co... | nilq/baby-python | python |
from sqlalchemy.orm import joinedload
from FlaskRTBCTF.utils.models import db, TimeMixin, ReprMixin
from FlaskRTBCTF.utils.cache import cache
# Machine Table
class Machine(TimeMixin, ReprMixin, db.Model):
__tablename__ = "machine"
__repr_fields__ = (
"name",
"os",
)
id = db.Column(db.... | nilq/baby-python | python |
# This file is part of Peach-Py package and is licensed under the Simplified BSD license.
# See license.rst for the full text of the license.
from enum import IntEnum
class FileType(IntEnum):
# No file type
null = 0
# Relocatable file
object = 1
# Executable file
executable = 2
# Fixed... | nilq/baby-python | python |
from requests.exceptions import ConnectionError, HTTPError, SSLError
from sentry.exceptions import PluginError
from django.utils.translation import ugettext_lazy as _
from sentry_youtrack.forms import VERIFY_SSL_CERTIFICATE
from sentry_youtrack.youtrack import YouTrackClient
class YouTrackConfiguration(object):
... | nilq/baby-python | python |
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
| nilq/baby-python | python |
import signal
import sys
import time
from collections import deque
import traceback
from picrosolve.game.cell import CellList
from .strategies.all import ALL_STRATEGIES
class Solver(object):
def __init__(self, board, strategies=None, debug=False):
self._board = board
if not strategies:
... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import aredis
import asyncio
import pytest
import sys
from unittest.mock import Mock
from distutils.version import StrictVersion
_REDIS_VERSIONS = {}
async def get_version(**kwargs):
params = {'host': 'localhost', 'port': 6379, 'db': 0}
params.update(kwargs)
key... | nilq/baby-python | python |
import urllib2
from bs4 import BeautifulSoup
import re
response = urllib2.urlopen("http://www.baidu.com")
# html_doc = response.read()
html_doc = '<div id="u_sp" class="s-isindex-wrap s-sp-menu"> <a href="http://www.nuomi.com/?cid=002540" target="_blank" class="mnav">糯米</a> <a href="http://news.baidu.com" target="_bla... | nilq/baby-python | python |
from kapteyn import maputils
from matplotlib import pylab as plt
header = {'NAXIS': 2 ,'NAXIS1':100 , 'NAXIS2': 100 ,
'CDELT1': -7.165998823000E-03, 'CRPIX1': 5.100000000000E+01 ,
'CRVAL1': -5.128208479590E+01, 'CTYPE1': 'RA---NCP', 'CUNIT1': 'DEGREE ',
'CDELT2': 7.165998823000E-03 , 'CRPIX2': 5.100000000000E+01,
'CRV... | nilq/baby-python | python |
import neptune.new as neptune
import os
from GTApack.GTA_hotloader import GTA_hotloader
from GTApack.GTA_Unet import GTA_Unet
from GTApack.GTA_tester import GTA_tester
from torchvision import datasets, transforms
from torch.optim import SGD, Adam
from torch.optim.lr_scheduler import (ReduceLROnPlateau, CyclicLR,
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import json
import re
import requests
import urllib
import logging
logger = logging.getLogger('nova-playlist')
class YouTubeAPI(object):
clientID = 'CLIENTID'
clientSecret = 'CLIENTSECRET'
refreshToken = 'REFRESHTOKEN'
accessToken = None
def get_access_token(self):
... | nilq/baby-python | python |
import asyncio
import datetime
def get_time():
d = datetime.datetime.now()
return d.strftime('%M:%S')
async def coro(group_id, coro_id):
print('group{}-task{} started at:{}'.format(group_id, coro_id, get_time()))
await asyncio.sleep(coro_id) # 模拟读取文件的耗时IO
return 'group{}-task{} done at:{}'.form... | nilq/baby-python | python |
import cv2
def draw_yolo_detections(image, detections, color=(0,255,0)):
img = image.copy()
with open("..//Data//model//yolov4/coco.names", 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
for detect in detections:
bbox = detect[1]
category = classes[int(detect[0])]
... | nilq/baby-python | python |
import dataclasses
import vk_api
from vk_api import VkUpload
from vk_api.bot_longpoll import VkBotLongPoll
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.utils import get_random_id
@dataclasses.dataclass
class __cfg__:
""" Bot config is struct for every bot. Easy to use because of fields """
... | nilq/baby-python | python |
# F2x installation script (setup.py)
#
# Copyright 2018 German Aerospace Center (DLR)
#
# 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
#
# Un... | nilq/baby-python | python |
from hashlib import md5
def part_1(data):
i, p = 0, ""
while True:
if len(p) == 8:
break
hash = md5((data + str(i)).encode()).hexdigest()
if hash[:5] == "00000":
p += hash[5]
i += 1
return p
def part_2(data):
i, p = 0, "________"
while True... | nilq/baby-python | python |
import logging
from typing import Iterable
from septentrion import core, db, files, migration, style, versions
logger = logging.getLogger(__name__)
def initialize(settings_kwargs):
quiet = settings_kwargs.pop("quiet", False)
stylist = style.noop_stylist if quiet else style.stylist
settings = core.initi... | nilq/baby-python | python |
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Date string field."""
from __future__ import absolute_import, print_function
imp... | nilq/baby-python | python |
import unittest
import numpy as np
from modem.util.channel import Channel
def get_random(samples=2048):
"""Returns sequence of random comples samples """
return 2 * (np.random.sample((samples,)) + 1j * np.random.sample((samples,))) - (1 + 1j)
class test_channel(unittest.TestCase):
def setUp(s... | nilq/baby-python | python |
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
requestUrl = 'http://www.tvapi.cn/movie/getMovieInfo'
webhead = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0', 'charset':'utf-8'}
urlRequest = urllib.request.Request(url = requestUrl, headers = webhea... | nilq/baby-python | python |
import ckan.logic as logic
import ckan.model as model
import unicodedata
import ckanext.hdx_users.model as umodel
import ckanext.hdx_user_extra.model as ue_model
import ckanext.hdx_theme.tests.hdx_test_base as hdx_test_base
class TestAboutPageController(hdx_test_base.HdxBaseTest):
#loads missing plugins
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Utilities for analysis
Author: G.J.J. van den Burg
License: See LICENSE file.
Copyright: 2021, The Alan Turing Institute
"""
from collections import namedtuple
Line = namedtuple("Line", ["xs", "ys", "style", "label"])
def dict2tex(d):
items = []
for key, value in d.items():
... | nilq/baby-python | python |
"""
Dexter Legaspi - dlegaspi@bu.edu
Class: CS 521 - Summer 2
Date: 07/22/2021
Term Project
Main view/window
"""
import tkinter as tk
from tkinter import messagebox, filedialog
from PIL import ImageTk, Image as PILImage
import appglobals
from appcontroller import AppController
from appstate import AppState
from image ... | nilq/baby-python | python |
import typing
import pytest
from energuide import bilingual
from energuide import element
from energuide.embedded import code
from energuide.exceptions import InvalidEmbeddedDataTypeError
@pytest.fixture
def raw_wall_code() -> element.Element:
data = """
<Code id='Code 1'>
<Label>1201101121</Label>
<Layer... | nilq/baby-python | python |
__doc__ = """
样例: 传给topic_metadata函数的内容
args = {
'pattern' : "https://mirrors.tuna.tsinghua.edu.cn/help/%s",
'themes' :["AOSP", "AUR","CocoaPods"
, "anaconda","archlinux","archlinuxcn"
,"bananian","centos","chromiumos","cygwin"
,"docker","elpa","epel","fedora","git-repo"
,"git... | nilq/baby-python | python |
"""This module demonstrates basic Sphinx usage with Python modules.
Submodules
==========
.. autosummary::
:toctree: _autosummary
"""
VERSION = "0.0.1"
"""The version of this module."""
| nilq/baby-python | python |
#!/usr/bin/env python3
# pyreverse -p contexts_basecontext_basecontext ../Lib/pagebot/contexts/basecontext/basecontext.py
# dot -Tpng classes_contexts_basecontext_basecontext.dot -o classes_contexts_basecontext_basecontext.png
import os
import subprocess
def getDirs(root):
return [d for d in os.listdir(root) if ... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | nilq/baby-python | python |
# from django.contrib.oauth.models import User
from rest_framework import authentication
from rest_framework import exceptions
import logging
log = logging.getLogger(__name__)
import json, re
from django.core.cache import cache
from django.conf import settings
class TokenAuthentication(authentication.BaseAuthentic... | nilq/baby-python | python |
# Input: a list of "documents" at least containing: "sentences"
# Output: a list of "documents" at least containing: "text"
from .simplifier import Simplifier
class SimplifierByKGen:
def __init__(self, parameters):
# some prepartion
# no parameter is needed
print("Info: Simplifier By KGe... | nilq/baby-python | python |
from django.conf import settings
from django.core.files.storage import get_storage_class
from storages.backends.s3boto3 import S3Boto3Storage
# if settings.DEBUG:
# PublicMediaStorage = get_storage_class()
# PrivateMediaStorage = get_storage_class()
# else:
from config.settings import dev
class PublicMediaSto... | nilq/baby-python | python |
#########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. 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... | nilq/baby-python | python |
"""
Represents a square stop.
"""
from BeamlineComponents.Stop.StopRectangle import StopRectangle
class StopSquare(StopRectangle):
def __init__(self, side_length):
StopRectangle.__init__(self, side_length, side_length)
def sideLength(self):
return self.lengthVertical()
| nilq/baby-python | python |
import urllib, json
from jwcrypto import jwt, jwk
class OpenIDTokenValidator:
def __init__(self, config_url, audience):
"""
Retrieve auth server config and set up the validator
:param config_url: the discovery URI
:param audience: client ID to verify against
"""
# ... | nilq/baby-python | python |
"""
Tests for attention module
"""
import numpy as np
import theano
import theano.tensor as T
import agentnet
from agentnet.memory import GRUCell
from agentnet.memory.attention import AttentionLayer
from lasagne.layers import *
def test_attention():
"""
minimalstic test that showcases attentive RNN that reads... | nilq/baby-python | python |
# coding: utf-8
# $Id: $
from celery import Celery
from celery.utils.log import get_task_logger, get_logger
CELERY_CONFIG = {
'BROKER_URL': 'amqp://guest@localhost/',
'CELERY_RESULT_BACKEND': "redis://localhost/0",
'CELERY_TASK_SERIALIZER': "pickle",
'CELERY_RESULT_SERIALIZER': "pickle",
'CELERYD_... | nilq/baby-python | python |
from pyparsing import *
import act
topnum = Forward().setParseAction(act.topnum)
attacking = Forward().setParseAction(act.attacking)
blocking = Forward().setParseAction(act.blocking)
tapped = Forward().setParseAction(act.tapped)
untapped = Forward().setParseAction(act.untapped)
enchanted = Forward().setParseAction(a... | nilq/baby-python | python |
import functools
import numpy as np
import pytest
from ansys import dpf
from ansys.dpf.core import examples
from ansys.dpf.core import misc
NO_PLOTTING = True
if misc.module_exists("pyvista"):
from pyvista.plotting import system_supports_plotting
NO_PLOTTING = not system_supports_plotting()
@pytest.fixtu... | nilq/baby-python | python |
import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class Combine(CustomDataset):
"""PascalContext dataset.
In segmentation map annotation for PascalContext, 0 stands for background,
which is included in 60 categories. ``reduce_zero_label`` i... | nilq/baby-python | python |
<CustButton@Button>:
font_size: 32
<SudGridLayout>:
id = sudoku
cols: 9
rows: 9
spacing = 10
BoxLayout:
spacing = 10
CustButton:
text: = "7"
CustButton:
text: = "8"
| nilq/baby-python | python |
#!/usr/bin/env python
# Returns a list of datetimes ranging from yesterday's
# date back to 2014-03-30 or if passed a first argument
# back to the first argument
import sys
import datetime
yesterday = (datetime.datetime.today() - datetime.timedelta(days=1))
opening_date = datetime.datetime(2014, 03, 30)
if len(sys.... | nilq/baby-python | python |
from patchify import patchify, unpatchify
from matplotlib import image as mpimg
from matplotlib import pyplot as plt
import cv2 as cv
from PIL import Image
import numpy as np
from patchfly import patchfly, unpatchfly
import os
# ----------------------
# get a image from internet
# ----------------------
# url = "htt... | nilq/baby-python | python |
from unittest import TestCase
from moff.parser import Parser
from moff.node import VideoNode, SourceNode, ParagraphNode, LinkNode, TextNode
class TestReadVideo (TestCase):
def test_parse1(self):
parser = Parser()
node1 = parser.parse_string("@video example.mp4")
node2 = VideoNode(
... | nilq/baby-python | python |
#!/usr/bin/python
import json
import sys
from datetime import datetime
from pprint import pprint
def dateconv(d):
return datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%Y-%m-%d %a %H:%M")
def printtask(task, lev):
print("%s %s %s" % (
lev,
("DONE" if task["completed"] else "TODO"),
... | nilq/baby-python | python |
import unittest
from mitama._extra import _classproperty
class TestClassProperty(unittest.TestCase):
def test_getter(self):
class ClassA:
@_classproperty
def value(cls):
return "hello, world!"
self.assertEqual(ClassA.value, "hello, world!")
| nilq/baby-python | python |
from asyncio.events import AbstractEventLoop
import inspect
from typing import Any, Coroutine, List, Tuple, Protocol, Union
from xml.etree.ElementTree import Element, XML
from aiohttp import web
import xml.etree.ElementTree as ET
import socket
XMLRPCValue = Any #TODO FIXME
def parse_args(params: List[Element]):
a... | nilq/baby-python | python |
from abc import ABC
from abc import abstractmethod
from dataclasses import dataclass
from dataclasses import field
from io import IOBase
from numpy import integer
from syntax import SyntaxBlock
from syntax import SyntaxStatement
from syntax import SyntaxTerm
from typing import Dict
from typing import List
from typing i... | nilq/baby-python | python |
from flask import render_template_string
from datetime import datetime
from actions.action import BaseAction
from models import ISTHISLEGIT_SVC
from models.email import EmailResponse
from models.event import EventReportResponded
from models.template import Template
from services.email import email_provider
def get_t... | nilq/baby-python | python |
from account.conf import settings
from account.models import Account
def account(request):
ctx = {
"account": Account.for_request(request),
"ACCOUNT_OPEN_SIGNUP": settings.ACCOUNT_OPEN_SIGNUP,
}
return ctx
| nilq/baby-python | python |
def create_info_2dfaces(cellid:'int[:,:]', nodeid:'int[:,:]', namen:'int[:]', vertex:'double[:,:]',
centerc:'double[:,:]', nbfaces:'int', normalf:'double[:,:]', mesuref:'double[:]',
centerf:'double[:,:]', namef:'int[:]'):
from numpy import double, zeros, sqrt
... | nilq/baby-python | python |
import datetime
import hashlib
import json
from typing import Dict
import uuid
class Utility(object):
@staticmethod
def make_json_serializable(doc: Dict):
"""
Make the document JSON serializable. This is a poor man's implementation that handles dates and nothing else.
This method modi... | nilq/baby-python | python |
image_directory = "./images/"
| nilq/baby-python | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
try:
... | nilq/baby-python | python |
from abc import ABC, abstractmethod
import pandas as pd
class ReducerAbstract(ABC):
@abstractmethod
def transform(self, df: pd.DataFrame) -> pd.DataFrame:
...
| nilq/baby-python | python |
import difflib
import json
import re
from itertools import zip_longest
try:
import html
except ImportError:
html = None
def _mark_text(text):
return '<span style="color: red;">{}</span>'.format(text)
def _mark_span(text):
return [_mark_text(token) for token in text]
def _markup_diff(a,
... | nilq/baby-python | python |
project = "Programmation en Python"
copyright = "2020, Dimitri Merejkowsky"
author = "Dimitri Merejkowsky - Contenu placé sous licence CC BY 4.0"
version = "0.3"
language = "fr"
copyright = "CC BY 4.0"
templates_path = ["_templates"]
exclude_patterns = []
keep_warnings = True
extensions = [
"notfound.extension"... | nilq/baby-python | python |
"""
Implements a decorator that counts the number of times a function was called,
and collects statistics on how long it took to execute every single function call.
"""
from time import time
from sys import stderr, stdout
import numpy as np
class FunctionLogger(object):
"""
stores two dictionaries:
- ... | nilq/baby-python | python |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, 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 cop... | nilq/baby-python | python |
from .walker import RandomWalker
class Node2Path:
def __init__(self, graph, walk_length, num_walks, p=1.0, q=1.0, workers=1):
self.graph = graph
self.walk_length = walk_length
self.num_walks = num_walks
self.p = p
self.q = q
self.workers = workers
def get_path... | nilq/baby-python | python |
#!/usr/bin/env python
import json
import argparse
import docker
# A Simple module that returns stats for given ids.
def get_nested_elements(info, elements):
# Function to traverse dictionaries and print when value is
# not a dict (instead it's a str)
# pdb.set_trace()
if isinstance(elements, str):
... | nilq/baby-python | python |
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.regression import LinearRegression
from pyspark.ml.evaluation import RegressionEvaluator
import matplotlib.pyplot as plt
import numpy as np
def read_data(file_path):
cars_df = spark.... | nilq/baby-python | python |
from collections import OrderedDict
from typing import Optional
from queryfs.db.schema import Schema
class File(Schema):
table_name: str = "files"
fields: OrderedDict[str, str] = OrderedDict(
{
"id": "integer primary key autoincrement",
"name": "text",
"hash": "text... | nilq/baby-python | python |
#!/usr/bin/env python2.7
import os
import sys
sys.path.append(os.path.realpath(__file__ + '/../../../../lib'))
import udf
from udf import useData, expectedFailure
class GetpassTest(udf.TestCase):
def setUp(self):
self.query('CREATE SCHEMA getpass', ignore_errors=True)
self.query('OPEN SCHEMA get... | nilq/baby-python | python |
from scipy.io import netcdf
import numpy as np
import numpy.matlib
tave = 900
basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/2nd_deriv/T1/'
basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/2nd_deriv/rho_scan2/r0.001/'
basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/fg_drive/r... | nilq/baby-python | python |
"""Data structures supporting the who wrote this news crawler.
----
Copyright 2019 Data Driven Empathy LLC
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 ... | nilq/baby-python | python |
""" Module for controlling motors. """
__all__ = [
"stepper",
]
| nilq/baby-python | python |
from rest_framework import serializers
from .models import CrashCourse, CourseChapter, ChapterSection
class CrashCourseSerializer(serializers.ModelSerializer):
no_of_chapter = serializers.SerializerMethodField()
class Meta:
model = CrashCourse
fields = ('id', 'title', 'slug', 'no_of_chapter')
... | nilq/baby-python | python |
#!/usr/bin/env python3
# Test whether a PUBLISH to a topic with QoS 2 results in the correct packet flow.
from mosq_test_helper import *
rc = 1
keepalive = 60
connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive)
connack_packet = mosq_test.gen_connack(rc=0)
mid = 128
publish_packet = mosq_test.... | nilq/baby-python | python |
import time
class Logger:
def __init__(self) -> None:
pass
def log(self, message: str) -> None:
print(f'{time.ctime()}: {message}')
| nilq/baby-python | python |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.av1_adaptive_quant_mode import Av1AdaptiveQuantMode
from bitmovin_api_sdk.models.av1_key_placement_mode import Av1KeyPlacementMode
from bitmovin_api_sdk... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2016 The TensorFlow 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
#
# Unle... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.