text
string
size
int64
token_count
int64
import logging from datetime import datetime, timedelta from normality import ascii_text from sqlalchemy import func from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm.attributes import flag_modified from aleph.core import db from aleph.model.metadata import Metadata from aleph.model.validate import ...
7,710
2,404
try: from main import ClassA, ClassB except: try: from pyInet import ClassA, ClassB except: from pyInet.main import ClassA, ClassB if __name__ == "__main__": child = ClassA #Public Class network = ClassB #Private Class print("Call function using public...
1,613
617
# # MIT License # # Copyright (c) 2020 Keisuke Sehara # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
3,854
1,171
from datetime import datetime import pytz from scrapy import signals RUNNING = "running" FAILING = "failing" STATUS_COLOR_MAP = {RUNNING: "#44cc11", FAILING: "#cb2431"} STATUS_ICON = """ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="144" height="20"> <linearGradient id=...
2,498
963
import networkx as nx import pygrank as pg import pytest from .test_core import supported_backends def test_zero_personalization(): assert pg.sum(pg.PageRank()(next(pg.load_datasets_graph(["graph9"])), {}).np) == 0 def test_abstract_filter_types(): graph = next(pg.load_datasets_graph(["graph5"])) with p...
5,438
1,885
import os import PIL from PIL import Image from PIL import Image, ImageStat PIL.Image.MAX_IMAGE_PIXELS = 10000000000 import numpy as np import cv2 import openslide import time PATCH_SIZE = 224 STRIDE = 224 DOWN_SIZE = 508 def preprocess_mask(path_ori, path_mask, width_resize=2560, height_resize=1920): start_tim...
9,816
3,498
# Copyright (c) 2021 Trevor Redfern # # This software is released under the MIT License. # https://opensource.org/licenses/MIT from __future__ import annotations from typing import Tuple, Iterator, List, TYPE_CHECKING import random import tcod from game_map import GameMap import tile_types if TYPE_CHECKI...
2,433
985
# -*- coding: utf-8 -*- """ ============================= Simulating a brain object ============================= In this example, we demonstrate the simulate_bo function. First, we'll load in some example locations. Then we'll simulate 1 brain object specifying a noise parameter and the correlational structure of the...
1,492
494
from poc.classes.AuxSTBlockWithSignature import AuxSTBlockWithSignature from poc.classes.AuxSymbolTable import AuxSymbolTable class AuxSTRuleOfInference(AuxSTBlockWithSignature): def __init__(self, i): super().__init__(AuxSymbolTable.block_ir, i) self.zfrom = i.last_positions_by_rule['PredicateId...
420
143
from io import TextIOWrapper from typing import IO, Text from cli_args_system import Args from cli_args_system import Args, FlagsContent from sys import exit HELP = """this is a basic file manipulator to demonstrate args_system usage with file flags -------------------flags---------------------------- -join: join th...
5,031
1,625
import unittest from src.main import substract, add class TestMain(unittest.TestCase): def test_add(self): result = add(9, 7) self.assertEqual(result, 16) def test_substract(self): result = substract(9, 7) self.assertEqual(result, 2)
276
95
import cfile as C hello = C.cfile('hello.c') hello.code.append(C.sysinclude('stdio.h')) hello.code.append(C.blank()) hello.code.append(C.function('main', 'int',).add_param(C.variable('argc', 'int')).add_param(C.variable('argv', 'char', pointer=2))) body = C.block(innerIndent=3) body.append(C.statement(C.fcall('pr...
441
174
class Question: def __init__(self, qtext, qanswer): self.text =qtext self.answer =qanswer
116
41
# Exercício 5.2 - Modifique o programa para exibir os números de 50 a 100. i = 50 print('\n') while i <= 100: print('%d' % i) i += 1 print('\n')
156
76
#!/usr/bin/env python # -*- coding: utf-8 -*- """ CREDIT: Main layout of this file was done by Lucija Kopic (graduation thesis) at Faculty of Electrical Engineering and Computing, University of Zagreb. """ import math from threading import Thread import actionlib import tf from tf.transformations import ...
14,141
4,474
import math n=int(input('Nhap mot so:')) output=math.factorial(n) print('Giai thua cua ',n,' la: ',output)
107
45
from __future__ import absolute_import import flytekit.plugins __version__ = '0.3.1'
86
31
""" @Author: Qu Xiangjun @Time: 2021.01.26 @Describe: 此文件负责根据雷达数据进行导航的线程类定义 """ import socket import time from threading import Thread import threading import numpy as np # python3.8.0 64位(python 32位要用32位的DLL) from ctypes import * from Navigation_help import * from Can_frame_help import * VCI_USBCAN2 = 4 # 设备类型 USBCA...
7,289
3,029
#Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo. valor = int(input("Dígite um número:")) if valor < 0: print("O número",valor,"é negativo!") else: print("O número",valor,"é positivo!")
233
86
f'{1:.5d} {2:3.5d} {3:3d} {"spam":>20} {4:<#d}'
48
40
""" make_one_on_comp =============== Autogenerated DPF operator classes. """ from warnings import warn from ansys.dpf.core.dpf_operator import Operator from ansys.dpf.core.inputs import Input, _Inputs from ansys.dpf.core.outputs import Output, _Outputs from ansys.dpf.core.operators.specification import PinSpecification...
6,346
1,914
# # Program: www_utils.py # Version: 0.10 # Description: # Generic search functions for Cheshire 3 # # Language: Python # Author: John Harrison <john.harrison@liv.ac.uk> # Date: 19 December 2007 # # Copyright: &copy; University of Liverpool 2005-2007 # # Version History: # 0.01 - 13/04/2005 - JH...
8,716
2,983
# coding: utf-8 import numpy as np from supervisely_lib.geometry.constants import DATA, ORIGIN from supervisely_lib.geometry.geometry import Geometry from supervisely_lib.geometry.point_location import PointLocation from supervisely_lib.geometry.rectangle import Rectangle from supervisely_lib.imaging.image import res...
5,057
1,615
""" .. module:: CClassifierGradientSGDMixin :synopsis: Mixin for SGD classifier gradients. .. moduleauthor:: Ambra Demontis <ambra.demontis@unica.it> .. moduleauthor:: Marco Melis <marco.melis@unica.it> """ from secml.array import CArray from secml.ml.classifiers.gradients import CClassifierGradientLinearMixin c...
851
256
# -*- coding: utf-8 -*- """ | **@created on:** 9/4/20, | **@author:** prathyushsp, | **@version:** v0.0.1 | | **Description:** | | | **Sphinx Documentation Status:** """ from abc import ABCMeta, abstractmethod import json class BaseClass(metaclass=ABCMeta): @abstractmethod def pretty(self): pass ...
455
171
adjective = input("Enter an adjective: ") adjective = input("Enter another adjective: ") noun = input("Enter a noun: ") noun = input("Enter another noun: ") plural_noun = input("Enter a plural noun: ") game = input("Enter a game: ") plural_noun = input("Enter another plural noun: ") verb = input("Enter a verb ending in...
1,891
577
import argparse import os import logging import sys from types import SimpleNamespace from .util.print_tree import print_tree def data_to_card_path(card_dir, fpath): return os.path.splitext("/" + os.path.relpath(fpath, start=card_dir))[0] class Card: def __init__(self, card_dir, fpath): self._fpath = ...
5,854
1,845
# -*- coding: utf-8 -*- #!/usr/bin/env python2 import fileinput import json import random import socket import thread # import urllib2 # import collections import time import traceback import re from decimal import Decimal as D from datetime import datetime import MySQLdb # import math username = 'Arcadia2' oper_key ...
35,322
9,898
"""Test suite for Average Genome Size tasks.""" from app.display_modules.ags.ags_tasks import boxplot, ags_distributions from app.samples.sample_models import Sample from app.tool_results.microbe_census.tests.factory import create_microbe_census from tests.base import BaseTestCase class TestAverageGenomeSizeTasks(B...
1,492
495
"""Global serialization configuration.""" from importlib import import_module import os def configure_serialization(): """Configure serialization for all classes in folder.""" for name in filter( lambda s: not s.startswith('_') and s.endswith('.py'), os.listdir(os.path.dirname(os.path...
491
145
import os import ctypes import windows from windows import winproxy from windows.generated_def import windef from windows.generated_def.winstructs import * # Remove this ? class EPUBLIC_OBJECT_TYPE_INFORMATION(PUBLIC_OBJECT_TYPE_INFORMATION): pass current_process_pid = os.getpid() class Handle(SYSTEM_HANDLE): ...
4,678
1,538
import traceback import numpy as np from matplotlib import pyplot, pyplot as plt from sklearn.metrics import ( mean_squared_error, median_absolute_error, roc_curve, auc, f1_score, precision_recall_curve, r2_score, ) from sklearn.metrics import confusion_matrix import column_labeler as clabel...
4,428
1,717
import pytest from pyutil import pull def test_pull_with_empty_list(): lst = [] pull(lst, 1) expected = [] assert lst == expected def test_pull_when_list_has_values(): lst = [1, 2, 3, 4, 5] pull(lst, 2) expected = [1, 3, 4, 5] assert lst == expected def test_pull_when_list_has_valu...
1,328
611
''' --------------------------------------------IMPORTING NECESSARY LIBRARIES------------------------------------------- ''' import numpy as np import pandas as pd from math import radians, cos, sin, asin, sqrt from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import LabelEncoder, OneHotEnc...
30,681
11,209
import random import time n = eval(input("Enter the number of elements to sort: ")) lst = list(range(n)) random.shuffle(lst) startTime = time.time() lst.sort() print("Sort time in Python is", int(time.time() - startTime), "seconds")
234
77
# -*- coding: utf-8 -*- __author__ = 'Daryl Yu' __email__ = 'dyu@fastmail.com' __version__ = '0.0.2'
102
52
"""Define common test configuraiton.""" import pytest from pysmartapp.dispatch import Dispatcher from pysmartapp.smartapp import SmartApp, SmartAppManager @pytest.fixture def smartapp(event_loop) -> SmartApp: """Fixture for testing against the SmartApp class.""" app = SmartApp(dispatcher=Dispatcher(loop=eve...
1,239
376
todo_list = ["" for i in range(11)] command = input() while command != 'End': task = command.split('-') importance = int(task[0]) thing_to_do = task[1] todo_list[importance] = thing_to_do command = input() final_list = [x for x in todo_list if x != ""] print(final_list)
294
109
#!/usr/bin/env python3.8 from socket import create_server from users import Users from credentials import Credentials def create_credentials(first_name, last_name, user_name, credential): users = Users(first_name, last_name, user_name, credential) return users def save_user(users): users.save_user() d...
6,035
1,527
from game_states import GameStates from action_consumer.available_actions_enum import Action def get_menu_title(menu_name): menu_titles = {} menu_titles.update({GameStates.SHOW_INVENTORY:'Press the key next to an item to use it, or Esc to cancel.\n'}) menu_titles.update({GameStates.DROP_INVENTORY: 'Press...
2,346
893
''' Version and license information. ''' __all__ = ['__version__', '__versiondate__', '__license__'] __version__ = '1.3.3' __versiondate__ = '2022-01-16' __license__ = f'Sciris {__version__} ({__versiondate__}) – © 2014-2022 by the Sciris Development Team'
270
111
# -*- coding: utf-8 -*- # Import Python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import TestCase from tests.support.mock import patch # Import Salt libs import salt.fileserve...
1,154
370
INTERVALS = [ "1h", ]
26
16
import torch.nn as nn from networks.resnet import resnet18 from networks.shufflenet import shufflenet_v2_x1_0 from networks.cifar_net import Net from networks.mlp import MLP class ModelFactory(): def __init__(self): pass @staticmethod def get_model(target_model, num_classes, img_size, pretrained...
1,273
407
from manim import * from TTS.TTS import get_mp3_file from utils import cut, get_duration, deal_text import time class Video(Scene): def construct(self): # INFO 视频开头 LOGO = ImageMobject("./media/images/logo.png").scale(0.3).to_edge(UP, buff=2) Slogan_text = "为你收集日落时的云朵,为你收藏下雨后的天空" g...
5,536
2,237
from unittest import TestCase class Test(TestCase): def test_punch(self): self.fail()
106
38
from sevenbridges.meta.resource import Resource # noinspection PyUnresolvedReferences,PyProtectedMember class BatchBy(Resource, dict): """ Task batch by resource. """ _name = 'batch_by' # noinspection PyMissingConstructor def __init__(self, **kwargs): self.parent = kwargs.pop('_parent...
1,518
470
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@email.com', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password) class ModelTests(Tes...
2,764
822
"""coBib's database tests."""
30
12
# program to display first n lines in a text file n = int(input("Enter number of lines: ")) with open("note.txt") as file: while n > 0: print( file.readline(), end="" ) n -= 1
230
72
import os import sys import ctypes import webbrowser from .lineEdit import LineEdit from .dialogWithCheckBox import DialogWithCheckBox from eplusplus.controller import ActorUser from eplusplus.exception import ColumnException, NoIdfException, InstallException, NoCsvException from PyQt5.QtCore import QSize, Qt, QRect fr...
23,420
6,711
from tree_map_class import * class RedBlackTreeMap(TreeMap): """Sorted map implementation using red-black tree.""" class _Node(TreeMap._Node): """Node class for red-black tree maintains bit that denotes color.""" __slots__ = "_red" # add additional data member to the Node class ...
4,555
1,299
from functools import wraps import datetime from flask import jsonify, Flask, request, session from my_class import ExternalFunctions app = Flask(__name__) app.config["SECRET_KEY"] = 'kkkoech' user_details = dict() diary_entries = dict() @app.route("/api/v1", methods=['GET']) def home(): return jsonify({"messa...
5,170
1,555
const1 = "a" const2 = "b"
26
15
"""intake plugin for SDMX data sources""" import intake from intake.catalog import Catalog from intake.catalog.utils import reload_on_change from intake.catalog.local import LocalCatalogEntry, UserParameter import pandasdmx as sdmx from collections.abc import MutableMapping from datetime import date from itertools im...
13,029
3,573
# #import scipy #from scipy import io as sio import scipy.io.wavfile from ext.spafe.utils import vis from ext.spafe.features.bfcc import bfcc class AfeBfcc: @staticmethod def extract_bfcc(wav_file): print('获取BFCC特征') num_ceps = 13 low_freq = 0 high_freq = 2000 nfilts = 2...
1,388
494
class Error(Exception): """Base class for other exceptions""" pass class ClientError(Error): """Raised when the client details are not valid""" pass class ImageError(Error): """Raised when the Image Returned is not valid""" pass
268
83
import logging from datetime import date from telegram import Update from telegram.ext import ApplicationBuilder, CommandHandler from config.notif_config import NotifConfig from src.emojis import Emojis from src.team_fixtures_manager import TeamFixturesManager from src.telegram_bot.bot_commands_handler import NextAnd...
4,673
1,454
"""Edit plugin for Home Assistant CLI (hass-cli).""" import json as json_ import logging import click import homeassistant_cli.autocompletion as autocompletion from homeassistant_cli.cli import pass_context from homeassistant_cli.config import Configuration from homeassistant_cli.helper import raw_format_output, req_r...
1,517
458
"""Collection of model.""" from typing import Any from django.conf import settings from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.translation import gettext_lazy as _ from djgeojson.fields import PointField from .utils import get_read_...
8,576
2,677
# coding = utf-8 import copy import json import logging import math import os import shutil import tarfile import tempfile import sys from io import open import torch from torch import nn from torch.nn import CrossEntropyLoss from activation_function import gelu, swish, ACT2FN import logging logger = logging.getLogge...
1,938
637
import numpy as np from osgeo import gdal from .median_absolute_deviation import MedianAbsoluteDeviation from .raster_file import RasterFile class RasterDataDifference(object): GDAL_DRIVER = gdal.GetDriverByName('GTiff') def __init__(self, lidar, sfm, band_number): self.lidar = RasterFile(lidar, ban...
2,276
742
import time import hmac import base64 import datetime import schedule import psycopg2 from time import mktime from hashlib import sha1 from pprint import pprint from requests import request from datetime import datetime from wsgiref.handlers import format_date_time from psycopg2.extensions import ISOLATION_LEVEL_AUTOCO...
3,386
943
# -*- coding: utf8 -*- # 作者:Light.紫.星 # QQ:1311817771 import AndroidQQ,threading,time from AndroidQQ import Android class Main: def __init__(self): pass def login(self,qqnum,qqpass): print 15*"-",("开始登陆QQ:"),qqnum,15*"-" self.sdk = Android() self.state = 0 s...
1,540
661
from util.env import log_dir import logging class MyFormatter(logging.Formatter): def formatTime(self, record, datefmt=None): return logging.Formatter.formatTime(self, record, datefmt).replace(',', '.') def get(name): log = logging.getLogger(name) log.setLevel(logging.DEBUG) formatter = MyFo...
527
172
# Generated by Django 2.2.2 on 2019-10-23 14:41 from django.db import migrations, models import tinymce.models class Migration(migrations.Migration): dependencies = [ ('core', '0095_auto_20191022_1602'), ] operations = [ migrations.AlterModelOptions( name='casestudy', ...
1,347
424
#!/usr/bin/python import colorsys from azure.servicebus import ServiceBusService from azure.servicebus import Message from blinkt import set_pixel, set_brightness, show, clear import time import json class Payload(object): def __init__(self, j): self.__dict__ = json.loads(j) def snake( r, g, b ): "Th...
2,243
831
print('Quanto dinheiro voce tem na carteiro') print('-'*20) re = float(input('R$ ')) dol = re * 0.1874 print('-'*20) print('US$ {:.2f}'.format(dol))
149
73
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/parallels/catkin_ws/src/baxter_common/baxter_core_msgs/msg/AnalogIOState.msg;/home/parallels/catkin_ws/src/baxter_common/baxter_core_msgs/msg/AnalogIOStates.msg;/home/parallels/catkin_ws/src/baxter_common/baxter_core_msgs/msg/AnalogOutputCommand...
3,163
1,393
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 12 17:45:51 2018 @author: zhao """ import argparse import torch import torch.nn.parallel from torch.autograd import Variable import torch.optim as optim import torch.nn.functional as F import sys import os import numpy as np BASE_DIR = os.path.dir...
14,031
5,410
import simpy import itertools import numpy as np from RideSimulator.Driver import Driver from RideSimulator.HexGrid import HexGrid def get_spot_locations(width: int, height: int, interval: int) -> np.ndarray: """ :param width: width of the grid :param height: height of the grid :param interval: distan...
6,839
2,029
""" Day $: https://adventofcode.com/2021/day/$ """ Data = list def parse_file(path: str) -> Data: with open(path) as f: raw = f.read().splitlines() data = raw return data def part_1(data: Data): ... def part_2(data: Data): ... def main(): data = parse_file("example.txt") ...
427
172
import numpy as np def Reichardt8(video, dirs=[0,1,2,3,4,5,6,7]): ''' Returns a tuple of Reichardt-Hassenstein correlators in 8 directions args: video: Shape ~ [TimeSteps, H, W, 1] ''' vp1, vm1 = Reichardt_vertical_2channels_Vectorized(video) #Directions 1, -1 vp3, vm3 = Reich...
3,174
1,351
from turtle import * coeficient = 0.5 speed(5) def base(): fillcolor("#fae0bd") begin_fill() pencolor("#c8835c") pensize(10 * coeficient) penup() backward(100 * coeficient) pendown() for i in range(0,2): forward(300 * coeficient) right(90) fo...
1,662
707
REDSTONE = 55 REPEATER = 93 TORCH = 75 AIR = 0 GLASS = 20 SLAB = 44 DOUBLE_SLAB = 43 WOOL = 35 DIR_WEST_POS_Z = 0 DIR_NORTH_NEG_X = 1 DIR_EAST_NEG_Z = 2 DIR_SOUTH_POS_X = 3 TORCH_ON_GROUND = 5 TORCH_POINTING_POS_X = 1 TORCH_POINTING_NEG_X = 2 TORCH_POINTING_POS_Z = 3 TORCH_POINTING_NEG_Z = 4 STONE_SLAB_TOP = 8 DO...
881
463
import os import subprocess import sys class CVSHandler(): """ Handler of CVS (fir, mercurial...) directories, The main purpose of this class is to cache external cvs command output, and determine the appropriate files to yield when navigating to a subdirectory of a project. This basically means th...
4,973
1,427
import json filename = "data.json" mydata = { "title":"我的测试数据", "lesson":{ "python":"学习中", 'vue':"学习完毕", "golang":"基本精通" }, "games":{ "GAT":"一年没有玩了" }, } # 文件写入 with open(filename,'w',encoding="utf-8") as data: # 数据,文件句柄,json缩进空格数 json.dump(mydata,data,inden...
436
225
import progressbar, time from .colors import * # progress bar def animated_marker(): widgets = ['In Process: ', progressbar.AnimatedMarker()] bar = progressbar.ProgressBar(widgets=widgets).start() for i in range(18): time.sleep(0.1) bar.update(i)
280
92
# from nipype import config # config.enable_debug_mode() # Importing necessary packages import os import os.path as op import glob import json import nipype from nipype import config, logging import matplotlib.pyplot as plt import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe import nipype.interfaces...
4,406
1,417
import sys N = -1 G = None H = None vis = None vis_aux = None valence = None flows = {} answer = [] allowed_flows = { 3 : [-1, 1], 4 : [-1, 1, 2], 5 : [-1, 1, 2, -2] } def has_k_flow (graph): global N, G, H, vis, valence, flows G = graph N = len(G) H = [[0] * N for i in xrange(0, N)] vis = [False] * N ...
3,692
1,744
#!/usr/bin/pyhon """ Copyright 2014 The Trustees of Princeton University 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...
45,642
13,948
from microplates.utils import * def test_itertuples(): assert list(itertuples((0,0),(0,2))) == [(0,0),(0,1),(0,2)] assert list(itertuples((1,0),(2,0))) == [(1,0),(2,0)] assert list(itertuples((1,0),(2,1))) == [(1,0),(1,1),(2,0),(2,1)] assert list(itertuples((1,0),(2,1), by='column')) == [(1,0),(2,0),(1...
3,009
1,365
import numpy as np import random from audio import read_mfcc from batcher import sample_from_mfcc from constants import SAMPLE_RATE, NUM_FRAMES from conv_models import DeepSpeakerModel from test import batch_cosine_similarity np.random.seed(123) random.seed(123) model = DeepSpeakerModel() model.m.load_weights('/Users...
1,066
481
import sys import os import subprocess import pytest import numpy as np from functools import partial import collections from grpc._channel import _Rendezvous from google.cloud import bigtable from google.auth import credentials from math import inf from datetime import datetime, timedelta from time import sleep from s...
135,252
55,314
import graphene_django_optimizer as gql_optimizer from ...delivery import models def resolve_delivery_zones(info): qs = models.DeliveryZone.objects.all() return gql_optimizer.query(qs, info)
202
69
import os import json import uuid import shlex import weechat import requests from ciscosparkapi import CiscoSparkAPI from ws4py.client.threadedclient import WebSocketClient SCRIPT_NAME = "spark" FULL_NAME = "plugins.var.python.{}".format(SCRIPT_NAME) SPARK_SOCKET_URL = 'https://wdm-a.wbx2.com/wdm/api/v1/devices' ...
5,617
1,860
import os import sys import subprocess import requests import ssl import random import string import json from flask import jsonify from flask import Flask from flask import request from flask import send_file import traceback from uuid import uuid4 from notebook_utils.synthesize import * try: # Python 3.5+ f...
1,869
607
import RPi.GPIO as GPIO import time import pygame from pygame import locals import pygame.display GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) speedA = 0.000 speedB = 0.000 x = 512.00 y = 512.00 # frequency=100Hz t_on = 0.00 t_off = 0.00 ledpin1 =35 # left_fwd ledpin2 =36 # right_fwd l...
4,728
2,595
""" This module contains functions that are geared toward serializing objects, in particular JSON API objects. """ import decimal from collections import Iterable from rest_helpers.jsonapi_objects import Resource, Response, Link, JsonApiObject, Relationship def to_jsonable(obj, no_empty_field=False, is_private=None):...
8,548
2,434
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here t = int(input()) for _ in range(t): n =...
458
161
import random import time from characters import Wizard, Creature def main(): game_header() game_loop() def game_header(): print('------------------------------') print(' WIZARD TEXT GAME APP') print('------------------------------') def game_loop(): creatures = [ Creature('T...
1,753
518
import threading from time import sleep import RPi.GPIO as GPIO illumination_time_default = 0.001 class XmasTree(threading.Thread): #Pins #Model B+ or A+ #A, B, C, D = 21, 19, 26, 20 #Other model, probably Model A or Model B #A, B, C, D = 7, 9, 11, 8 def __init__(self, A = 21,B = ...
2,581
1,012
jogo = [[], [], []], [[], [], []], [[], [], []] cont = 0 contx = conto = contxc = contoc = 0 while True: l = int(input('Informe a linha: ')) c = int(input('Informe a coluna: ')) if l < 4 and c < 4: if cont % 2 == 0: jogo[l-1][c-1] = 'X' else: jogo[l-1][c-1] = 'O' ...
1,962
722
# Copyright 2018 PayTrace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
23,625
6,507
#!/usr/bin/env python3 # Day 3, with some speed optimizations # Not really necessary for day 3, but probably later import sys import typing import array if len(sys.argv) != 2: print('Usage:', sys.argv[0], '<input.txt>') sys.exit(1) width = 0 heigth = 0 # Use 1-d array of bytes to keep pixels def read_input...
1,283
500
x = 23 epsilon = 0.001 guess = x/2 tries = 0 while abs(guess**2- x) >= epsilon: if guess**2 > x: guess /=2 else: guess *=1.5 tries +=1 print(f'Number of tries: {tries}') print(f'Guess = {guess}')
226
105
import dash_core_components as dcc import dash_html_components as html from .layouts.info_card import render as info_card from .layouts.graph_wrapper import render as graph_wrapper from .layouts.project_bar import render as project_bar from .layouts.color_card import render as color_card from ..data_retrievers.dummy ...
6,223
1,414
"""" 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dis...
2,440
736
from office365.runtime.client_value import ClientValue class PopularTenantQuery(ClientValue): pass
105
31
"""blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
1,320
425