content
stringlengths
5
1.05M
class Solution(object): def distinctNumbers(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ s = {} n = len(nums) ans = [] if n < k: return ans for i in range(k): if nums[i] in s: ...
"""Resolwe SDK for Python.""" from .collection_tables import CollectionTables # noqa from .resdk_logger import log_to_stdout, start_logging # noqa from .resolwe import Resolwe, ResolweQuery # noqa
import pyeapi def main(): pynet_sw2 = pyeapi.connect_to('pynet-sw2') show_int = pynet_sw2.enable("show interfaces") show_int = show_int[0] show_int = show_int['result'] show_int = show_int['interfaces'] show_int.keys() mgmt1 = show_int['Management1'] eth1 = show_int['Ethernet1'] ...
#!/usr/bin/env python3 ''' Trainer Author: Oyesh Mann Singh ''' import os from utils.eval import Evaluator from tqdm import tqdm, tqdm_notebook, tnrange import torch import torch.nn as nn import torch.optim as optim from sklearn.metrics import accuracy_score torch.manual_seed(163) tqdm.pandas(desc='Progress'...
#!/usr/bin/python3 -S # -*- coding: utf-8 -*- from cargo.fields import Char from cargo.validators import LengthBoundsValidator from unit_tests import configure from unit_tests.validators.Validator import TestValidator class TestLengthBoundsValidator(TestValidator): field = Char(minlen=2, maxlen=5, validator=Leng...
#!/usr/bin/env python3 import sys n = int(sys.argv[1]) peak_pos = int(sys.argv[2]) zeros = int(sys.argv[3]) a = [0]*n a[peak_pos] = n+1 for i in range(zeros+1, n, zeros+1): if peak_pos+i < n: a[peak_pos+i] = 1 if peak_pos-i >= 0: a[peak_pos-i] = 1 print(len(a)) print(' '.join(map(str, a)))
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2018-03-19 14:10 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('kiddyer', '0002_authusergroups'), ] operations = [ migrations.RenameModel( ...
from sympy import symbols, GreaterThan, simplify, solve def main(): s_0, s_1, s_2 = symbols('s_0 s_1 s_2') x_b_0, x_b_1, x_b_2 = symbols('x_b_0 x_b_1 x_b_2') y_b_0, y_b_1, y_b_2 = symbols('y_b_0 y_b_1 y_b_2') x, y = symbols('x y') p_0_x = s_0 * x + x_b_0 p_1_x = s_1 * x + x_b_1 p_2_x = s_...
try: import simplejson as json except ImportError: import json import functools from cgi import parse_header def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False): """ A middleware that parses the body of json requests and encodes the json responses. NOTE: this middle...
import lxml.html import sqlite3 from urllib.request import urlopen from urllib.parse import urlencode from os import environ html = urlopen(environ['KRISHAKZBOT_URL'], timeout=60).read().decode('utf-8') doc = lxml.html.fromstring(html) top_ads = [(link.get('href'),) for link in doc.cssselect('.a-card__title')] conn =...
import graphene from django_prices.templatetags import prices class Money(graphene.ObjectType): currency = graphene.String(description="Currency code.", required=True) amount = graphene.Float(description="Amount of money.", required=True) localized = graphene.String( description="Money formatted a...
import os import locale import codecs import nose import numpy as np from numpy.testing import assert_equal import pandas as pd from pandas import date_range, Index import pandas.util.testing as tm from pandas.tools.util import cartesian_product, to_numeric CURRENT_LOCALE = locale.getlocale() LOCALE_OVERRIDE = os.en...
#!/usr/bin/env python """ check lexicons check the phase1 or phase2 output lexicon files for debugging purpose """ import os import sys from struct import unpack, calcsize def main(filename): """ main routine """ lex_schema = 'iiih' if not os.path.exists(filename): print 'error' offset = 0 rec_si...
"""coding=utf-8 Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved. Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team. 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 Lice...
import argparse import operator import sys import os import setGPU import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from data import get_batch from meta_optimizer import MetaModel, MetaOptimizer, FastMetaOptimizer from model import Model from torch.autogr...
from __future__ import print_function import xlsxwriter import xml.dom import xml.etree import sys if len(sys.argv) < 2: print("\nNo files were specified on the command line.\n" + "Usage: python_excel_writer.py infile.nessus outfile.xlsx\n" + "Quitting....\n") exit() elif ".nessus" not in sy...
import copy import importlib import itertools import logging import os import sys import numpy as np import pandas as pd from pandas.api.types import is_integer from pathlib import Path try: # used by pytest tmpdir from py._path.local import LocalPath FILE_TYPE = (str, Path, LocalPath) except ImportErro...
############################################################################## # # Copyright (c) 2001, 2002 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # TH...
# -*- coding: utf-8 -*- # Copyright © 2012-2013 Roberto Alsina and others. # 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 t...
from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.conf import settings import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^people/', views.people, name='people'), url(r'^api/', views.api, name='people'), ...
# -*- coding: utf-8 -*- """ Copyright (C) 2014-2016 bromix (plugin.video.youtube) Copyright (C) 2016-2018 plugin.video.youtube SPDX-License-Identifier: GPL-2.0-only See LICENSES/GPL-2.0-only for more information. """ FILES = 'files' SONGS = 'songs' ARTISTS = 'artists' ALBUMS = 'albums' MOVIES = 'movi...
import json import logging import tweepy from main import send_tweet_to_discord logging.basicConfig( level=logging.INFO, format="%(asctime)s | %(name)s | %(levelname)s | %(message)s" ) logger = logging.getLogger(__name__) class TwitterUser: def __init__(self, _id, id_str, name, screen_name, location, u...
from typing import Union import pandas as pd import gframe def cat_to_num(self, col : str) -> None: """Changes categories to binary columns Args: col (str): Column in DataFrame drop (bool, optional): Should it drop original column. Defaults to False. """ categories = self.df[col].dropn...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-04 18:30 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Attempt to check each interface in nipype """ # Stdlib imports import os import re import sys import warnings from nipype.interfaces.base import BaseInterface import black # Functions and classes cla...
import torch import sentencepiece as spm from bert.model import MovieClassification, BERTPretrain from bert.data import MovieDataSet, movie_collate_fn, PretrainDataSet, make_pretrain_data, pretrin_collate_fn from config import Config import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt from IPytho...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: game.py # ------------------- # Divine Oasis # Text Based RPG Game # By wsngamerz # ------------------- import divineoasis import logging import logging.config import os import platform import pyglet import sys from divineoasis.assets import Assets, Directo...
"""Grype SCA and Container tool class""" import shlex from pydash import py_ from eze.core.enums import VulnerabilityType, VulnerabilitySeverityEnum, ToolType, SourceType, Vulnerability from eze.utils.cli import extract_cmd_version, run_async_cli_command from eze.core.tool import ToolMeta, ScanResult from eze.utils.i...
import numpy as np import pickle import os import matplotlib.pyplot as plt import networkx as nx base_file_path = os.path.abspath(os.path.join(os.curdir, '..', '..', '..')) # should point to the level above the src directory data_path = os.path.join(base_file_path, 'data', 'Intercity_Dallas') county_data = pickle.loa...
from typing import Tuple, Union import numpy as np from abito.lib.utils import _quantile_is_valid def _argquantile_weighted( weights_sorted: np.ndarray, q: np.ndarray ) -> Tuple[np.ndarray, np.ndarray]: inds = [] cuts = [] q = np.asanyarray(q) weight_qs = [int(q * weights_sorted.sum())...
import numpy as np from BDQuaternions import UnitQuaternion from BDQuaternions import functions as qt q1 = UnitQuaternion() q2 = UnitQuaternion(np.array([0, 1, 0, 0], dtype=np.double)) print('BDQuaternions:', q1, q2) print('Scalar part:', q1.scalar_part()) print('Vector part:', q1.vector_part()) print('q1* =', q1.co...
# Scraper for Oklahoma Court of Criminal Appeals #CourtID: oklacrimapp #Court Short Name: OK #Author: Andrei Chelaru #Reviewer: mlr #Date: 2014-07-05 from datetime import date from juriscraper.opinions.united_states.state import okla class Site(okla.Site): def __init__(self): super(Site, self).__init__(...
import plotly.express as px import matplotlib.pyplot as plt import streamlit as st import pandas as pd def pareto_plot(df_abc): fig = px.line( data_frame=df_abc, width=800, height=600, x='SKU_%', y='QTY%_CS', labels={ "SKU_%": 'Percentage of SKU (%)', "QTY%_CS": 'Percentage of the Qua...
from __future__ import unicode_literals from django.http import JsonResponse from django.http import Http404 from django.shortcuts import render def index(request): return render(request, 'index.html') def health(request): state = {"status": "UP"} return JsonResponse(state) def handler404(request): ...
#!/usr/bin/env python #-*- coding:utf-8 -*- ## ## instdep.py ## ## Created on: Apr 19, 2020 ## Author: Alexey Ignatiev ## E-mail: alexey.ignatiev@monash.edu ## Taken from: https://github.com/rjungbeck/pysat/blob/master/instdep.py # #==========================================================================...
# plotting.py - plotting utilities # ASS, 21 Apr 2020 # # This file contains some utility functions for plotting CRNs # # Copyright (c) 2018, Build-A-Cell. All rights reserved. # See LICENSE file in the project root directory for details. import math import random import statistics from warnings import warn from .com...
from setuptools import setup, find_packages ''' py_modules:只识别.py文件,其他文件不识别 可以自动添加README.rst和MANIFEST.in文件,但不能自动添加LICENSE.txt文件 packages=find_packages 让setup自动查找需要打包的子包 platforms=["all"] 支持所有平台使用 ''' setup( name='fileutil', version='1.0.4', description=r''' file union,file split by row/...
from os.path import expanduser from pkg_resources import resource_string SETTINGS_FILE = expanduser('~/.digiglass') APP_NAME = 'digiglass' APP_AUTHOR = 'mplewis' CACHE_EXPIRY = 900 # 15 minutes # The max number of categories to display when asking the user to choose MAX_CATEGORIES = 20 # Used for getting choices ...
from django.contrib import admin from wkz import models admin.site.register(models.Sport) admin.site.register(models.Activity) admin.site.register(models.Settings) admin.site.register(models.Traces) admin.site.register(models.Lap) admin.site.register(models.BestSection)
import os from datetime import datetime _OUTPUT_DIR = 'data' def ensure_path(path): if not os.path.exists(path): os.makedirs(path) def ensure_output_path(mod): p = _OUTPUT_DIR + '/' + mod ensure_path(p) def get_output_dir(mod): return _OUTPUT_DIR + '/' + mod def get_output_path(mod, file): return get...
from interactions.utils.sim_focus import SimFocus, get_next_focus_id from socials.geometry import SocialGeometry import interactions.utils.sim_focus import sims4.log import sims4.math import services logger = sims4.log.Logger('Social Group') class SocialFocusManager: class SimFocusEntry: def __init__(sel...
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. from __future__ import division, print_function from ase.atoms import Atoms as ASEAtoms, Atom as ASEAtom from ase.symbol...
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
# Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from coremltools.converters.mil.mil import Builder as mb from coremltools.converters.mil.testing_util...
import json import mock import pytest from click.testing import CliRunner from gradient.api_sdk import sdk_exceptions from gradient.api_sdk.clients.http_client import default_headers from gradient.cli import cli from tests import MockResponse, example_responses EXPECTED_HEADERS = default_headers.copy() EXPECTED_HEAD...
from agility.main import Servo, Leg, Robot, Head, Body from finesse.eclipse import Finesse from theia.eye import Camera ################ # Define robot. ################ class Android: camera = Camera(0, 90, 60) # Leg 1. servo1 = Servo(0, -180, 90, 500, 2500, 150, bias=-10, direction=1) servo2 = Ser...
from django.db import models from jsonfield import JSONField class TimeStampedModel(models.Model): """ An abstract base class model that provides self-updating ``created`` and ``modified`` fields. """ created = models.DateField(auto_now_add=True) modified = models.DateField(auto_now=True) ...
# Generated by Django 3.0 on 2020-10-13 16:37 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Vendor', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
# -*- coding: utf-8 -*- import subprocess import os from .sqlite_resource import SqliteResource class Parser(object): # path to data file dumped by demoinfogo dat_file = os.path.dirname(os.path.realpath(__file__)) + "/dat/demo.dat" # path to demoinfogo executable path_to_demoinfogo = os.path.dirname(o...
import torch from torch.autograd import Variable import numpy as np from torch import distributions as dis from copy import deepcopy import torch.nn as nn EPS = 1e-6 # Avoid NaN (prevents division by zero or log of zero) # CAP the standard deviation of the actor LOG_STD_MAX = 2 LOG_STD_MIN = -20 REG = 1e-3 # regular...
import os import sys if __name__: sys.path.append(os.path.dirname( os.path.abspath(os.path.dirname(__file__)))) from utils.util import * class LockerFrame(tk.Frame): STATE_WAIT = "W" STATE_USED = "U" STATE_BROKEN = "B" STATE_KIOSK = "K" DEFAULT_MODE = 0 FIX_MODE = 1 UNLOCK...
""" This is a function for enabling data capture. Checks these 2 things of the input data: - features (aka input schema) - descriptive statistics about input features """ from urllib.parse import urlparse from time import gmtime, strftime, sleep import time from threading import Thread import boto3 import pan...
import json import logging.config import os def load_config(filepath): """Config dictionary Args: filepath (str): Returns: dict: Raises: ImportError: FileNotFoundError: """ if os.path.exists(filepath): _, ext = os.path.splitext(filepath) if ex...
import os import yaml # Set defaults system = dict( use_acct_db = False, use_cors = False, debug = False, host = '0.0.0.0', port = 5000, serve_index = False, archive_usage_load = False, archive_wait_time = 60, archive_path = 'db.json', ) # Change to yaml values ymlfile = None if os...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from bioseq.models.Variant import Variant from pdbdb.models import Residue, PDBResidueSet, Property, ResidueSet class PDBVariant(models.Model): variant = models.ForeignKey(Variant, models.CASCADE, "pdb_variants") re...
import io from codenode.base import CodeNode from typing import Union DumpStream = Union[io.StringIO, io.TextIOBase] class CodeNodeWriter: def node_to_lines(self, node: CodeNode): stack = [(node, 0, node.total())] while stack: node, depth, iterator = stack[-1] try: ...
import re from datetime import date, datetime from gazette.items import Gazette from gazette.spiders.base import BaseGazetteSpider class SpSumareSpider(BaseGazetteSpider): TERRITORY_ID = "3552403" allowed_domains = ["sumare.sp.gov.br"] name = "sp_sumare" start_urls = ["https://www.sumare.sp.gov.br/Di...
""" Admin """ from django.contrib import admin from .models import Quiz, Question, Result admin.site.register(Quiz) admin.site.register(Question) admin.site.register(Result)
""" Helper functions for creating Form classes from Django models and database field objects. """ from collections import OrderedDict from itertools import chain from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.forms.fields import ChoiceField,...
import torch import torch.nn as nn def focal_loss(input, target, alpha=0.25, gamma=2.): ''' Args: input: prediction, 'batch x c x h x w' target: ground truth, 'batch x c x h x w' alpha: hyper param, default in 0.25 gamma: hyper param, default in 2.0 Reference: Focal Loss ...
from memory.space import Bank, START_ADDRESS_SNES, Write import instruction.asm as asm import instruction.f0 as f0 import args import data.event_bit as event_bit from constants.gates import character_checks import constants.objectives.condition_bits as condition_bits import menus.pregame_track_scroll_area as scroll_ar...
def initialize(): exit = False while(exit == False): print("⚙️ Selecciona el tipo de interfaz:") print("(0) -> Salir") print("(1) -> CLI") print("(2) -> GUI") n = 100 try: n = int(input()) except ValueError: print("⛔ No has introd...
from time import perf_counter as perC counted=0 """直前に計測が完了した処理の秒数""" def funcTimer(functionObject:function)->function: """ 処理を実行してから完了するまでの時間を計測するデコレータです。 変数countedに計測した秒数を代入します。 """ def retFunc(*args,**kwards): global counted st=perC() ret=functionObject(*args,**kwards) ...
from django.contrib import admin from .models import Banner, Services, Video, Testimonial admin.site.register(Banner) admin.site.register(Services) admin.site.register(Video) admin.site.register(Testimonial)
import numpy as np class Activation: """ Activation function Meant to be calculated as follows: f(W * X.T + b) Where: - f - non-linear activation function - X is m (batch,examples) by n (prev units) - W is m (units) by n (prev units) - b is intercept term (bias) - vector of n units...
""" common automol parameters """ import inspect import itertools class ReactionClass: """ Names of supported reaction classes """ TRIVIAL = 'trivial' # Unimolecular reactions HYDROGEN_MIGRATION = 'hydrogen migration' BETA_SCISSION = 'beta scission' RING_FORM_SCISSION = 'ring forming sciss...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Median Maintenance """ import math def _get_parent(key: int): if key == 0: return 0 else: return (key + 1) // 2 - 1 def _get_children(key: int): return 2 * key + 1, 2 * key + 2 class MaxHeap: def __init__(self): self._arr...
import socket def threaded_method(self): sock = socket.socket() sock.connect(('xkcd.com', 80)) request = 'GET {} HTTP/1.0\r\n\r\n'.format('/353/') sock.send(request.encode('ascii')) response = b'' chunk = sock.recv(4096) while chunk: response += chunk chunk = sock.recv(4096...
# # 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...
from django.contrib import admin from socialregistration.contrib.sapo.models import SapoProfile admin.site.register(SapoProfile)
import requests import json def test_hello(url): response = requests.get(url) assert response.status_code == 200 assert response.text == "Hello, World!"
import subprocess as sp import soundfile as sf import tempfile as tmp from itertools import chain import warnings import re import stempeg def check_available_aac_encoders(): """Returns the available AAC encoders Returns ---------- codecs : list(str) List of available encoder codecs """ ...
""" Numpy stages. The examples in this section assume >>> import numpy """ import types try: from ._src import * from ._filt import * from ._snk import * except ValueError: from _src import * from _filt import * from _snk import * __all__ = [] for m in [_src, _filt, _snk]: for s i...
import os import math from PIL import Image import requests from io import BytesIO from torchvision import transforms, utils class DataLoader(): def __init__(self): pass def load(self, url, size): try: response = requests.get(url) img = Image.open(BytesIO(resp...
#!/usr/bin/env python3 import rospy import smach from smach import State # define state Foo class Code(smach.State): def __init__(self): smach.State.__init__(self, outcomes=['time_to_sleep','done']) self.counter = 0 def execute(self, userdata): rospy.loginfo('Executing state FOO') ...
# -*- coding: utf8 -*- import os, sys import requests import logging from io import BytesIO from sanic import Sanic, response from sanic_cors import CORS from sanic.response import text, json from Services.Aslide.aslide import Aslide from Services.Aslide.deepzoom import ADeepZoomGenerator app = Sanic(__name__) # 跨...
""" str - string """ print("Essa é uma 'string' (str) ") print('Essa é uma "string" (str) ') print("Esse é meu \"texto\" (str) ") # uso da \ como caracter de escape print('Esse é meu \'texto\' (str) ') # uso da \ como caracter de escape print("Esse é meu \n (str)") # erro ao usar a \ como caracter de escape print(r"E...
#!/usr/bin/python3 import time from MessageConverters.MessageConverter import MessageConverter import logging from datetime import datetime class KLAX(MessageConverter): def __init__(self, devicename): super().__init__(devicename) def __toTime(self, byteArray): year = 2000 + (byteArray[3] >> ...
from itertools import chain from django import forms from django.core.exceptions import ValidationError from django.db.models import Count, Prefetch from django.utils.encoding import force_text from django.utils.formats import number_format from django.utils.html import escape from django.utils.safestring import mark_...
from .config import add_dqrf_config from .config import add_dataset_path from .dqrf_detr import DQRF_DETR
# 图片验证码的有效期, 单位秒 IMAGE_CODE_REDIS_EXPIRES = 300 # 短信验证码有效期 SMS_CODE_REDIS_EXPIRES = 300 # 短信验证码发送间隔 SEND_SMS_CODE_INTERVAL = 60 # 短信验证码模板编号 SMS_CODE_TEMP_ID = 1
from django.db.models import Max from django.db.models.expressions import OuterRef, Subquery from haystack import indexes from djangocms_internalsearch.helpers import ( get_version_object, get_versioning_extension, ) class BaseSearchConfig(indexes.SearchIndex, indexes.Indexable): """ Base config cla...
# -*- coding: utf-8 -*- from flask import Blueprint from flask_cors import CORS # Flask Blueprint 정의 api = Blueprint('api', __name__) CORS(api) # enable CORS on the API_v1.0 blueprint from . import particle, search
from django.apps import AppConfig class MainbookConfig(AppConfig): name = 'mainBook'
import os import shutil from unittest import TestCase from broker.service.spreadsheet_storage.spreadsheet_storage_service import SpreadsheetStorageService TEST_STORAGE_DIR = "test_storage_dir" class SpreadsheetStorageServiceTest(TestCase): def setUp(self): os.mkdir(TEST_STORAGE_DIR) def test_store...
import pymysql db = pymysql.connect("localhost","testuser","test123","sakila",3306) cursor = db.cursor() sql = "SELECT VERSION()" cursor.execute(sql) data = cursor.fetchone() print("Database version : %s" % data) db.close()
""" Custom Django settings for django-user-tasks. """ from datetime import timedelta from django.conf import settings as django_settings from django.core.files.storage import get_storage_class from user_tasks import filters class LazySettings(): """ The behavior of ``django-user-tasks`` can be customized v...
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Defines a set of constants shared by test runners and other scripts.""" import os CHROME_DIR = os.path.abspath(os.path.join(os.path.dirname(__file_...
# # from moviepy.editor import VideoFileClip # output2 = 'trucks2_cut.mp4' # clip2 = VideoFileClip("DJI_0686.MOV").subclip(0,14) # # clip2.write_videofile(output2, audio=False) # #clip2 = VideoFileClip("challenge_video.mp4").subclip(20,28) from moviepy.editor import VideoFileClip output2 = 'horse.mp4' clip2 = VideoF...
import datetime from IPython.display import display, display_javascript, display_html import json import pydoc from typing import Union import uuid from sfaira.data.dataloaders.base import DatasetGroup, DatasetSuperGroup from sfaira.data.dataloaders.databases.cellxgene.cellxgene_loader import Dataset from sfaira.data...
import time from selenium import webdriver from selenium.webdriver.support.ui import Select #scraper for wildflower.org def scrape(name): image_urls = set() caps = webdriver.DesiredCapabilities().FIREFOX caps["marionette"] = True driver = webdriver.Firefox(capabilities=caps) driver.get('https://www...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 29 16:53:19 2019 @author: gparkes """ import numpy as np import matplotlib.pyplot as plt # task 1 def monte_carlo_integrate(f, dx, dy, N): area = (dx[1] - dx[0])*(dy[1] - dy[0]) # generate random numbers in 2-d pairs = np.random.rand(N,...
from pathlib import Path import httpx class Poem: def __init__(self): self._token_url = "https://v2.jinrishici.com/token" self._poem_url = "https://v2.jinrishici.com/sentence" self._token = self._init_token() def _init_token(self) -> str: token_path = Path("./poem_token") ...
''' Module for comparing data in two DataTables. The main entry point is the diff method which takes the two tables and the list of headers which specifies the "primary key" for the tables diff returns a ResultSet instance which contains the difference data by primary key. ResultSet contains several methods for pruni...
import sys import os def debug(msg): if (len(sys.argv) > 2): if (sys.argv[2] == 'debug'): print(msg) if (len(sys.argv) < 2): print('Usage: {} file.dyn [debug]'.format(sys.argv[0])) sys.exit(1) filename = sys.argv[1] dest = os.path.splitext(filename)[0] + '.zip' # XOR key and shuffle index arrays for...
class Solution: def isPalindrome(self, s: str) -> bool: special_char = "~!@#$%^&*()_+`-=[]\\;',./{} |:<>?\"'" s = s.lower() for i in special_char: s = s.replace(i, "") return s == s[::-1]
''' reference https://blog.csdn.net/zhang_gang1989/article/details/72884662 https://blog.csdn.net/weixin_38215395/article/details/78679296 ''' #change lineArr[1] the index accoring to the data trace format import os import argparse def mkdir(path): folder = os.path.exists(path) if not folder: ...
#!/usr/bin/env python # coding=utf-8 import xlrd from lxml import etree import json import io import sys def read_xls(fromfile): # with open(fromfile) as f: # content = f.read() # # print (content) # return book = xlrd.open_workbook(fromfile) sheet = book.sheet_by_name('student') ...
from celery.schedules import crontab # uses AWS creds from the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY env variables BROKER_URL = 'sqs://' BROKER_TRANSPORT_OPTIONS = { 'region': 'eu-west-1', 'polling_interval': 15 * 1, 'queue_name_prefix': 'mma-dexter-', 'visibility_timeout': 3600, } # all our t...
import os import torch import numpy as np import torch.nn as nn from torch.autograd import Variable from src.crowd_count import CrowdCounter from src.data_loader import ImageDataLoader from src import utils import h5py import scipy.io as io import PIL.Image as Image import numpy as np import os import ...