text
string
size
int64
token_count
int64
from typing import Container from asts.typed import Name as TypedName from asts import base, visitor, types_ as types PREDEFINED_TYPES: Container[str] = ( ",", "->", "Bool", "Float", "Int", "List", "String", "Unit", ) def resolve_type_vars( node: base.ASTNode, defined_types: ...
3,399
1,072
# -*- coding: utf-8 -*- """ cdist-plugin implementation. Author: Andrea Cervesato <andrea.cervesato@mailbox.org> """ import pytest from cdist import __version__ from cdist.redis import RedisResource from cdist.resource import ResourceError def pytest_addoption(parser): """ Plugin configurations. """ ...
3,533
993
# Copyright 2015 Rackspace, 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 writin...
2,851
855
#!/usr/bin/python # -*- coding: utf-8 -*- from cloudshell.cli.service.cli_service_impl import CliServiceImpl from cloudshell.huawei.cli.huawei_cli_handler import HuaweiCli, HuaweiCliHandler from cloudshell.huawei.wdm.cli.huawei_command_modes import ( WDMConfigCommandMode, WDMEnableCommandMode, ) class Huawei...
1,150
375
# Generated by Django 2.2.7 on 2019-11-20 14:10 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
1,510
410
# 二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)。 # # 每个 LED 代表一个 0 或 1,最低位在右侧。 # # # # 例如,上面的二进制手表读取 “3:25”。 # # 给定一个非负整数 n 代表当前 LED 亮着的数量,返回所有可能的时间。 # # 案例: # # 输入: n = 1 # 返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"] #   # # 注意事项: # # 输出的顺序没有要求。 # 小时不会以零开头,比如 “01:00” 是不允许的...
980
657
from __future__ import division, print_function, absolute_import import numpy as np import torch, sys import os.path as osp from torchreid import metrics from torchreid.losses import TripletLoss, CrossEntropyLoss from torchreid.losses import ClassMemoryLoss from ..engine import Engine from ..pretrainer impo...
22,340
7,167
from setuptools import setup setup( name="cartotools", version="1.2.1", description="Making cartopy suit my needs", license="MIT", packages=[ "cartotools", "cartotools.crs", "cartotools.img_tiles", "cartotools.osm", ], author="Xavier Olive", install_requi...
337
116
""" Functional testing for /models/* endpoints. """ import os import json import importlib import logging import pytest from pytest_bdd import scenario, given, then, when from fastapi.testclient import TestClient import app.main from app.tests import load_sqlalchemy_response_from_json from app.tests import load_json_fi...
2,623
786
from django.contrib import admin from Module_DeploymentMonitoring import views from django.urls import path,re_path urlpatterns = [ path('instructor/ITOperationsLab/setup/awskeys/',views.faculty_Setup_GetAWSKeys,name='itopslab_setup_AWSKeys'), path('instructor/ITOperationsLab/monitor/',views.faculty_Monitor_Ba...
3,144
1,055
class Akash(): msg=""" Seems like you are in trouble now. I can feel that...hahaaa Your name:Akash Address:Nepalgunj """ another=""" I am not really good friend of yours becauase i am going transfer some viruses from the internet.\n ...
2,918
629
from django.contrib.auth.models import User from django.db import models from mainapp.functions.search import params_to_search_string, search_string_to_params from mainapp.functions.search_notification_tools import ( params_to_human_string, params_are_equal, ) class UserAlert(models.Model): user = models...
1,312
390
#!/usr/bin/env python # # fatdisk.py - Unit test cases for COT.helpers.fatdisk submodule. # # March 2015, Glenn F. Matthews # Copyright (c) 2014-2017 the COT project developers. # See the COPYRIGHT.txt file at the top-level directory of this distribution # and at https://github.com/glennmatthews/cot/blob/master/COPYRIG...
8,123
2,521
#!/usr/bin/env python import baxter_interface import rospy if __name__ == '__main__': rospy.init_node("set_left_arm_py") names = ['left_e0', 'left_e1', 'left_s0', 'left_s1', 'left_w0', 'left_w1', 'left_w2'] joints = [-0.8022719520640714, 1.7184419776286348, 0.21399031991001521, 0.324436936637765, 2.586291...
541
303
#------------------------------------------------------------------------------ # Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # Sess...
4,414
1,158
"""Reward wrapper that gives rewards for positive change in z axis. Based on MOPO: https://arxiv.org/abs/2005.13239""" from gym import Wrapper class JumpWrapper(Wrapper): def __init__(self, env): super(JumpWrapper, self).__init__(env) self._z_init = self.env.sim.data.qpos[1] def step(self...
536
189
import matplotlib.pyplot as plt import numpy as np import cv2 from thresholding import * # list of lists def plot_images_along_row(images): fig = plt.figure() rows = len(images) cols = len(images[0]) i = 0 for row in range(rows): for col in range(cols): a = fig.add_subplot(row...
2,102
921
import signal import ConfigParser def get_config(): conf = ConfigParser.ConfigParser() conf.read("config.cfg") name = conf.get("test", "name") print(name) def update_config(signum, frame): print("update config") get_config() def ctrl_c(signum, frame): print("input ctrl c") exit(1) ...
479
183
#!/usr/bin/env python # coding: utf-8 # In[ ]: import flask from flask import request, jsonify import time import sqlite3 import random # import the necessary packages from keras.preprocessing.image import img_to_array from keras.models import load_model from keras import backend from imutils import build_montages ...
5,602
1,747
from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.models import User from rest_framework import permissions, status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from .serialize...
1,917
526
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .filter_tweets import filter_tweets_from_directories from .filter_tweets import filter_tweets_from_files from .download_tweets import get_tweets_by_user from .embed_tweets import SentenceEncoder from .embed_tweets import embed_tweets_from_file from .embed_tweets impor...
352
128
from django.db import models from scenarios.models import ScenarioData # Create your models here. class scpData(models.Model): velocidade = models.DecimalField(max_digits=5, decimal_places=1) scenario = models.ForeignKey(ScenarioData, null=True) num_teste = models.SmallIntegerField() descricao_erro = models....
2,132
824
import logging from flask import Flask, render_template, request, redirect, flash, session, jsonify from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, LoginManager, login_user, logout_user from datetime import datetime from passlib.hash import sha256_crypt import msnotifier.bot.siteMonitor as s...
19,230
6,112
import sys, os import gym import gym_urbandriving as uds import cProfile import time import numpy as np import pickle import skimage.transform import cv2 import IPython import pygame from random import shuffle from gym_urbandriving.agents import KeyboardAgent, AccelAgent, NullAgent, TrafficLightAgent#, RRTAgent from g...
2,344
647
import os import tempfile import time import urllib import urllib.parse import pexpect import maccli.dao.api_instance import maccli.helper.cmd import maccli.helper.simplecache import maccli.helper.metadata from maccli.helper.exception import InstanceDoesNotExistException, InstanceNotReadyException def list_instance...
12,319
3,457
""" The 'helpers' module provides various helper functions. """ import getpass import json import os import subprocess import sys from odml import fileio from odml.dtypes import default_values from odml.tools.parser_utils import SUPPORTED_PARSERS from .treemodel import value_model try: # Python 3 from urllib.p...
5,741
1,751
# Copyright 2019 Huawei Technologies Co., Ltd # # 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...
3,511
1,066
import re from CGATReport.Tracker import * from CGATReport.Utils import PARAMS as P # get from config file UCSC_DATABASE = "hg19" EXPORTDIR = "export" ################################################################### ################################################################### ##############################...
2,264
725
from typing import List class Solution: def sumEvenAfterQueries(self, A: List[int], queries: List[List[int]]) -> List[int]: even_sum = sum(num for num in A if not num & 1) result = [] for val, idx in queries: if not A[idx...
512
150
import csv # Finding States' Laziness Rankings: # dataDict = {} with open('data.csv', 'rU') as csvfile: dataReader = csv.reader(csvfile, delimiter=',') for row in dataReader: state = row[0] row.pop(0) dataDict[state] = row projectedmeans = [] with open('rafadata.csv', 'rb') as csvfile: dataReader = csv....
7,400
2,534
#/bin/python3 import numpy as np from PIL import Image def processbad(array): #arr = np.zeros([array.size(),array[0].size(),array[0][0].size]) arr = np.zeros([int(np.size(array)/8), int(np.size(array[0])/8),3], dtype=np.byte) # print (arr) counter = 0 count = 0 for i in array: ...
1,540
602
import click from esque import validation from esque.cli.autocomplete import list_topics from esque.cli.helpers import edit_yaml, ensure_approval from esque.cli.options import State, default_options from esque.cli.output import pretty_topic_diffs from esque.resources.topic import copy_to_local @click.command("topic"...
1,290
390
# -*- coding: utf-8 -*- """Main entry point into euporie.""" from euporie.app import App if __name__ == "__main__": App.launch()
134
53
# Original work Copyright 2018 Brainwy Software Ltda (Dual Licensed: LGPL / Apache 2.0) # From https://github.com/fabioz/pyvmmonitor-core # See ThirdPartyNotices.txt in the project root for license information. # All modifications Copyright (c) Robocorp Technologies Inc. # All rights reserved. # # Licensed under the Ap...
9,535
2,691
version_info = (0, 5, 2)
25
15
""" ``hippynn`` currently has interfaces to the following other codes: 1. ``ase`` for atomic simulation 2. ``pyseqm`` for combined ML-seqm models 3. ``schnetpack`` for usage of schnet models in ``hippynn``. This subpackage is not available by default; you must import it explicitly. """
291
88
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Author: ClarkYAN -*- import requests def set_up_connection(url, sender): # files = {'dataset': open(filename, 'rb')} user_info = {'name': sender} r = requests.post(url, data=user_info, headers={'Connection': 'close'}) if r.text == "success": ...
459
155
""" use of script to create the login method use a fake account! """ from selenium import webdriver from time import sleep from bs4 import BeautifulSoup as bs class Login: def __init__(self, email, password, idPage): self.browser = webdriver.Chrome('/home/ekoar/chromedriver') self.email = email ...
1,553
535
# -*- coding: utf-8 -*- import joblib import torch import numpy as np from ntee.utils.my_tokenizer import RegexpTokenizer from ntee.utils.vocab_joint import JointVocab from ntee.utils.vocab import Vocab class ModelReader(object): def __init__(self, model_file): model = joblib.load(model_file, mmap_mode='r...
4,699
1,480
from setuptools import setup import importlib version = importlib.import_module('sputr.config').version setup( name='sputr', version=version, description='Simple Python Unit Test Runner', long_description="An intuitive command line and Python package interface for Python's unit testing framework.", ...
1,479
431
#!/usr/bin/env python3 # Copyright 2018-2021 VMware, Inc., Microsoft Inc., Carnegie Mellon University, ETH Zurich, and University of Washington # SPDX-License-Identifier: BSD-2-Clause import matplotlib import matplotlib.pyplot as plt import numpy as np import re #import json def parse_one_histogram(line): #retur...
1,820
673
# -*- coding: utf-8 -*- """ oy.models.mixins.polymorphic_prop ~~~~~~~~~~ Provides helper mixin classes for special sqlalchemy models :copyright: (c) 2018 by Musharraf Omer. :license: MIT, see LICENSE for more details. """ import sqlalchemy.types as types from sqlalchemy import literal_column, ev...
4,587
1,438
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
1,735
526
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test Project Template The code below is derived from several locations: REFERENCES: REF1: https://docs.pytest.org/en/latest/contents.html REF2: https://github.com/hackebrot/pytest-cookies LOCATIONS LOC1: https://github.com/audreyr/cook...
5,487
1,540
import json from msilib.schema import Directory import pandas as pd import csv with open('./result-#succubus Drawings, Best Fan Art on pixiv, Japan-1647491083659.json', 'r',encoding="utf-8") as f: data = json.load(f) Tags_Directory = {} print(f"已經捕捉到{len(data)}條信息,準備將tag新增到字典……") n = len(data) for i in range(0,n): ...
2,053
925
from abc import abstractmethod from typing import Dict, Tuple from curse_manager import CursesManager from telegram import TelegramBot class VoyagerEventHandler: """ A base class for all event handlers to inherit from. To handle an incoming event from voyager application server, Most important method is...
3,583
969
from django import forms from django.utils.encoding import force_text from django.utils.translation import pgettext, ugettext_lazy as _ from fluent_contents.extensions import ContainerPlugin, plugin_pool, ContentItemForm from . import appsettings from .models import BootstrapRow, BootstrapColumn GRID_COLUMNS = appset...
3,063
1,001
import logging import json from datetime import datetime, timedelta from getpass import getpass import uuid import requests from Cryptodome.PublicKey import RSA import utils NONE, SIGN, TICKET = 0, 1, 2 SERVER = 'https://appstudentapi.zhihuishu.com' SSL_VERIFY = True TAKE_EXAMS = True SKIP_FINAL_EXAM = False EXAM_AU...
8,083
2,832
import autogl if autogl.backend.DependentBackend.is_dgl(): from ._base_feature_engineer_dgl import BaseFeatureEngineer else: from ._base_feature_engineer_pyg import BaseFeatureEngineer class BaseFeature(BaseFeatureEngineer): ...
244
81
import os import urllib.request from flask import Flask, request, redirect, render_template, jsonify from flask import Blueprint, request, current_app as app from controllers.sc_judgment_header_ner_eval import SC_ner_annotation import json from models.response import CustomResponse from models.status import Status ner_...
1,440
436
import sys import os import unittest import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging import numpy as np # # HandGenerator # class HandGenerator(ScriptedLoadableModule): def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = "Hand ...
4,594
1,428
from django.urls import path from . import views urlpatterns = [ path('movie/', views.MovieListView.as_view()), path('movie/<int:pk>/', views.MovieDetailView.as_view()), path('review/', views.ReviewCreateView.as_view()), ]
238
80
import re import uuid import time from typing import (Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union, Text) def camelcase_to_snakecase(_str: str) -> str: """camelcase_to_snakecase. Transform a camelcase string to snakecase Args: _str (str): String to apply ...
1,166
414
#!/usr/bin/env python3 # Pesquisa binaria # Read num = int(input("Number to find the sqrt of? ")) index = 0 step = num / 2 prox = True while abs(index * index - num) > 1e-10: if (prox): index += step else: index -= step step = step / 2 if (index * index) < num: prox = True ...
434
165
import pandas as pd import os import random class MakeDataset(): def __init__(self, known=30, predict=7, ratio=0.4, path=None): # ratio means the valid/(train + valid) assert path is not None, "The path is invalid" self.df = pd.read_excel(path) self.columns = self.df.columns ...
2,625
820
from math import sqrt from numpy import matrix from intpm import intpm A = matrix([[1, 0, 1, 0], [0, 1, 0, 1]]) b = matrix([1, 1]).T c = matrix([-1, -2, 0, 0]).T mu = 100 x1 = 0.5 * (-2 * mu + 1 + sqrt(1 + 4*mu*mu)) x2 = 0.5 * (-mu + 1 + sqrt(1 + mu * mu)) x0 = matrix([x1, x2, 1 - x1, 1 - x2]).T intpm(A, b, c, x0, ...
326
183
import psycopg2 # encoding=utf-8 __author__ = 'Hinsteny' def get_conn(): conn = psycopg2.connect(database="hello_db", user="hinsteny", password="welcome", host="127.0.0.1", port="5432") return conn def create_table(conn): cur = conn.cursor() cur.execute('''CREATE TABLE if not exists COMPANY ...
2,205
828
# # PySNMP MIB module DHCP-Server-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DHCP-SERVER-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:31:49 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
21,351
9,033
from cv_utils.object_detection.dataset.converter import coco_to_yolo from cv_utils.object_detection.dataset.converter import yolo_to_coco ''' COCO --> YOLO This code uses the ultralytics/yolov5 format. The converted dataset will be saved as follow: - {output_folder} - images - {output_set_name} ...
1,603
592
from django.db import models from django.contrib import admin from .country import Country from .filter import Filter from .setting import Setting from .site import Site class Keyword(models.Model): site = models.ForeignKey('Site') phrase = models.CharField(max_length=50) feed_url = models.CharField( ...
2,369
740
# -*- coding: utf-8 -*- # Copyright 2017 Chris Meyers <cmeyers@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (...
4,262
1,306
import time from flask import render_template, flash, redirect, url_for from flask.globals import request from flask_login.utils import logout_user from werkzeug.urls import url_parse # from flask.helpers import flash # 闪动消息 from app import app, db # 第二个 app 是 init文件里的app 对象 from app.forms import LoginForm, Registratio...
2,781
1,070
import math from collections import OrderedDict import json from asr_deepspeech.decoders import GreedyDecoder import os from ascii_graph import Pyasciigraph from asr_deepspeech.data.loaders import AudioDataLoader from asr_deepspeech.data.samplers import BucketingSampler from .blocks import * from asr_deepspeech.data.da...
10,501
3,179
n,k = [int(x) for x in input().split()] arr = [int(x) for x in input().split()] arr.sort() total = 0 for i in range(k): if arr[i] < 0: total += -arr[i] print(total)
179
80
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\ensemble\ensemble_interactions.py # Compiled at: 2016-07-13 03:28:12 # Size of source mod 2**32: 107...
1,099
402
import socket from typing import Optional, List __version__ = '0.1.0' class ICMPv6Socket(socket.socket): # From https://elixir.bootlin.com/linux/v4.18/source/include/linux/socket.h#L312 SOL_ICMPV6 = 58 # type: int # From https://elixir.bootlin.com/linux/v4.18/source/include/uapi/linux/icmpv6.h#L139 ...
1,663
577
"""Game map resource manager.""" __all__ = ("get_map_template",) _cache = {} def get_map_template(name: str): """ Get a map template by its ``name``. Returns ``None`` if not found. Loaded :class:`MapTemplate` will be cached until the application exits. :param name: name of the map template. ...
603
189
from evaluation_framework.manager import FrameworkManager if __name__ == "__main__": evaluation_manager = FrameworkManager() evaluation_manager.evaluate( "objectFrequencyS.h5", vector_file_format="hdf5", debugging_mode=False )
248
70
from django.conf import settings from django.contrib import messages as django_messages from django.urls import reverse_lazy from django.utils.decorators import method_decorator from django.views.decorators.http import require_POST from django.views.generic.base import RedirectView, TemplateView from django.views.gener...
7,127
1,960
from MakeYourOwnGraph import * #user needs to import this line def F1(x,y): if x<=2: return 1 else: return F1(x-1,y)+F1(x-2,y) GraphOfMyAlgo(F1,2,[1,30,2,31]) #user needs to execute this line in his or her algorithm where the first argument is the name of the Algorithm Function, here F1 ...
685
189
# The new robopilot training pipeline.
38
11
import sys from PySide2 import QtCore from PySide2 import QtWidgets from shiboken2 import wrapInstance import maya.OpenMayaUI as omui def mayaMainWindow(): """ Get maya main window as QWidget :return: Maya main window as QWidget :rtype: PySide2.QtWidgets.QWidget """ mainWindowPtr = omui.MQtUt...
1,257
384
import math from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag(takes_context=True) def buildfullurl(context, url): """Converts relative URL to absolute. For example: {% buildfullurl article.get_absolute_url %} or: ...
853
264
import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) def create_lists_of_users(): outgoing_callers = set() not_telemarketers = set() for idx, call in enumerate(calls): ...
967
351
""" [1,2,3,4]의 부분 배열은 다음과 같이 16개가 있습니다. [] [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [1, 2, 4] [1, 3] [1, 3, 4] [1, 4] [2] [2, 3] [2, 3, 4] [2, 4] [3] [3, 4] [4] 처음에 있는 blank list([])의 값을 0으로 계산하면 모든 부분 배열의 합(subarray sum)은 80입니다. 숫자로 된 배열을 입력 받아서, 부분 배열의 합을 구하여 보세요. Input 숫자로 된 배열이 입력됩니다. 숫자는 정수입니다. Output 부분 배열의 합을 출력합...
971
597
"""Command line interface to the fastlite package """ import sys import argparse from .fastalite import fastalite, fastqlite, Opener from . import __version__ def count(seqs, fname): i = 1 for i, seq in enumerate(seqs, 1): pass print(('{}\t{}'.format(fname, i))) def names(seqs, fname): fo...
1,683
532
""" *Major Key* """ from abc import ABCMeta from ._key import ModedKey class MajorKey( ModedKey, ): __metaclass__ = ABCMeta
142
58
"""Simple python clients for the Gravitate BestBuy Services""" __version__ = "0.1.18" from .fc import get_fc_service from .ims import get_ims_service
151
51
#!/usr/bin/python3 # -*- coding: utf-8 -*- from libGamePiratesAndFishers import assertIfIsWeelFormat,makeSureThatIsnumberLimited class Individual(object): """ This class Define object type Individual, it is a base for object used for being the base of fishers, and is used for enemies in application. """ def ...
9,482
3,772
#!/usr/bin/env python3 """ Author : FabrizioPe Date : 2021-02-10 Purpose: Find and replace vowels in a given text """ import argparse import os # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Apple...
1,544
456
import pandas as pd from openpyxl import worksheet def map_team_names(names_sheet: worksheet, games_sheet: worksheet): mapped_names = [] missing_names = set() names_last_row = names_sheet.max_row for row in range(1, names_last_row): team_name = names_sheet.cell(row, 1).value if team_...
1,434
465
from django.core.mail import send_mail from django.http import Http404 from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User from django.utils.datastructures import MultiValueDictKeyError from django.utils import timezone from django.contrib.auth i...
8,889
2,668
def str2sec(string): if len(string.split(':')) == 3: hours, mins, secs = map(int, string.split(':')) elif len(string.split(':')) == 2: mins, secs = map(int, string.split(':')) hours = 0 else: raise ValueError('string must have the form [hh:]mm:ss : ' + str(string)) second...
1,941
644
# Adafruit CircuitPython 2.2.0 # Adafruit CircuitPlayground Express import board ; import neopixel; import time pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.2) pixels.fill((0,0,0)) pixels.show() def blue(): pixels.fill((0,0,22)) def magenta(): pixels.fill((22,0,22)) blue(); pixels.show(); t...
415
175
# Generated by Django 2.1.15 on 2021-03-15 15:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('indent', '0002_auto_20210314_2324'), ] operations = [ migrations.AddField( model_name='indentmaster', name='note', ...
385
139
''' File: lotka-volterra.py Authors: - Sjoerd Wenker, 10617558 - Tristan van Vaalen, 10551832 Contains a Lotka-Volterra Model which is simulated using the RK4 method. ''' from integration import RungeKutta4 import matplotlib.pyplot as plt from matplotlib.widgets import Slider ''' Method that simulates a Lotka-Volte...
2,310
921
#!/usr/bin/env python3 # Common Imports import io import rospy import sys import unittest # Specific Imports import time import wave from harmoni_common_lib.action_client import HarmoniActionClient from harmoni_common_lib.constants import ActionType, DetectorNameSpace, SensorNameSpace, State from audio_common_msgs.m...
3,717
1,210
# coding: utf-8 from __future__ import absolute_import, unicode_literals from optparse import make_option import time from django import VERSION from django.core.management.base import NoArgsCommand from smoked import default_registry from smoked.runner import run_tests stats_msg = """ Results ======= Total: {total}...
2,196
630
''' Testing your data with asserts Here, you'll practice writing assert statements using the Ebola dataset from previous chapters to programmatically check for missing values and to confirm that all values are positive. The dataset has been pre-loaded into a DataFrame called ebola. In the video, you saw Dan use the ....
1,735
467
COLLIDER_SUITE_OFFSHOOT_RANGE = (0, 100) COLLIDER_SUITE_SPLIT_ABS_RANGE = (0, 10) COLLIDER_SUITE_SPLIT_REL_RANGE = (-1, 1, 2) COLLIDER_SUITE_ASSIMILATE_SIZE_RANGE = (0, 10) TAPE_FRAME_SEARCH_LIMIT_RANGE = (1, 100000) TAPE_PIXEL_SEARCH_LIMIT_RANGE = (1, 1000000) DEFAULT_CALIBRATION_ENCLOSURE_SIZE_RANGE = (0, 1000) COLL...
623
393
from ._http import (HTTPClient, get_id, Route, GET, PUT, DELETE, ) import asyncio class Me: def __init__(self, _http: HTTPClient): self.http = _http self.request = _http.request ...
6,084
1,742
import json def load_extensions_from_json(): try: extensions = json.load(open("extensions.json")) except FileNotFoundError: return for ext in extensions: __import__(f"iiif_prezi3.extensions.{ext}") def load_extension(path): pass def monkeypatch_schema(schema_class, patch_c...
582
186
# Copyright 2019 Spotify AB # # 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...
1,237
392
# Generated by Django 2.2.4 on 2019-08-10 14:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0014_post_imgdata'), ] operations = [ migrations.AlterField( model_name='post', name='imgdata', ...
395
135
#!/usr/bin/env python3 import tkinter as tk from tkinter import filedialog from tkinter import messagebox from tkinter import ttk import os import sys print_n = sys.stdout.write STAT_TXT = ("ST", "MA", "VI", "AG") # Characters CHAR_OFFSET = "0x24" CHAR_ID = ("0x75", 2) CHAR_LVL = ("0x79", 1) CHAR_EXP = ("0x7C", 2) ...
71,385
31,011
import json import matplotlib.animation as animation import matplotlib.pyplot as plt import numpy as np import scipy.signal as signal import yaml from mpl_toolkits.mplot3d.axes3d import Axes3D from scipy.interpolate import interp1d from tf_pwa.config_loader import ConfigLoader from tf_pwa.experimental.extra_amp impor...
6,692
3,072
''' A script for accessing visualization data (saving images at validation steps during training) and saving them to a local directory. ''' import pymongo as pm import pickle import os import gridfs import cPickle import numpy as np from PIL import Image dbname = 'future_pred_test' collname = 'asymmetric' port = 27017...
3,316
1,377
""" BASICS Creates the necessary tables and users. """ import os import psycopg2 con = psycopg2.connect (host = os.environ["POSTGRES_URL"], database = os.environ["POSTGRES_DB"], user = os.environ["POSTGRES_USER"], password = os.environ["POSTGRES_PASSWORD"]) cur = con.cursor() # Creates main user table cur.execut...
1,543
520
from collections import defaultdict computing_graph = defaultdict(list)#defaultdict(list),会构建一个默认value为list的字典, """ for (key, value) in data: result[key].append(value) print(result)#defaultdict(<class 'list'>, {'p': [1, 2, 3], 'h': [1, 2, 3]}) """ n = 'p' m = [1,2,23] computing_graph[n].append(m) print(...
338
149
#!/usr/bin/env python3 from botlib.curl import Curl from botlib.html2list import HTML2List, MatchGroup URL = 'https://www.vice.com/en/topic/motherboard' SOURCE = Curl.get(URL, cache_only=True) SELECT = '.vice-card__content' match = MatchGroup({ 'url': r'<a href="([^"]*)"', 'title': r'<h3[^>]*><a [^>]*>([\s\S]...
597
258