text
string
size
int64
token_count
int64
"""Script to run camera calibration""" from camera import Camera camera = Camera(source_dir='/home/mce/Documents/bubble3D/calibration/Cam01', outfilename='Cam01', target_dir='results/camera', verbose=True) camera.calibrate() camera.compute_undistort()
270
84
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "MPZinke" ######################################################################################################################## # # # cre...
1,994
416
from flask import Flask from werkzeug.routing import BaseConverter class RegexConverter(BaseConverter): def __init__(self, url_map, *args): super(RegexConverter, self).__init__(url_map) self.regex = args[0] def to_python(self, value): """ 匹配到的值 :param value: :...
783
290
from pyfields import field from trend_analyze.src.validate import Validate from trend_analyze.config import * class EntityUrl: v = Validate().generate url: str = field(default=DEFAULT_ENTITY_URL, validators=v(is_blank=True, max_len=150), check_type=True) start: int = field(default=-1, check_type=True) ...
773
260
# -*- coding: utf-8 -*- """ Inheritance Diagram ------------------- .. inheritance-diagram:: kotti.testing """ import os from os.path import join, dirname from unittest import TestCase from pytest import mark from pyramid import testing from pyramid.events import NewResponse from pyramid.security import ALL_PERMISS...
8,148
2,557
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] result = [] queue = ...
694
203
# simple recursions def count_down(n): # print n, n-1, n-2, ... , 3, 2, 1 print(n, end=" ") if n > 1: # check for end case count_down(n-1) # do smaller problem print("-"*5, "count down from 10") count_down(10) print() print("-"*5, "count down from 5") count_down(5) print()
300
129
# Standard Python import copy # Thirdparty import numpy as np class Activation(): ''' Base class for an activation layer Inspired by https://github.com/eriklindernoren/ML-From-Scratch/blob/master/mlfromscratch/deep_learning/activation_functions.py ''' def __call__(self, x): return ...
1,513
544
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2019-07-23 22:47 # @Author : Simon Meng # @Site : # @File : mkdir.py # @Software: PyCharm import os # Make a folder under the current path def mkdir(path): folder = os.path.exists(path) if not folder: os.makedirs(path)
302
130
import os import sys header_file_fmt = "{name}_ocl.hpp" header_string = ( "#ifndef {definition}_OCL_HPP\n" "#define {definition}_OCL_HPP\n" "#include <opencv2/core/ocl.hpp>\n" "const cv::ocl::ProgramSource& {module}_{name}_ocl() {{\n" "static cv::ocl::ProgramSource source(\"{module}\", \"{name}\", \"{kernel}\", \"\");...
2,183
890
from lotto_game.lotto_game import LottoGame def main(): # Play Tickets LottoGame.acquire_tickets() # Do Extraction LottoGame.do_extraction() # Check Results LottoGame.check_results() if __name__ == "__main__": main()
251
93
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class MailMessage(models.Model): _inherit = 'mail.message' weixin_id = fields.Char('微信ID', required=False)
256
94
# ---------------------------------------------------------------------- # | # | BinaryStatementParserInfo.py # | # | David Brownell <db@DavidBrownell.com> # | 2021-10-12 13:55:27 # | # ---------------------------------------------------------------------- # | # | Copyright David Brownell 2021 # | Di...
2,361
592
__author__ = 'Daniel Kapellusch' import astropy.io.fits as fits import os import csv import json import sys import multiprocessing as mp #necessary imports. Note: this is written in python 2. from os import path import ConfigParser from os import system #necessary imports. Note: this is written in python 2. global pa...
10,947
3,631
import datetime import random from django.test import TestCase from django.utils.dateparse import parse_datetime from .models import Article class ArticleTestCase(TestCase): def setUp(self) -> None: self.article = Article.objects.create( source="HackerNews", author="Guido van Ro...
3,143
947
import nltk from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize from nltk.corpus import wordnet # TODO move cut words to config CUT_WORDS = ( "drop", "cut", "leave", "lose", "trim", "shed", "cast", "unload", "strike", "skip", "throw", "shake",...
2,648
800
Python 3.9.2 (v3.9.2:1a79785e3e, Feb 19 2021, 09:06:10) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license()" for more information. >>>
173
98
from __future__ import unicode_literals import boto import sure # noqa from nose.tools import assert_raises from boto.exception import BotoServerError from moto import mock_iam @mock_iam() def test_create_group(): conn = boto.connect_iam() conn.create_group('my-group') with assert_raises(BotoServerError...
2,144
779
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: unversioned Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "Licens...
2,955
912
import pytest from rampwf.utils.sanitize import _sanitize_input def test_sanitize_input(): _sanitize_input('Harmess code') msg = "forbidden key word open detected" with pytest.raises(RuntimeError, match=msg): _sanitize_input("with open('test.txt', 'wr') as fh") msg = "forbidden key word sca...
433
155
from django.apps import AppConfig class IssuesAppConfig(AppConfig): name = 'issues' verbose_name = 'Issues'
118
39
from Parser import Parser from LexicalAnalyzer import LexicalAnalyzer class FileNamePurifier: def __init__(self, stringAppendToFront, stringAppendToEnd, removeFirstInstanceOfStringsInList, removeAllInstancesOfStringsInList, substringsToPreserve, oldSeperators, seperatorToUse, breakUpBy...
2,018
557
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import numpy as np import torch def to_tensor(data): """ Convert numpy array to PyTorch tensor. For complex arrays, the real and im...
11,406
3,655
import doctest from migrate_exblog import entries_to_mt def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(entries_to_mt)) return tests
171
60
from .server import get_server_params, get_ssl_params, redirect_root_to_docs, start_model_server
97
31
import os import tempfile from types import TracebackType from typing import Any, BinaryIO, Optional, TextIO, Type, Union import yaml class StoredState: def __init__(self, state: "State") -> None: self.state = state if self.state.stored_name is not None: raise RuntimeError('You may on...
1,883
573
import numpy as np import cv2 def rem_multi_lines(lines, thresh): """ to remove the multiple lines with close proximity :param lines: initial list with all the lines(multiple in place of singular) :param thresh: dist between two lines for them to be considered as same :return: final list with sin...
2,711
1,046
# Before running this command, you should firstly run: # pip install fairseq # pip install fastBPE # wget https://dl.fbaipublicfiles.com/fairseq/models/lm/wmt19.en.tar.gz # tar zxvf wmt19.en.tar.gz import argparse from itertools import islice import numpy as np from fairseq.models.transformer_lm import TransformerLang...
1,553
589
import warnings from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from aioli.service import BaseService from aioli.controller import BaseHttpController from aioli.exceptions import NoMatchFound class OpenApiService(BaseService): _specs = {} def oas_schema(self, pkg): ...
2,742
667
import pandas as pd import plotly.graph_objs as go def load_data(): df = pd.read_csv("data/Data.csv") return df
124
47
import factory from faker import Faker from popup.models import Popup fake = Faker() class PopupFactory(factory.django.DjangoModelFactory): class Meta: model = Popup name = factory.LazyFunction(lambda: fake.word()) page = factory.LazyFunction(lambda: fake.word()) title = factory.LazyFunctio...
399
125
import os import glob import shutil import logging # logging.basicConfig(level=logging.DEBUG) # DEBUG:root:Skipping file /Users/hygull/Projects/Python3/DjangoTenantOracleSchemas/django-tenant-oracle-schemas/src/tenants/models.py # logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG) # 2019-06-2...
1,863
778
from typing import Callable, List, Union, Optional, Dict, Tuple import re import spacy import logging import math from enum import Enum logger = logging.getLogger(__name__) def remove_excess_space(inp: str) -> str: return ' '.join(inp.split()).strip() def get_spacy_model(model: str) -> spacy.language.Model: ...
6,075
1,865
""" ===== Distributed by: Notre Dame SCAI Lab (MIT Liscense) - Associated publication: url: https://arxiv.org/abs/2010.03957 doi: github: https://github.com/zabaras/transformer-physx ===== """ import logging import h5py import torch from .dataset_phys import PhysicalDataset from ..embedding.embedding_model import Embe...
2,106
683
import FWCore.ParameterSet.Config as cms #from ..modules.hltL1TkMuons_cfi import * from ..modules.hltL1TkSingleMuFiltered22_cfi import * from ..sequences.HLTBeginSequence_cfi import * from ..sequences.HLTEndSequence_cfi import * L1T_SingleTkMuon_22 = cms.Path( HLTBeginSequence + # hltL1TkMuons + hltL1TkSin...
359
154
import os import math import argparse import dbh_util as util from sklearn.ensemble import RandomForestClassifier parser = argparse.ArgumentParser() parser.add_argument('--n-estimators', type=int, default=10, help='The number of trees in the forest') parser.add_argument('--max-depth', type=int, default=5, help='Max d...
927
296
# Copyright 2017 - Nokia # # 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, sof...
9,476
3,180
import json import os import subprocess import sys TEST_FILENAME = "tmp_py_file" TEST_FOLDER = "clone_tests" TESTS = [ ("clone!( => move || {})", "If you have nothing to clone, no need to use this macro!"), ("clone!(|| {})", "If you have nothing to clone, no need to use this macro!"), ("cl...
4,137
1,332
from __future__ import unicode_literals from django.http import HttpRequest from django.template import Context, Template, TemplateSyntaxError from django.test import TestCase from snakeoil.models import SeoUrl from .models import TestModel class GetSeoDataTagTests(TestCase): def test_invalid_syntax(self): ...
2,437
717
from .trainers import * from .predictors import *
50
15
import torch from torch_geometric.nn import GravNetConv def test_gravnet_conv(): num_nodes, in_channels, out_channels = 20, 16, 32 x = torch.randn((num_nodes, in_channels)) conv = GravNetConv(in_channels, out_channels, space_dimensions=4, propagate_dimensions=8, k=12) assert co...
420
171
from datetime import datetime from hootpy import HootPy class CrossPlotter(HootPy): """ CrossPlotter Purpose: Handles the plotting of cross section products. Started: 14 June 2010 by Tim Supinie (tsupinie@ou.edu) Completed: [not yet] Modified: [not yet] """ def __init__(self,...
2,216
650
import logging import ldap from django.conf import settings from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from django_auth_ldap.backend import LDAPBackend from chiffee.models import User logger = logging.getLogger('syncldap') # This command synchronizes local data...
3,072
890
from ols import * from diagnostics import * from diagnostics_sp import * from user_output import * from twosls import * from twosls_sp import * from error_sp import * from error_sp_het import * from error_sp_hom import * from ols_regimes import * from twosls_regimes import * from twosls_sp_regimes import * from error_s...
598
197
from pytest import fixture from encountertk.e_model import EncounterModel, ps_encounter, mean_vol_encountered @fixture(scope='function') def EModel(): return EncounterModel(kernel=1,pop2c=[1],pop1c=[1])
209
72
import sys from collections import deque a, b, c = sys.stdin.read().split() def main(): deck = dict([("a", deque(a)), ("b", deque(b)), ("c", deque(c))]) p = "a" while True: if deck[p]: p = deck[p].popleft() else: return p.upper() if __name__ == ...
367
145
""" Runs LightGBM using distributed (mpi) training. to execute: > python src/pipelines/azureml/lightgbm_training.py --exp-config conf/experiments/lightgbm_training/cpu.yaml """ # pylint: disable=no-member # NOTE: because it raises 'dict' has no 'outputs' member in dsl.pipeline construction import os import sys import ...
16,504
4,558
from xml.etree import ElementTree as Et import pandas as pd import requests from twinfield.core import Base from twinfield.exceptions import ServerError from twinfield.messages import METADATA_XML class Metadata(Base): def __init__(self, access_token: str, code: str, company: str): """ This clas...
3,319
869
# Author: Artem Skiba # Created: 20/01/2020 from .dataset import FastDataset from .dataloader import get_dataloader __all__ = [ 'FastDataset', 'get_dataloader' ]
172
75
INIT = 1 REST = ['START_MODSAFE',[0,0]] NEUTRAL = ['START_MODSAFE',[1,INIT]] FDBK = ['START_MODSAFE',[2,INIT]] LIN = ['START_MODSAFE',[3,INIT]] SIN = ['START_MODSAFE',[4,INIT]] TYPES = {'Vconst':LIN,'Fconst':FDBK,'Zconst':NEUTRAL} try: import epz as tempEpz import inspect _,_,keys,_ = inspect.getargspec(...
5,053
1,893
import pytest from mock import patch from app.device.brakes import Brakes from app.utils.servo import Servo from app.utils.exceptions import InvalidArguments @patch.object(Servo, 'write') @patch.object(Servo, '__init__') def test_init_creates_servo_on_pin_21(servo_init_mock, servo_write_mock): servo_init_mock.ret...
1,177
453
from collections import Counter def top_3_words(text): text = text.lower() count = "" j = [] for u in text: if ord(u) > 96 and ord(u) < 123 or ord(u) == 39: count += u else: j.append(count) count = "" i = [] for k in j: temp = "" ...
601
226
'''Test package for robosync'''
33
11
#!/usr/bin/env python # coding: utf-8 """ create at 2017/11/22 by allen """ import re from flask import request, session, current_app from app.lib.constant import ResourceType from app.models.auth import Resource, role_resource, Role, user_role, User from app.lib.exceptions import AuthError, PermissionError cla...
4,921
1,375
class Solution(object): # Time Complexity: O(n) @staticmethod def plus_one(digits): keep_going = True for i, e in reversed(list(enumerate(digits))): if keep_going: if e == 9: digits[i] = 0 else: digits[i] +=...
656
204
from django.conf import settings from django.template.loader import render_to_string from vms import models def test_accept(client_admin_invite_factory, user_factory): """ Accepting the invitation should create a new client admin for the user who accepts. """ invite = client_admin_invite_factory(...
1,607
492
import base64 import os import asyncio from pbx_gs_python_utils.utils.Process import Process from osbot_aws.Dependencies import load_dependency def run(event, context): load_dependency("pyppeteer") # (on first run downloads a zip file from S3 to /tmp/lambdas-dependencies/pyppeteer/ whic...
3,489
836
""" Filter to convert results from network device show commands obtained from ios_command, eos_command, et cetera to structured data using TextFSM templates. """ from __future__ import unicode_literals from __future__ import print_function import os from textfsm.clitable import CliTableError import textfsm.clitable a...
2,757
825
#!/usr/bin/python import threading import Queue import serial import time from datetime import datetime from firebase import firebase import sqlite3 from datetime import datetime, timedelta from gpiozero import Button, LED #/////////////////////////////////////////// import firebase_admin from firebase_admin import c...
5,705
1,714
#-------------------------------------------------------------------------------------------------- # Function: look-for # Purpose: Loops through all AWS accounts and regions within an Organization to find a specific resource # Inputs: # # { # "view_only": "true|false", # "regions": ["us-east-1", ...] # } #...
3,204
851
import logging from typing import Any, Dict from pydantic import ValidationError from scrapy import Spider from scrapy.http import Response from opennem.pipelines.aemo.downloads import DownloadMonitorPipeline from opennem.schema.aemo.downloads import AEMOFileDownloadSection from opennem.utils.dates import parse_date ...
2,972
814
import wiringpi as pi pi.wiringPiSetupGpio() pi.pinMode(18, pi.PWM_OUTPUT) pi.pwmSetMode(pi.PWM_MODE_MS) pi.pwmSetClock(2) pi.pwmSetRange(192000) while True: for i in list(range(-90, 90, 10)) + list(range(90, -90, -10)): pi.pwmWrite(18, int(((i + 90) / 180 * (2.4 - 0.5) + 0.5) / 20 * 192000)) pi.delay(200)
319
188
import cv2 as cv from geometry_msgs.msg import Pose2D from vision_msgs.msg import (BoundingBox2D, Detection2D, Detection2DArray, ObjectHypothesisWithPose) THRESHOLD_MAX = 255 THRESHOLD = 240 class BlobDetector: def __init__(self): pass def detect_multi(self, images): ...
2,549
823
from setuptools import find_packages, setup setup( name="triplet-reid", version="0.1.0", description="Triplet-based Person Re-Identification", packages=find_packages(), )
188
62
import csv import sys from KafNafParserPy import KafNafParser from naflib import * woorden = [r['original'] for r in csv.DictReader(open("klimaatwoorden.csv"))] o = csv.writer(sys.stdout) o.writerow(["file", "sentence", "term", "text"]) for fn in sys.argv[1:]: naf = KafNafParser(fn) for klimaterm in find_te...
530
207
# coding=utf-8 from flask import Blueprint, render_template, redirect from controlers.user import UserCtr from libs.login import login_user, logout_user, current_user bp = Blueprint("user", __name__, url_prefix="/user") @bp.route("/login", methods=["GET"]) def login_form(): return render_template("user/login.htm...
1,127
370
#!/usr/bin/env python import vector import math, types, operator """ A sparse matrix class based on a dictionary, supporting matrix (dot) product and a conjugate gradient solver. In this version, the sparse class inherits from the dictionary; this requires Python 2.2 or later. """ class sparse(dict): """ A compl...
9,607
4,673
import re class BibRefParser: def __init__(self): self.reset() def reset(self, reference=''): self._ref = reference self.reference = reference self.title = '' self.authors = '' # publication date self.date = '' self.publisher = '' self...
7,557
2,362
#https://www.youtube.com/watch?v=f9PR1qcwOyg #create global convention import mysql.connector __cnx=None def get_sql_connection(): global __cnx if __cnx is None: __cnx = mysql.connector.connect(user='root', password='password', host='127.0.0.1', ...
392
132
import matplotlib.pyplot as plt def plot_gp(xtest, predictions, std=None, xtrain=None, ytrain=None, title=None, save_name=None): xtest, predictions = xtest.squeeze(), predictions.squeeze() fig, ax = plt.subplots() # Plot the training data if (xtrain is not None) and (ytrain is not None): ...
1,217
421
#!_PYTHONLOC # # (C) COPYRIGHT 2004-2021 Al von Ruff, Bill Longley and Ahasuerus # ALL RIGHTS RESERVED # # The copyright notice above does not evidence any actual or # intended publication of such source code. # # Version: $Revision$ # Date: $Date$ from isfdb import * from isfdblib impor...
2,780
880
import pyaudio import numpy as np import mixer class Sound(object): def __init__(self): self.p = pyaudio.PyAudio() self.mixers = [] self.streams = [] for i in range(self.p.get_device_count()-3): self.streams.append(SoundcardStream(self.p, i)) def start_...
2,154
652
""" From https://github.com/brechtm/rinohtype/blob/master/noxutil.py https://github.com/cjolowicz/nox-poetry/discussions/289 """ import json from collections.abc import Iterable from pathlib import Path from typing import Optional from urllib.request import urlopen, Request from poetry.core.factory import Factory f...
2,284
647
from django.contrib import admin from tbutton_web.tbutton_maker.models import Application, Button, DownloadSession, UpdateSession class DownloadSessionAdmin(admin.ModelAdmin): list_display = ['time', 'query_string'] admin.site.register(DownloadSession, DownloadSessionAdmin) class UpdateSessionAdmin(admin.ModelAdm...
423
110
#PASCALS TRIANGLE USING RECURSION def pascal(n): if n == 0: #if 0 number of rows return [] #return a null list elif n == 1: ...
1,359
363
#!/usr/bin/env python2.7 from __future__ import division import roslib import rospy import tf from nav_msgs.msg import Odometry from nav_msgs.msg import Path from geometry_msgs.msg import PoseStamped import numpy as np import pdb from message_filters import Subscriber, ApproximateTimeSynchronizer class GT_cleaner: ...
3,806
1,317
from datetime import datetime from gpiozero import DistanceSensor from garage_door import garage_door from garage_camera import garage_camera import MQTT_Config import paho.mqtt.client as mqtt from temp_sensor import temp_sensor from time import sleep """ GPIO pin assignments: relays range finder sensor (echo...
3,266
1,065
# encoding: utf-8 import os import time from multiprocessing import Pool, cpu_count from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import T...
5,887
1,898
from .hola import *
20
8
import collections class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: m = collections.Counter(nums1) result = [] for num in nums2: if num in m: result.append(num) if m[num] == 1: del m[num] else: m[num] -= 1 return r...
326
113
import numpy as np if __name__ == '__main__': try: f = open('test_file.txt', 'w') f.write('this is exception finally') except Exception as e: pass finally: f.close pass
217
72
import os store.set_global_value("ctrl-space", False) with open(os.path.expanduser("~/.config/polybar/keys.fifo"), "wb") as f: f.write(b"TITLE:\n") store.set_global_value("emacs-chain-keys", [])
198
80
from .field import Field # NOQA from .datetime_field import DateTime # NOQA from .date import Date # NOQA from .string import String # NOQA from .object import Object # NOQA from .list import List # NOQA from .polymorphic_object import PolymorphicObject # NOQA from .polymorphic_list import PolymorphicList # NOQ...
520
176
from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), path('logout/', views.logoutView, name='logout'), path('signup/', views.signup, name='signup'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}...
564
217
__version__ = "0.2" import threading import numpy as np import pygame from expyriment.stimuli import Canvas, Rectangle, TextLine from expyriment.stimuli._visual import Visual from expyriment.misc import constants lock_expyriment = threading.Lock() Numpy_array_type = type(np.array([])) class Scaling(object): """...
14,918
4,613
# -*- coding: utf-8 -*- ################################################################################ # Copyright 2014, Distributed Meta-Analysis System ################################################################################ """ This file provides methods for handling weighting across GCMs under delta meth...
3,528
1,741
from rest_framework import status from rest_framework.generics import RetrieveUpdateAPIView from rest_framework.response import Response from ecojunk.users.api.v1.serializers import UserSerializer class UserResource(RetrieveUpdateAPIView): serializer_class = UserSerializer def retrieve(self, request, *args,...
764
221
# encoding: utf-8 # pylint: disable=bad-continuation """ RESTful API Payments resources -------------------------- """ import logging from flask_login import current_user from flask_restplus_patched import Resource from flask_restplus._http import HTTPStatus from app.extensions import db from app.extensions.api impo...
2,905
821
import msgraphy_util import argparse from msgraphy import GraphApi def main(name, starts_with, exact, channels, folder): api = GraphApi(scopes=["Group.Read.All"]) response = api.team.list_teams(search=name, starts_with=starts_with, exact=exact) for team in response.value: print(f"{team.display_na...
1,616
483
import pygame as p from math import floor from copy import deepcopy import Tkinter, tkFileDialog root = Tkinter.Tk() root.withdraw() p.init() running = True tileWidth = 16 tileHeight = 16 mapWidth = 100 mapHeight = 100 camX = 0 camY = 0 scale = 2 uiScale = 2 hand = 1 layerStack = True file_path = '' file_path = t...
21,372
7,561
import tkinter as tk from tkinter.colorchooser import askcolor from tkinter import ttk from Scrollable import Scrollable from ViewLedgerWidget import ViewLedgerWidget from List import ListView from Group import Group # window for editing a group prevLens = [ 10, 25, 100 ] class EditGroupWindow( tk.Toplevel ): de...
5,148
1,725
crabs = sorted(map(int, open("input.txt", "r").readline().strip().split(","))) # position with minimal fuel usage is at the median position median_pos = crabs[len(crabs) // 2] min_fuel = sum([abs(crab_pos - median_pos) for crab_pos in crabs]) print(min_fuel)
261
101
# Author: Matej Mik from ..component import Component from ..da import DAI import re def add_team_g(string, attributes): if 'tym' in string: if re.search('(muj|moj|meh)[^ ]{0,3} tym', string): attributes.append('team=default') else: team = string.split('tym')[-1].split(' '...
5,172
1,647
from SSstache import * from plumbum.path.utils import delete from plumbum.cmd import ls, touch, mkdir def test_makeSupportScriptStache(): delete('xyz') assert makeSupportScriptStache(stacheDir='xyz').endswith('xyz') assert ls('xyz').split()==['RSrun.2.7.min.js', 'glow.2.7.min.js', 'ide.css', 'jquery-ui.cu...
1,447
497
import matplotlib.pyplot as plt x = [1, 2, 5] y = [2, 3, 7] plt.title("1 grafico com python") # Eixos plt.xlabel("Eixo X") plt.ylabel("Eixo Y") plt.plot(x,y) plt.show()
173
94
import cv2 import numpy import glob import os images = [] path = os.getcwd()+"\\frames\\" myVideo = cv2.VideoWriter("quicksort-1.mkv", cv2.VideoWriter_fourcc(*"DIVX"), 60, (1920,1080)) for filename in range(len(os.listdir(path))): filename = f"frame-{filename}.png" img = cv2.imread(f"{path}{f...
421
175
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.layers import * from model.build import * import cv2 from model.utils import * def get_test_input(): img = cv2.imread("images/dog-cycle-car.png") img = cv2.resize(img, (416, 416...
18,008
4,753
from icemac.addressbook.browser.search.result.handler.manager import ( SearchResultHandler) def makeSRHandler(viewName): """Create a `SearchResultHandler` with the specified `viewName`.""" handler = SearchResultHandler(None, None, None, None) handler.viewName = viewName return handler def test_m...
1,131
332
import json import pymysql import random import string import time # def get_data(): # with open('E:\\QQ文档\\1420944066\\FileRecv\\Code (2)\\data\\nice looking data\\与gooddata里重复\\20_30(1).json', 'r') as f: # camera_text = json.load(f) # 解析每一行数据 # print(camera_text) # return camera_text # def...
2,271
862
import os import random import cv2 import numpy as np import torch from Experiments.all import load_models, embedd_data, save_batch from GenerativeModels.utils.data_utils import get_dataset device = torch.device("cuda") def sample_latent_neighbors(outputs_dir, models_dir): """Find nearest latent neighbors of d...
3,290
1,375