text
string
size
int64
token_count
int64
def firstDuplicate(a): number_frequencies, number_indices, duplicate_index = {}, {}, {} # Iterate through list and increment frequency count # if number not in dict. Also, note the index asscoiated # with the value for i in range(len(a)): if a[i] not in number_frequencies: numbe...
862
272
from django import forms from django.core.exceptions import ValidationError from abs.models import dataflows class ABSDataflowForm(forms.Form): dataflow = forms.ChoiceField(choices=(), required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["dataflow"...
374
118
# Python import logging # Unicon from unicon.core.errors import SubCommandFailure # Logger log = logging.getLogger(__name__) def clear_access_session_intf(device, intf): """ clear access-session interface {} Args: device (`obj`): Device object intf('str'): Name of the interface ...
734
199
"""Support for referencing Pipeline packages in forms and widgets.""" from __future__ import unicode_literals from django.contrib.staticfiles.storage import staticfiles_storage from django.utils.functional import cached_property try: from django.utils.six import iteritems, add_metaclass except ImportError: fr...
9,713
2,441
from django.http import QueryDict from django.http.response import JsonResponse from rest_framework import viewsets, status from rest_framework.views import APIView from .serializers import * class UserInfoViewSet(viewsets.ModelViewSet): queryset = UserInfoModel.objects.all() serializer_class = UserInfoSerial...
1,838
569
import os import re import sys def spec_replacer(match): if match.group(0) == ' ': return '^_' return '^' + match.group(0) def create_content(type, major, minor, level, edit): python_dir = '/python$root' python_dir_len = len(python_dir) all_dirs = [] all_files = [] spec_pattern = r...
5,043
1,763
#!/usr/bin/env python # .py # @TODO: # - fix the diffing # - use rsync across hosts or something fancy import argparse, difflib, functools, re, shutil, subprocess, sys, time, os from pprint import pprint __description__ = "Manage your dotfiles." ls = lambda path: os.listdir(path) ls_abs = lambda path: [os.path.join...
10,458
3,184
import matplotlib.pylab as plt def plot_log_population(population, _title, _xlabel, _ylabel, _bins): plt.hist(population,bins=_bins) plt.xlabel(_xlabel) plt.ylabel(_ylabel) plt.title(_title) plt.yscale('log'); plt.show()
246
98
""" Driver class for Hagisonic Stargazer, with no ROS dependencies. """ from serial import Serial from collections import deque import re import yaml import time import logging import rospy import numpy as np from threading import Thread, Event from tf import transformations # STX: char that represents the start of a ...
12,711
3,483
from flatifylists import flatifyList example = [[[1,2], [3,[4,[5],6],7],8,9]] print(flatifyList(example))
107
44
import os import json import subprocess from ._exceptions import ProbeException __all__ = ['probe'] def probe(filename, cmd='ffprobe', timeout=None): """Runs the ffprobe on the given file and outputs in json format """ if not os.path.isfile(filename): raise FileExistsError(f"Input file {filename} d...
834
259
def printMax(x,y): '''prints the maximum of two numbers. The two values must be integers.''' x = int(x) y = int(y) if x > y: print x,'is maximun' else: print y,'is maximum' printMax(3,5) print printMax.__doc__
252
92
#!/usr/bin/env python3 # Disclaimer: # This script is for educational purposes only. # Do not use against any network that you don't own or have authorization to test. #!/usr/bin/python3 # We will be using the csv module to work with the data captured by airodump-ng. import csv # If we move csv files to a backup ...
16,602
4,700
import subprocess def get_gpu_memory_map(): ''' Keys are device ids as integers. Values are memory usage as integers in MB. ''' result = subprocess.check_output( [ 'nvidia-smi', '--query-gpu=memory.used', '--format=csv,nounits,noheader' ], encoding='...
597
197
import unittest from sys import argv import numpy as np import torch from objective.ridge import Ridge, Ridge_ClosedForm, Ridge_Gradient from .utils import Container, assert_all_close, assert_all_close_dict def _init_ridge(cls): np.random.seed(1234) torch.manual_seed(1234) n_features = 3 n_samples ...
2,010
762
from django.shortcuts import redirect from django.http.response import JsonResponse from django.http import HttpResponse from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required from rest_framework.response import Response from rest_framework.decorators import api...
11,795
3,494
import numpy as np import torch from torch.autograd import grad from learn2learn.utils import clone_module, update_module from torch import nn, optim def maml_update(model, lr, grads=None): """ [[Source]](https://github.com/learnables/learn2learn/blob/master/learn2learn/algorithms/maml.py) **Description** Perfo...
33,949
14,044
#coding:utf-8 #from graypy import GELFHandler import logging.config import logging ''' handler = GELFHandler(host='0.0.0.0', port=12201) logger = logging.getLogger() logger.addHandler(handler) logger.error('catch error') ''' LOG_LEVEL = 'DEBUG' def get_log_config(category): log_file = "{}.log".format(category)...
1,602
495
from instanotifier.fetcher import tests def run(): # is executed when ran with 'manage.py runscript tests' tests.test_rss_fetcher()
142
47
import sqlite3 def main(): # se establece conexion con la BD y abro cursor conn = sqlite3.connect("alumnos.db") cursor = conn.cursor() # creo una tupla de tuplas para agregar registros a la tabla alumnos = ( (1, "Juan", "Granizado", 8, 25), (2, "Esteban", "Quito", 2, 19), ...
676
259
import sqlite3 con = sqlite3.connect('agenda.db') cursor = con.cursor() cursor.execute(''' create table if not exists agenda( nome text, telefone text) ''') cursor.execute(''' insert into agenda(nome, telefone) values(?, ?) ''', ("Tamara", "51-98175-05...
366
122
import logging import math import re import time import dask import numpy as np import requests import json import xml.etree.ElementTree as ET from falconcv.data.scraper.scraper import ImagesScraper from falconcv.util import ImageUtil logger = logging.getLogger(__name__) FLICKR_ENDPOINT = "https://www.flickr.com/servic...
4,298
1,392
# argParser # this class generates a RunParams object from the args passed to the script from runparams import * import os.path import string ## handles args passed to the program # class ArgParser(object): def parsePtCutString(self, ptCutString): return map(float, string.split(ptCutString,',') ) de...
9,893
3,553
# pip install -U pywinauto from pywinauto.application import Application import subprocess import time subprocess.run('SCHTASKS /DELETE /TN BuildTasks\\Sites /f') app = Application(backend='uia') app.start('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe --force-renderer-accessibility ') window = app.top_win...
1,326
474
# ---------------------------------------------------------------------- # Migrate SLAProbe to workflow # ---------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- ...
992
315
# dirstateguard.py - class to allow restoring dirstate after failure # # Copyright 2005-2007 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import from .i18n import ...
2,640
756
""" CONFIGURATION FILE This is being developed for the MF2C Project: http://www.mf2c-project.eu/ Copyright: Roi Sucasas Font, Atos Research and Innovation, 2017. This code is licensed under an Apache 2.0 license. Please, refer to the LICENSE.TXT file for more information Created on 18 oct. 2018 @author: Roi Sucasas...
2,061
723
# # PySNMP MIB module IANA-MALLOC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANA-MALLOC-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:50:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27...
3,606
1,289
from .version import VersionViewSet, DeployVersionViewSet __all__ = ["VersionViewSet", "DeployVersionViewSet"]
112
33
import warnings from .xilinx import XilinxPlatform __all__ = ["XilinxSpartan3APlatform", "XilinxSpartan6Platform"] XilinxSpartan3APlatform = XilinxPlatform XilinxSpartan6Platform = XilinxPlatform # TODO(amaranth-0.4): remove warnings.warn("instead of amaranth.vendor.xilinx_spartan_3_6.XilinxSpartan3APlatform and...
455
167
from ast import literal_eval from collections import Counter from typing import Dict, Optional from anndata import AnnData from spatialtis.config import Config, analysis_list from ...utils import doc from ..base import graph_position_interactive, graph_position_static from .utils import query_df @doc def community...
2,968
996
# Python 2-to-3 compatibility code from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import collections from pynics.binparse.forbinfile import RecordError def cbin_results_parse(binfile, results_store, curr_version, pa...
7,209
2,402
import os import socket import threading HEADER = 64 PORT = 5053 FW = "192.168.101.2" ADDR = (FW, PORT) FORMAT = 'utf-8' DISCONNECT_MESSAGE = "!DISCONNECT" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_client(conn, addr): print(f"[FIREWALL CONNECTION] {addr} connected.")...
1,084
382
""" 1208. Get Equal Substrings Within Budget Straight forward. Asked the max len, so count the max each time. """ class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: cost = 0 window_start = 0 result = 0 for window_end in range(...
652
201
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The Unit-e developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import UnitETestFramework from test_framework.util import ( json, con...
13,836
4,231
import unittest from geopy.compat import u from geopy.point import Point from geopy.geocoders import YahooPlaceFinder from test.geocoders.util import GeocoderTestBase, env class YahooPlaceFinderTestCaseUnitTest(GeocoderTestBase): # pylint: disable=R0904,C0111 def test_user_agent_custom(self): geocoder ...
2,213
889
#!/usr/bin/env python2.4 # -*- encoding: latin-1 -*- """A small XML-RPC Server running under control of the internet superserver inetd. Configuring: Add this line to your inetd.conf embedxmlrpc stream tcp nowait user /usr/sbin/tcpd inetdxmlrpc.py Where user is the user to execute the script and inetdxmlp...
1,151
395
""" Train shadow net script """ import argparse import functools import itertools import os import os.path as ops import sys import time import numpy as np import tensorflow as tf import pprint import shadownet import six from six.moves import xrange # pylint: disable=redefined-builtin sys.path.append('/data/') fr...
17,504
5,231
# Copyright 2014 CloudFounders NV # # 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 writ...
7,007
2,056
# Copyright 2015 Internap. # # 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, so...
6,314
1,867
#!/usr/bin/env python import setuptools from memsource import version with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="memsource", version=version.__version__, author="Yanis Guenane", author_email="yguenane+opensource@gmail.com", desc...
939
292
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- """Implements FunctionTransformer, a class to create custom transformers.""" __author__ = ["Bouke Postma"] __all__ = ["FunctionTransformer"] import numpy as np from sktime.transformations.base import _SeriesToSeriesTransformer from sktime.utils.validation.series imp...
5,637
1,583
# vim: set encoding=utf-8 import re from lxml import etree import logging from regparser import content from regparser.tree.depth import heuristics, rules, markers as mtypes from regparser.tree.depth.derive import derive_depths from regparser.tree.struct import Node from regparser.tree.paragraph import p_level_of from...
13,963
4,281
from distutils.core import setup from setuptools import find_packages setup( name="stytra", version="0.1", author="Vilim Stih, Luigi Petrucco @portugueslab", author_email="vilim@neuro.mpg.de", license="MIT", packages=find_packages(), install_requires=[ "pyqtgraph>=0.10.0", ...
1,216
378
#!/usr/bin/python3 # let board be 3x3 bool array def isWin(board): start = board[0][0] win = False next = [(0, 1), (1, 1), (1, 0)] while(!win): while return win def main(): pass if __name__ == '__main__': main()
226
105
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the G...
2,138
590
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainUi.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWin...
83,653
31,924
class File: @staticmethod def tail(self, file_path, lines=10): with open(file_path, 'rb') as f: total_lines_wanted = lines block_size = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 ...
1,177
365
import argparse class ArchParser(argparse.ArgumentParser): def __init__(self, model_names, *args, **kwargs): super().__init__(*args, **kwargs) self.add_argument('-a', '--arch', metavar='ARCH', choices=model_names, help='model architecture: ' + ' | '.join(model_names)) c...
4,122
1,146
from finicky.validators import ValidationException def validate(schema, data, hook=None): """ Given an input named `data` validate it against `schema` returning errors encountered if any and the input data. It's important to note that, validation continues even if an error is encountered. :param schem...
2,401
572
from common import small_buffer import pytest import numpy as np import pyarrow as pa import vaex def test_unique_arrow(df_factory): ds = df_factory(x=vaex.string_column(['a', 'b', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'a'])) with small_buffer(ds, 2): assert set(ds.unique(ds.x)) == {'a', 'b'} v...
3,194
1,275
# utility functions for frequency related stuff import numpy as np import numpy.fft as fft import math def getFrequencyArray(fs, samples): # frequencies go from to nyquist nyquist = fs/2 return np.linspace(0, nyquist, samples) # use this function for all FFT calculations # then if change FFT later (i.e. FFTW), j...
810
301
# -*- coding: utf-8 -*- # :Project: pglast -- Extract keywords from PostgreSQL header # :Created: dom 06 ago 2017 23:34:53 CEST # :Author: Lele Gaifax <lele@metapensiero.it> # :License: GNU General Public License version 3 or later # :Copyright: © 2017, 2018 Lele Gaifax # from collections import defaultdict f...
2,329
756
from collections import namedtuple from sublime import Region as R from VintageousPlus.tests import set_text from VintageousPlus.tests import add_sel from VintageousPlus.tests import ViewTest from VintageousPlus.vi.text_objects import find_indent_text_object test = namedtuple('simple_test', 'content start expected ...
1,913
675
import cv2 from imutils.paths import list_images import imutils import re import datetime from datasets.hdf5datasetwriter import HDF5DatasetWriter import progressbar def get_frame_number(impath): return int(re.search(r"image data (\d+)", impath).group(1)) def get_timestamp(impath): "assuming that the timestam...
1,417
499
#!/usr/bin/env python import matplotlib.pyplot as plt import numpy as np import time import cv2 from real.camera import Camera from robot import Robot from subprocess import Popen, PIPE def get_camera_to_robot_transformation(camera): color_img, depth_img = camera.get_data() cv2.imwrite("real/temp.jpg", color...
4,378
1,805
# Header starts here. from sympy.physics.units import * from sympy import * # Rounding: import decimal from decimal import Decimal as DX from copy import deepcopy def iso_round(obj, pv, rounding=decimal.ROUND_HALF_EVEN): import sympy """ Rounding acc. to DIN EN ISO 80000-1:2013-08 place value = Rundest...
3,708
1,974
#!/usr/bin/python3 import csv ucc_dictionary_file_list = [ './downloads/diary08/diary08/uccd08.txt', './downloads/diary09/diary09/uccd09.txt', './downloads/diary11/diary11/uccd11.txt', './downloads/diary10/diary10/uccd10.txt', ] cleaned_ucc_dictionary = dict() for dictionary in ucc_dictionary_file_l...
870
332
import datetime import os import traceback from inspect import ismethod from queue import Empty, Queue from threading import Event, Lock, Thread from time import sleep from typing import Dict, Optional, Tuple, Type import ray from eventsourcing.application.process import ProcessApplication from eventsourcing.applicat...
30,937
8,136
# Generated by Django 3.2.6 on 2021-08-23 14:34 import django.contrib.postgres.fields from django.apps.registry import Apps from django.db import migrations, models from django.db.backends.base.schema import BaseDatabaseSchemaEditor from authentik.stages.password import BACKEND_APP_PASSWORD, BACKEND_INBUILT def upda...
1,766
488
from django.test import TestCase from django.contrib.auth.models import User from article.models import Article, Category class ArticleModelTestCase(TestCase): def setUp(self): self.category = Category.objects.create(name=u'Sports') self.user = User.objects.create(username=u'test', password=u'sec...
1,211
347
import os , sys sys.path.append(os.getcwd()) import pytest from typehints_checker import * @pytest.mark.asyncio async def test_import(): ...
145
53
# -*- coding: utf-8 -*- """ Created on Nov 24, 2014 @author: moloch Copyright 2014 Root the Box 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/licen...
2,240
703
import glib import dbus from dbus.mainloop.glib import DBusGMainLoop from pyee import EventEmitter import logbook logger = logbook.Logger('connman-dispatcher') __all__ = ['detector'] def property_changed(_, message): if message.get_member() == "PropertyChanged": _, state = message.get_args_list() ...
1,278
402
#!/usr/bin/env python3 # # Copyright (c) 2015 - 2022, Intel Corporation # SPDX-License-Identifier: BSD-3-Clause # """ Runs an application with a large number of short regions and checks that the controller successfully runs. """ import sys import unittest import os import subprocess import glob import geopmpy.io i...
4,294
1,270
# Description: OptiAlign.py by Jason Vertree modified for aligning multiple RNA structures. # Source: Generated while helping Miranda Adams at U of Saint Louis. """ cmd.do('python') cmd.do(' ##############################################################################') cmd.do('#') cmd.do('# @SUMMARY: -- QKabsch.py...
13,627
5,499
test_input = """ L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL """ test_input2 = """ .......#. ...#..... .#....... ......... ..#L....# ....#.... ......... #........ ...#..... """ test_input3 = """ ............. .L.L.#.#.#.#. ............. """ test_input...
12,933
6,651
from SMA2CAgent import SMA2CAgent from A2CAgent import A2CAgent from RandomAgent import RandomAgent # from .SMA2CAgent import SMA2CAgent import gym import numpy as np from IPD_fixed import IPDEnv import axelrod import time import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.ad...
2,849
985
import heapq as h class MedianFinder: def __init__(self): self.rightHalf = [] self.leftHalf = [] def addNum(self, num: int) -> None: if len(self.leftHalf) > len(self.rightHalf): temp = h.heappush(self.leftHalf, -num) temp2 = h.heappop(self.leftHalf) ...
876
312
import pytest from app.domain.models.Metadatafil import Metadatafil, MetadataType from app.exceptions import InvalidContentType from app.routers.mappers.metadafil import _get_file_content, metadatafil_mapper, _content_type2metadata_type def test__content_type2metadata_type__success(): """ GIVEN the string ...
1,781
539
from django import template register = template.Library() RACK_SIZE_PX = 20 MARGIN_HEIGHT = 2 def _rack_unit_to_height(units): # for every unit over 1 add a 2 px margin margin = (units - 1) * MARGIN_HEIGHT return units * RACK_SIZE_PX + margin def _equipment_spacer(units): return { 'units': ...
2,748
988
import numpy as np import matplotlib.pyplot as plt from shamir import * from binascii import hexlify # img = plt.imread('cat.png') # plt.imshow(img) # plt.show() s = 'TEST_STRING'.encode() print("Original secret:", hexlify(s)) l = Shamir.split(3, 5, '12345'.encode()) for idx, item in l: print("Share {}: {}".fo...
442
179
"""Reverse stack is using a list where the top is at the beginning instead of at the end.""" class Reverse_Stack: def __init__(self): self.items = [] def is_empty(self): # test to see whether the stack is empty. return self.items == [] def push(self, item): # adds a new item to the bas...
825
283
from gerapy.server.manage import manage import sys def server(): # Call django cmd manage()
101
30
#!/usr/bin/env python import sys, tty, termios, array, fcntl, curses class TTYSettings(object): def __init__(self): self.tty_fd = sys.stdout.fileno() # save self.saved = termios.tcgetattr(self.tty_fd) self.win_size = self.get_win_size() self.rows, self.cols = self.win_size[0...
964
361
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions a...
25,123
7,728
"Test handling/parsing of various DAZ Studio files" from pathlib import Path from tempfile import NamedTemporaryFile from django.apps import apps from rendaz.daztools import ( DSONFile, ProductMeta, manifest_files, supplement_product_name, ) TEST_DIR = Path(__file__).parent def test_read_dson_com...
2,897
1,047
import random import string from typing import Union, List import torch import torch.nn as nn import torch.nn.functional as F from ..layers.common import EncoderRNN, DecoderRNN, dropout from ..layers.attention import * from ..layers.graphs import GraphNN from ..utils.generic_utils import to_cuda, create_mask from ..u...
20,000
6,674
# Copyright 2021 Zilliz. 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://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
2,939
793
from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length = 200, verbose_name = "Titulo") description = models.TextField(verbose_name="Descripcion") image = models.ImageField(verbose_name="Imagen", upload_to = "projects") link = mode...
744
241
# Copyright 2015–2020 Kullo GmbH # # This source code is licensed under the 3-clause BSD license. See LICENSE.txt # in the root directory of this source tree for details. from django.test import TestCase # Create your tests here.
231
76
#!/usr/bin/env python import signal import buttonshim print(""" Button SHIM: rainbow.py Command on button press. Press Ctrl+C to exit. """) import commands @buttonshim.on_press(buttonshim.BUTTON_A) def button_a(button, pressed): buttonshim.set_pixel(0x94, 0x00, 0xd3) s=commands.getstatusoutput("ra...
1,018
449
from .cascade_head import CascadeFCBBoxHead from .convfc_bbox_head import SharedFCBBoxHead __all__ = [ 'CascadeFCBBoxHead', 'SharedFCBBoxHead']
153
58
import datetime from .monzobalance import MonzoBalance from .monzopagination import MonzoPaging from .monzotransaction import MonzoTransaction class MonzoAccount(object): def __init__(self,api,json_dict=None): self.api = api self.account_id = None self.created = None self.descripti...
3,146
926
from typing import Dict, Optional from fastapi import status, Request from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from learninghouse.models import LearningHouseErrorMessage MIMETYPE_JSON = 'application/json' class LearningHouseException(Exception): STATUS_CO...
3,718
992
import pandas as pd def get_windowed_ts(ranged_ts, window_size, with_actual=True): """ Creates a data frame where each row is a window of samples from the time series. Each consecutive row is a shift of 1 cell from the previous row. For example: [[1,2,3],[2,3,4],[3,4,5]] :param ranged_ts: a pd.Da...
1,751
590
# Copyright (C) 2021 Markus Wallerberger and others # SPDX-License-Identifier: MIT import numpy as np import xprec def _compare_ufunc(ufunc, *args, ulps=1): fx_d = ufunc(*args) fx_q = ufunc(*(a.astype(xprec.ddouble) for a in args)).astype(float) # Ensure relative accuracy of 2 ulps np.testing.assert_...
1,310
629
from .read_hdf5 import * from .hdf5_api import *
48
20
from pathlib import Path from toolz import itertoolz, curried import vaex transform_path_to_posix = lambda path: path.as_posix() def path_to_posix(): return curried.valmap(transform_path_to_posix) transform_xlsx_to_vaex = lambda path: vaex.from_ascii(path, seperator="\t") def xlsx_to_vaex(): return curr...
932
376
import PIL from PIL import Image from io import BytesIO import re def resize(s3_client, bucket, original_key, width, height, suffix): obj = s3_client.get_object(Bucket=bucket, Key=original_key) full_size_key = original_key.replace('__incoming/', '') ext = re.sub(r'.+\.([^.]+)$', r'\1', full_size_key) ...
1,409
503
# Copyright 2018-2021 The Matrix.org Foundation C.I.C. # # 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...
4,792
1,448
import tempfile import maya.OpenMaya as OpenMaya import maya.OpenMayaRender as OpenMayaRender import maya.OpenMayaMPx as OpenMayaMPx import maya.cmds as cmds import maya import re from maya.app.edl.fcp import * class ImportExport(OpenMayaMPx.MPxCommand): def __del__(self): pass def __init__(...
2,205
679
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 2006-2010 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~...
1,040
309
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todolist.settings') application = get_wsgi_application()
169
61
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of CERN Search. # Copyright (C) 2018-2021 CERN. # # Citadel Search is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line utilities.""" import json import c...
4,501
1,508
__author__ = 'wektor' from generic import GenericBackend import redis class RedisBackend(GenericBackend): def __init__(self): pool = redis.ConnectionPool(host='localhost', port=6379, db=0) self.store = redis.Redis(connection_pool=pool) def get_typecode(self, value): typecode = str...
906
279
# Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from collections import namedtuple from time import sleep try: from botocore.exceptions impor...
11,288
3,415
# Uppercases string one character at a time from cs50 import get_string s = get_string("Before: ") print("After: ", end="") for c in s: print(c.upper(), end="") print()
176
62
from datetime import datetime from pathlib import Path import pytz import kobuddy def get_test_db(): # db = Path(__file__).absolute().parent.parent / 'KoboShelfes' / 'KoboReader.sqlite.0' db = Path(__file__).absolute().parent / 'data' / 'kobo_notes' / 'input' / 'KoboReader.sqlite' return db # a bit meh, ...
2,050
749
from django.shortcuts import render from .models import Tank from django.db import models from django.http import HttpResponse from django.views import View # Create your views here. # The view for the created model Tank def tank_view(request): queryset = Tank.objects.all() context = { 'object': quer...
1,062
355