text
string
size
int64
token_count
int64
import math import matplotlib.pyplot as plt import json import os import warnings warnings.filterwarnings("ignore") def make_dataset(dir, file_ext=[]): paths = [] assert os.path.exists(dir) and os.path.isdir(dir), '{} is not a valid directory'.format(dir) for root, _, fnames in sorted(os.walk(dir)): ...
1,400
496
import agenda23 agenda23.le('Agenda.txt') while True: opcao = agenda23.menu() if opcao == 0: break elif opcao == 1: agenda23.novo() elif opcao == 2: agenda23.altera() elif opcao == 3: agenda23.apaga() elif opcao == 4: agenda23.lista() elif opcao == 5:...
497
209
def maxProfit(self, prices: List[int]) -> int: with_stock = -2147483647 without_stock = 0 for stock in prices : with_stock = max(with_stock, without_stock - stock) without_stock = max(without_stock, with_stock + stock) return without_stock
296
92
try: import os import pkg_resources # part of setuptools __version__ = pkg_resources.get_distribution(os.path.dirname(__file__)).version except: pass from .qualtrics import *
192
61
from django.apps import AppConfig class ImageAppConfig(AppConfig): name = 'image_app'
97
34
import time import requests import xml.dom.minidom from lxml import etree from django.shortcuts import render from django.http import HttpResponse from django.contrib import messages from django.core.urlresolvers import reverse_lazy from django.views.generic import ListView, DetailView from django.views.generic.edit im...
9,650
2,735
from amlb.utils import call_script_in_same_dir def setup(*args, **kwargs): call_script_in_same_dir(__file__, "setup.sh", *args, **kwargs) def run(dataset, config): from .exec import run return run(dataset, config)
230
80
def generate_pentagons(n_of_pentagons): pentagons = (num * (3 * num - 1) // 2 for num in range(1, n_of_pentagons)) for _ in range(n_of_pentagons - 1): yield next(pentagons)
189
79
from itunes_app_scraper.util import AppStoreException, AppStoreCollections, AppStoreCategories, AppStoreUtils import json import pytest import os def test_category_exists(): category = AppStoreCategories() assert category.BOOKS == 6018 def test_category_does_not_exist(): category = AppStoreCategories() ...
932
267
from .record import Record class Span(Record): __attributes__ = ['start', 'stop', 'type'] def adapt_spans(spans): for span in spans: yield Span(span.start, span.stop, span.type) def offset_spans(spans, offset): for span in spans: yield Span( offset + span.start, ...
802
235
from __future__ import print_function from bingads.service_client import _CAMPAIGN_OBJECT_FACTORY_V13 from bingads.v13.internal.bulk.string_table import _StringTable from bingads.v13.internal.bulk.entities.single_record_bulk_entity import _SingleRecordBulkEntity from bingads.v13.internal.bulk.mappings import _SimpleBul...
7,297
2,124
""" Tests for the LTI outcome service handlers, both in outcomes.py and in tasks.py """ from unittest.mock import MagicMock, patch import ddt from django.test import TestCase from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator import lms.djangoapps.lti_provider.tasks as tasks from common.djangoapps...
4,320
1,368
from loser_agent import * class DumbAgent(LoserAgent): def __init__(self, is_logging = False, is_printing_to_console = False, isMainAgent = False, fileName = ""): super().__init__(is_logging, is_printing_to_console, isMainAgent) # For debugging self.is_logging = is_logging...
1,954
633
from .base.api_handler import APIBaseHandler class APIHandler(APIBaseHandler): def get(self): pass
113
34
import random def find(array): summation = sum(array) n = len(array) total = n*(n+1)//2 miss = total - summation return miss def main(): arr = [i for i in range(99)] print(arr) result = find(arr) print("The missing number is-", result) if __name__ == '__main__': main()
317
117
# Problem Reduction: variation of n-th staircase with n = [1, 2] steps. # Approach: We generate a bottom up DP table. # The tricky part is handling the corner cases (e.g. s = "30"). # Most elegant way to deal with those error/corner cases, is to allocate an extra space, dp[0]. # Let dp[ i ] = the number of ways to ...
1,099
449
""" Tile svs/scn files Created on 11/01/2018 @author: RH """ import time import matplotlib import os import shutil import pandas as pd matplotlib.use('Agg') import Slicer import staintools import re # Get all images in the root directory def image_ids_in(root_dir, mode, ignore=['.DS_Store', 'dict.csv']): ids =...
4,525
1,535
from __future__ import division import numpy as np import matplotlib.pyplot as plt m = 4 b = -.2 bl = -.1 br = -.1 sh = .13 def show_ped(image, bb): im = np.zeros(image.shape[:2]) [ymin, xmin, ymax, xmax] = bb im[ymin:ymax,xmin:xmax]=1 plt.imshow(im) plt.show() def in_region(x,y, m=0, b=0, ab...
2,850
1,157
# # PySNMP MIB module DPS-MIB-V38 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DPS-MIB-V38 # Produced by pysmi-0.3.4 at Mon Apr 29 18:39:21 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...
20,941
10,234
import numpy as np def load_graph(path): edges = np.array([]) with open(path, 'r', encoding='utf-8', errors='ignore') as g_file: next(g_file) # skip the header line for line in g_file: try: fields = line.split(",") edges = np.append(edges, [int(field...
524
165
import time from smqtk.utils import SmqtkObject class SimpleTimer (SmqtkObject): """ Little class to wrap the timing of things. To be use with the ``with`` statement. """ def __init__(self, msg, log_func=None, *args): """ Additional arguments are passed to the logging method ...
1,055
326
arr = ['', 'Rolien', 'Naej', 'Elehcim', 'Odranoel'] n = int(input()) while n != 0: n -= 1 k = int(input()) while k != 0: k -= 1 num = int(input()) print(arr[num])
206
94
import socket, time, sys import argparse __version__="0.1" min_port=0 #max_port=65535 max_port=10000 parser = argparse.ArgumentParser(description="a simple python port scanner",epilog="author: blackc8") parser.add_argument("hostname",metavar="<hostname>",help="host to scan") parser.add_argument("-dp","--ddport",help=...
3,314
1,132
# -*- coding: utf-8 -*- """ Created on Mon Sep 16 20:15:55 2019 @author: Shinelon """ import numpy as np import pandas as pd import matplotlib.pyplot as plt path='ex2data1.txt' data=pd.read_csv(path,header=None,names=['Exam1','Exam2','Admitted']) data.head() #两个分数的散点图,并用颜色编码可视化 positive=data[data['Admitted'].isin([1]...
4,730
2,240
# Generated by Django 2.1.9 on 2019-09-01 09:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('trade', '0002_accountdetail_orderinfo'), migrations.swappable_d...
855
282
# Code from Chapter 5 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by Stephen Marsland (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no...
3,557
1,266
#!/usr/bin/env python3 """ Gradients for inner product. """ import tensorflow as tf from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import sparse_ops correlation_grad_module = tf.load_op_library('./build/libcorrelation_grad.so') @ops.RegisterGradien...
929
276
from ._scorer import make_ts_scorer from ._scorer import get_scorer __all__ = [ "get_scorer", "make_ts_scorer", ]
123
52
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file. """ auth.views.user selenium tests """ from flask import url_for from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from sner.server.auth.models import User from sner.serve...
2,776
951
# -*- coding: utf-8 -*- from .box import indent from .box import read_box class MediaFile(object): def __init__(self): self.ftyp = None self.mdats = [] self.meta = None self.moov = None def __repr__(self): rep = self.ftyp.__repr__() + '\n' rep +...
936
317
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> >>> ================================ RESTART ================================...
2,257
814
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from glob import glob import logging import os from os.path import abspath, dirname, normpath import re from shutil import rmtree import sqlite3 import sys import ...
3,690
1,333
# -*- coding: utf-8 -*- from __future__ import unicode_literals TIPO = 'selectable' # 'basic' or 'selectable'. 'basic': necesario para el funcionamiento del programa # 'selectable': No necesario. Añade nuevas funcionalidades al programa # Por ejemplo autenticar es 'basic', pero actas es pre...
3,486
1,135
import os import cv2 import fire import time import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn.functional as F from configs.common import config as cfg from hawkdet.models.build import build_detor from hawkdet.lib.numpy_nms import np_nms from hawkdet.lib.box_utils import decode, dec...
5,944
2,140
class Content: def __init__(self, id="", value=""): if(id == ""): raise TypeError else: self.id = id self.value = value
178
51
name="zhuiyue" num="123456" num=111 num3=333 str="keep going" num4=666 num5=888 num5=777 num6=999
101
69
from keydra.clients.contentful import ContentfulClient from keydra.providers.base import BaseProvider from keydra.providers.base import exponential_backoff_retry from keydra.exceptions import DistributionException from keydra.exceptions import RotationException from keydra.logging import get_logger LOGGER = get_log...
2,491
655
# Generated by Django 2.2.13 on 2021-02-11 13:07 from django.db import migrations, models import django.db.models.deletion def set_exam_resources(apps, schema_editor): Resource = apps.get_model('numbas_lti', 'Resource') Attempt = apps.get_model('numbas_lti', 'Attempt') for r in Resource.objects.exclude(e...
1,266
435
from requests import Session from requests.adapters import HTTPAdapter from urllib3 import Retry from sahyun_bot.utils_logging import HttpDump DEFAULT_RETRY_COUNT = 3 RETRY_ON_METHOD = frozenset([ 'HEAD', 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'TRACE' ]) RETRY_ON_STATUS = frozenset([ 403, 429, 500, 502,...
1,356
446
import json import requests from datetime import datetime, timedelta from BookCirculation import BookCirculation from DAO.AbstractDAO import AbstractDAO from DAO.BookDAO import BookDAO from DAO.UserDAO import UserDAO from constant import * from datetime import datetime class BookCirculationDAO(AbstractDAO): def __...
5,763
1,580
#!/usr/bin/env python # -*- coding: utf-8 -*- # Common Python library imports import os # Pip package imports from six.moves.urllib.parse import urljoin from flask import url_for, request, abort from werkzeug import secure_filename, FileStorage, cached_property # Internal package imports from flask_mm.utils import...
4,128
1,148
from functools import partial from marshmallow import ValidationError from web.extensions import db from .validators import validate_user_token from .serializers import SuperUserSchema from .exceptions import InvalidUsage from .user import SuperUser def validate_and_extract_user_data(json_data, skipped_fields: tuple=...
1,627
517
''' Registers auxillary encodings in the codecs module. >>> 'x\x9cK\xc9L/N\xaa\x04\x00\x08\x9d\x02\x83'.decode('zip') 'digsby' ''' from peak.util.imports import lazyModule sys = lazyModule('sys') warnings = lazyModule('warnings') locale = lazyModule('locale') collections = lazyM...
12,853
4,400
from ._factor_base import FactorBase from ._factor_stack import FactorStack from ._stacked_factor_graph import StackedFactorGraph from ._storage_metadata import StorageMetadata from ._variable_assignments import VariableAssignments from ._variables import RealVectorVariable, VariableBase __all__ = [ "FactorStack",...
463
133
# coding=utf-8 import cyfib def test_valid(): assert (17711 == cyfib.compute_fibonacci_wrapper(20))
106
47
#!/usr/bin/env python3 from http.server import SimpleHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs import time class CCVRRequestHandler(SimpleHTTPRequestHandler): def do_GET(self): # Add 'files' prefix self.path = '/files' + self.path super().do_GET() def do_HEAD(self): # Add 'files' pre...
1,612
644
import os from datetime import datetime, timedelta from airflow import DAG from airflow.operators.docker_operator import DockerOperator from docker.types import Mount default_args = { "owner": "airflow", "description": "Use of the DockerOperator", "depend_on_past": False, "start_date": datetime(2021, ...
4,907
1,584
from django.http import JsonResponse from django.http import HttpResponse from rest_framework.views import APIView from .store_population import StorePopulation import time as processTiming import uuid # API to fetch Ireland population used by frontend. The result consist of population estimate and year. class Ireland...
1,723
466
# -*- coding: utf-8 -*- """ This script shows how to embed the animation into a background image (it's also possible to embed the animation into another animation, but that's too complicated to implement in a simple program ...) """ from colorsys import hls_to_rgb import gifmaze as gm from gifmaze.algorithms import wil...
2,536
929
from socket import * a=input("请输入IP地址:") b=input("请输入端口:") ADDR = ("176.17.12.178", 31414) giao = socket(AF_INET, SOCK_DGRAM) while 1: m = input(":") if not m: break else: giao.sendto(m.encode(), ADDR) d, a = giao.recvfrom(1024) print("意思是", d.decode()) giao.close()
313
156
from django.conf.urls import url from django.conf import settings from panel.views import * urlpatterns = [ url(r'^$', index, name='index'), ]
151
51
import turtle color=["green", "yellow",'orange','blue','pruple','red','pink'] x=10 y= 270 i=0 turtle.bgcolor("black") while True: turtle.color(color[0]) turtle.forward(x) turtle.left(y) x+=10 y-=1 i+=1 turtle.mainloop()
244
117
"""Model definitions.""" # Authors: Afshine Amidi <lastname@mit.edu> # Shervine Amidi <firstname@stanford.edu> # MIT License import numpy as np from enzynet import constants from keras import initializers from keras import layers from keras.layers import advanced_activations from keras import models from k...
2,446
821
from db import db class AddressEntity(db.Model): __tablename__ = "address" id = db.Column(db.Integer, primary_key=True) int_number = db.Column(db.String(15), nullable=False) ext_number = db.Column(db.String(15), nullable=False) block = db.Column(db.String(15), nullable=False) number = db.Colu...
998
350
import os import click import requests from FeatureCloud.api.imp.exceptions import FCException from FeatureCloud.api.imp.test import commands from FeatureCloud.api.cli.test.workflow.commands import workflow @click.group("test") def test() -> None: """Testbed related commands""" test.add_comma...
10,357
2,995
import subprocess import logging import os, time from pathlib import Path from shutil import copyfile import pandas as pd from datetime import datetime def estimate_time(filename, config, layer=None): base_commands = ['axicli', filename, '--config', config] end_command = ['-vTC'] if layer is None: ...
4,188
1,358
#!/usr/bin/env python import argparse parser = argparse.ArgumentParser(prog="region_optimize.py", description="Find the kernel parameters for Gaussian region zones.") parser.add_argument("spectrum", help="JSON file containing the data, model, and residual.") parser.add_argument("--sigma0", type=float, default=2, help=...
5,258
1,915
import requests from urllib.request import urlopen from bs4 import BeautifulSoup def get_urls_and_last_updates(): # Pega a url e a ultima data de atualização das bases disponíveis no OpenDataSUS urls = list() last_ups = list() try: html = BeautifulSoup(urlopen('https://opendatasus.saude.gov.br/da...
2,261
798
# Copyright 2022 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 or agreed to in writing, ...
10,699
4,681
import asyncio from fusionsid import Decorators deco = Decorators do_roast = deco.roast @deco.compliment() # will give you a complement before the function is run @Decorators.fact() # you can just put the class name and use that instead of setting it to a var @do_roast() # you can set it to a variable and use th...
427
143
# Basiskonfigurationsfile _base_ = '../centripetalnet/centripetalnet_hourglass104_mstest_16x6_210e_coco.py' model = dict( type='CornerNet', backbone=dict( type='HourglassNet', downsample_times=5, num_stacks=2, stage_channels=[256, 256, 384, 384, 384, 512], stage_blocks=...
2,303
1,015
import json import mock import os from django.contrib.auth import get_user_model from django.core import mail from django.core.urlresolvers import reverse from django.test import Client from firecares.firestation.models import FireDepartment, FireStation, DataFeedback from firecares.firecares_core.tests.base import Bas...
3,175
958
from .gtkscheduler import GtkScheduler from .pygamescheduler import PyGameScheduler from .qtscheduler import QtScheduler from .tkinterscheduler import TkinterScheduler from .wxscheduler import WxScheduler __all__ = [ "GtkScheduler", "PyGameScheduler", "QtScheduler", "TkinterScheduler", "WxScheduler...
325
109
import map2annotation if __name__ == '__main__': map2annotation.main()
75
25
import dataclasses from dataclasses import dataclass @dataclass class RulePattern: id: str label: str pattern: str @property def as_dict(self): return dataclasses.asdict(self)
207
63
#!/usr/bin/python # ---------------------------------------------------------------------------- # cocos2d "install" plugin # # Authr: Luis Parravicini # # License: MIT # ---------------------------------------------------------------------------- ''' "run" plugin for cocos2d command line tool ''' __docformat__ = 'res...
1,014
292
import configparser class Configuration(): DefaultDic = {'windowDefault':{'HS' : 0,\ 'VS' : 0,\ 'energy' : 20,\ 'azimuth' : 0,\ 'scaleBarLength' : 5,\ ...
2,759
679
import datetime import json from flask import Response, request, Blueprint from flask_jwt_extended import jwt_required from flask_restplus import Api, Namespace, Resource, reqparse from sqlalchemy.exc import IntegrityError from api.core.db_execptions import bad_db_response from api.core.models import SensorInfoModel,...
4,772
1,312
# -*- coding: utf-8 -*- def slug2id(slug): return long(slug) - 110909 def id2slug(id): return id + 110909
116
60
import tkinter, hashlib root = tkinter.Tk() root.title("Hash Calculator") label = tkinter.Label(text="Write the string to hash") label.pack() option = tkinter.StringVar() option.set("sha224") string = tkinter.StringVar() entry = tkinter.Entry(root, textvariable=string, width=150, justify="center") entr...
995
374
# Bring in all of the public TensorFlow interface into this # module. # pylint: disable=wildcard-import from tensorflow.python import *
136
40
# -*- coding: utf-8 -*- # Copyright 2016 Dana James Traversie and Check Point Software 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:/...
4,337
1,224
# -*- coding: utf-8 -*- from channels.staticfiles import StaticFilesConsumer from tandlr.notifications import consumers channel_routing = { 'http.request': StaticFilesConsumer(), # Wire up websocket channels to our consumers: 'websocket.connect': consumers.ws_connect, 'websocket.receive': consumers....
387
126
from collections import defaultdict, Counter from itertools import product import re with open('03.txt') as fd: inp = [] for l in fd.readlines(): groups = re.findall(r'\d+', l) inp.append(list(map(int, groups))) claims = defaultdict(int) for (id, l,t, w,h) in inp: for y in range(t,t+h): ...
646
291
import os import sys import logging import boto3 def handler(event, context): logger = setup_logging(context.aws_request_id) logger.setLevel(logging.INFO) logger.info('## ENVIRONMENT VARIABLES') logger.info(os.environ) logger.info('## EVENT') logger.info(event) count = '1' CLUSTER_NAME = os.environ...
2,591
893
# # Copyright John Reid 2010 # """ Code to deal with the Bergman curated set of fly motifs. """ import os, biopsy.data as D, numpy as N import xml.etree.ElementTree as ET def xms_filename(): "@return: The filename of the XMS file where the motifs are stored." return os.path.join(D.data_dir(), "Bergman-Fly-M...
4,478
1,625
"""Holds the HTTP handlers for the addressbook app.""" from django import db from django import http from django.views import generic import json from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from addressbook import models JSON_XSSI_PREFIX = ")]}'\n" ...
7,950
2,302
from django.http import HttpResponseRedirect from django.urls import reverse from django.utils.translation import gettext_lazy as _
132
33
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import tensorflow as tf import keras import os print(os.listdir("../input")) print("Success") # Any results you write to the current directory are saved as output. # importing models/layers from keras.models ...
1,124
389
"""remove unique constraint from user table Revision ID: 29e48091912e Revises: f73df8de1f1f Create Date: 2021-12-22 22:26:20.918461 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '29e48091912e' down_revision = 'f73df8de1f1f' branch_labels = None depends_on = N...
1,194
452
'''ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F import math class BasicBlock(nn.Module...
6,065
2,329
import json from django import forms from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.exceptions import ValidationError from django.db.models import F from django.db.models.functions import ACos, Cos, Radians, Sin import requests from bc.recruitment.constants import J...
5,159
1,483
import argparse import os import shutil import time, math, datetime, re from collections import OrderedDict import torch import torch.nn as nn import torch.nn.parallel import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torchvision.transform...
7,264
2,442
import matplotlib.pyplot as plt import numpy as np from visHullTwoD import Scene, SegmentType #%% def doubleFaceTest(f): doubleFace = False origHE = f.halfEdge he = f.halfEdge.next while he != origHE: if f.index != he.leftFace.index: doubleFace = True break he =...
10,017
4,998
import numpy as np from scipy.sparse import issparse from sklearn.utils import sparsefuncs import anndata from typing import Union from ..dynamo_logger import LoggerManager, main_tqdm from ..utils import copy_adata def lambda_correction( adata: anndata.AnnData, lambda_key: str = "lambda", inplace: bool = ...
5,966
1,738
#!/usr/bin/env nemesis # # ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # Charles A. Williams, GNS Science # Matthew G. Knepley, University at Buffalo # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://g...
4,095
1,172
# util functions about data from scipy.stats import rankdata, iqr, trim_mean from sklearn.metrics import f1_score, mean_squared_error import numpy as np from numpy import percentile def get_attack_interval(attack): heads = [] tails = [] for i in range(len(attack)): if attack[i] == 1: ...
3,551
1,364
import gym, random, copy, string, uuid import numpy as np rddl_template = string.Template(''' non-fluents nf_sysadmin_inst_$uid { domain = sysadmin_mdp; objects { computer : {$objects}; }; non-fluents { REBOOT-PROB = $reboot_prob; $connections }; } instance sysadmin_inst_$uid { domain = sysadmin_mdp; non...
5,654
2,472
import torch import torch.optim as optim from transformers import AutoTokenizer from .utils import epsilon_greedy_transform_label, uid_variance_fn, OPTIMIZER_DIC import pytorch_lightning as pl class RLLMLightningModule(pl.LightningModule): def __init__( self, model, action_table: torch.Lon...
3,974
1,208
from unittest import TestCase from elastic_workplace_search.client import Client class TestClient(TestCase): dummy_authorization_token = 'authorization_token' def setUp(self): self.client = Client('authorization_token') def test_constructor(self): self.assertIsInstance(self.client, Clie...
324
93
from neotext.lib.neotext_quote_context.quote import Quote t0 = Quote( citing_quote="""<p>I am sick and tired of watching folks like Boris Johnson, Marine Le Pen, Donald Trump and others appeal to the worst racial instincts of our species, only to be shushed by folks telling me that it&#8217;s not <i>really</i> rac...
4,437
1,483
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Test suite for the daily average Toggl API process.""" from random import random from tempfile import NamedTemporaryFile from time import sleep, time from unittest import TestCase from recipes.imperative_vs_reactive.get_daily_average_imp import \ get_avg_daily_wor...
3,590
1,571
# Copyright 2013 Oscar Araque # # 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 writin...
4,077
1,291
import os import datetime import secrets import json from flask import Flask, abort, request, jsonify from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from werkzeug.security import safe_str_cmp from flask_stateless_auth import ( StatelessAuthError, Sta...
7,623
2,499
from microbit import * import music A = False B = False PITCH = 440 # PIN2 read_analog() ACTION_VALUE = 50 VOLUMEUP_VALUE = 150 VOLUMEDOWN_VALUE = 350 #nothing: 944 prev_l = False prev_r = False l = False r = False while True: v = pin2.read_analog() if v < ACTION_VALUE: l,r = True, True elif v <...
920
367
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('comments', '0003_comment_public'), ] ...
1,062
303
# Generated by Django 3.1.5 on 2021-05-02 05:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hospital', '0010_appointment_finished'), ] operations = [ migrations.RemoveField( model_name='a...
1,096
322
try: print(5/0) except ZeroDivisionError: print('你是啥子吗!') else: print('算了')
87
43
import pdbCleanup as pc import fxndefinitions as f import numpy as np from numpy.linalg import eig pc.takeInput1() DataFrame1 = [] pc.CsvToDataframe(DataFrame1) pc.takeInput2() DataFrame2 = [] pc.CsvToDataframe(DataFrame2) xtil = [0, 0, 0] ytil = [0, 0, 0] x = np.array(DataFrame1) y = np.array(DataFrame2) # This f...
1,924
958
# l1 = [1095, 1094, 1095] # del l1[:] # l1.extend([1005, 1094, 1095]) # print(l1) l1 = [8676, 4444, 3333, 2222, 1111] for i, n in enumerate(l1): print(i, n) if int(n / 1000) == 1: l1[i] = n + 8000 elif int(n / 1000) == 2: l1[i] = n + 6000 elif int(n / 1000) == 3: l1[i] = n + 40...
626
386