text
string
size
int64
token_count
int64
import pandas as pd import numpy as np print(pd.__version__) # 1.0.0 print(pd.DataFrame.agg is pd.DataFrame.aggregate) # True df = pd.DataFrame({'A': [0, 1, 2], 'B': [3, 4, 5]}) print(df) # A B # 0 0 3 # 1 1 4 # 2 2 5 print(df.agg(['sum', 'mean', 'min', 'max'])) # A B # sum 3.0 12.0 # mean ...
4,230
1,971
from flask_sqlalchemy import SQLAlchemy from flask_user import UserMixin from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) db = SQLAlchemy() class User(db.Model, UserMixin): __tablename__ = 'user' id = db.Column(db.Integer, prima...
4,016
1,408
import json from urllib.parse import urlencode import requests from bs4 import BeautifulSoup from .api import BitflyerApi class BitflyerApiWithWebOrder(BitflyerApi): def __init__(self, ccxt, login_id, password, account_id, device_id=None, device_token=None): super().__init__(ccxt) ...
6,324
1,977
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : train.py @Contact : 3289218653@qq.com @License : (C)Copyright 2021-2022 PowerLZY @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2021-10-04 15:03 PowerLZY&yuan_mes ...
2,969
1,053
from enum import Enum from typing import Tuple, Type, Optional class Mode(Enum): SIMPLE = "s" EXTENDED = "e" def __str__(self) -> str: return self.value class Header(Enum): PATH = "Path" NAME = "Name" SIZE = "Size" MODIFIED = "Modified" ACCESSED = "Accessed" INPUT = "Inp...
453
168
#!/usr/bin/env python3 # (c) 2021 Martin Kistler from abc import ABC, abstractmethod from enum import Enum from os import linesep from twisted.internet import reactor from twisted.internet.error import ConnectionDone from twisted.internet.protocol import Factory, Protocol from twisted.logger import Logger from twiste...
6,190
1,878
def second_task(**context): print("This is ----------- task 2") return "hoge======" def third_task(**context): output = context["task_instance"].xcom_pull(task_ids="python_task_2") print("This is ----------- task 3") return "This is the result : " + output
279
90
""" MARKDOWN --- YamlDesc: CONTENT-ARTICLE Title: python builtin class attributes MetaDescription: python object oriented programming class builtin attributes __doc__, __name__, __module__, __bases__ example code, tutorials MetaKeywords: python object oriented programming class builtin attributes __doc__, __name__, __m...
1,803
565
from flask import Blueprint, render_template,redirect,url_for,request,flash,make_response from flask import current_app as app from flask_login import ( LoginManager, current_user, login_required, login_user, logout_user, UserMixin, ) from ..models import User, db from ..security import hash_str...
2,950
761
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time from math import atan2, degrees import board import busio import adafruit_mpu6050 class GY521_MPU6050(): def __init__(self, id=None, address=0x68) -> None: self.id_sensor = id self.i2c = busio.I2C(board.SCL, board.SDA) self.mpu = adafruit_mpu60...
2,072
876
#!/usr/bin/env python # -*- coding: Latin-1 -*- """ @file TaxisPerEdge.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-04-08 @version $Id$ Counts for every edge in the given FCD-file the number of Taxis which used this edge. After that this information can be visualized w...
1,832
618
''' Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/ Author : Yuan Wang Date : 2018-07-21 /********************************************************************************** *Given a binary tree, find its maximum depth. * *The maximum depth is the number of nodes along the longest path from the ...
879
312
import os import re from cli.mmt import MMT_HOME_DIR, MMT_LIB_DIR, MMT_BIN_DIR, MMT_JAR, MMT_PLUGINS_JARS from cli.utils import osutils def __get_java_version(): try: stdout, stderr = osutils.shell_exec(['java', '-version']) java_output = stdout + '\n' + stderr for line in java_output.sp...
6,358
2,276
#AUTHOR : HAMORA HADI """ You have been given a stack of documents that have already been processed and some that have not. Your task is to classify these documents into one of eight categories: [1,2,3,...8]. You look at the specifications on what a document must contain and are baffled by the jargon. However...
2,497
776
""" generates lists of SARS-CoV-2 samples which occurred before a particular date Also generates a dictionary of reference compressed sequences And a subset of these Together, these can be passed to a ram_persistence object which can be used instead of an fn3persistence object to test the performance of PCA, or for o...
4,232
1,457
import os import re import pickle import numpy as np import pandas as pd from tqdm import tqdm # Assign labels used in eep conversion eep_params = dict( age = 'Age (yrs)', hydrogen_lum = 'L_H', lum = 'Log L', logg = 'Log g', log_teff = 'Log T', core_hydrogen_frac = 'X_core', # must be added ...
7,476
2,642
from com.vividsolutions.jts.io import WKTReader, WKTWriter from geoscript.util import deprecated def readWKT(wkt): """ Constructs a geometry from Well Known Text. *wkt* is the Well Known Text string representing the geometry as described by http://en.wikipedia.org/wiki/Well-known_text. >>> readWKT('POINT (1...
685
276
import os import dj_database_url import dotenv from .base import BASE_DIR env = BASE_DIR / '.env' dotenv.read_dotenv(env) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["multiple-vendor-e-commerce.herokuapp.com"] # Database # https://docs.djangoproject.com/en/3....
1,053
444
from django.views import View from django.http import JsonResponse from tracker.models import Match from tracker.forms import MatchForm import json class MatchView(View): def put(self, request): try: body = request.body.decode('utf-8') body = json.loads(body) except json.decoder.JSONDecodeError as ex: ...
638
234
from precise.covariance.movingaverage import ema_scov from precise.covariance.matrixfunctions import grand_mean, grand_shrink from sklearn.covariance._shrunk_covariance import ledoit_wolf_shrinkage import numpy as np # Experimental estimator inspired by Ledoit-Wolf # Keeps a buffer of last n_buffer observations # Tra...
2,400
1,031
from setuptools import setup, find_packages with open('README.md') as f: long_description = f.read() setup(name='Text2CArray', version='0.1.0', description='Script for generating C arrays from text.', long_description=long_description, long_description_content_type='text/markdown', # This i...
704
225
VARIABLE_1 = 10 VARIABLE_2 = 20
32
22
import json import os.path import operator import time from multiprocessing import Pool import markovify from tqdm import tqdm removeWords = ['c', 'tsp', 'qt', 'lb', 'pkg', 'oz', 'med', 'tbsp', 'sm'] removeWords2 = [" recipes "," recipe "," mashed "," fat ",' c. ',' c ','grams','gram','chopped','tbsps','tbsp','cups',...
7,708
2,579
from nanome._internal._structure._complex import _Complex from nanome._internal import _PluginInstance from nanome._internal._network import PluginNetwork from nanome._internal._network._commands._callbacks import _Messages from nanome.util import Matrix, Logs from .io import ComplexIO from . import Base class Comple...
11,740
3,363
from django.db import models from django.contrib.postgres.fields import ArrayField from django.urls import reverse # Create your models here. class Neighbourhood(models.Model): image = models.ImageField(upload_to='neighbourhood_avatars', default='dummy_neighbourhood.jpg') name = models.CharField(max_length=2...
1,862
623
from doubly_linked_list import DoublyLinkedList class TextBuffer: def __init__(self): self.storage = DoublyLinkedList() # return a string to the print function def __str__(self): # build a string s = "" current_node = self.storage.head while current_node: ...
1,932
605
# -*- coding: utf-8 -*- """ This file holds user profile information. (The base User model is part of Django; profiles extend that with locally useful information.) TWLight has three user types: * editors * coordinators * site administrators. _Editors_ are Wikipedia editors who are applying for TWL resource acce...
14,911
4,078
import numpy as np import pandas as pd import tensorflow as tf import itertools import datetime import os from sklearn.metrics import roc_auc_score from model import mlp, lognormal_nlogpdf, lognormal_nlogsurvival from model_reddit import load_batch from train_reddit import get_files from train_mimic import rae_over_s...
14,694
7,029
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # 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 appli...
1,272
385
# -*- coding: utf-8 -*- import json from django.db import models, migrations DIARY_KEYS = (0, 3, 4, 17, 20001, 20002, 20003, 40000, 40001, 40002, 40003, 40004, ...
4,392
1,642
import sys sys.path.append("../src") import numpy as np import matplotlib.pyplot as plt import seaborn as sns import C_calculation plt.style.use(['seaborn-deep', '../paper.mplstyle']) """ This script produces Figure S3, which displays a detailed summary of the calculations used to determine a suitable value for C. ...
1,764
780
#Faça um Programa que leia um vetor de 5 números inteiros e mostre-os. lista=[] for i in range(1, 6): lista.append(int(input('Digite um número: '))) print(lista)
167
66
from enum import Enum class TradeStatus(Enum): PENDING_ACCEPT = 0 PENDING_CONFIRM = 1 PENDING_CANCEL = 2 CANCELED = 3 CONFIRMED = 4 FAILED = 5
169
79
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ======================== SBPy Vega Sources Module ======================== Descriptions of source Vega spectra. """ # Parameters passed to Vega.from_file. 'filename' is a URL. After # adding spectra here update __init__.py docstring and # docs/sbpy...
522
205
import os os.environ["KERAS_BACKEND"] = "tensorflow" import numpy as np import keras from keras.applications import imagenet_utils from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.preprocessing import image from k...
3,455
1,288
def divide_by_four(input_number): return input_number/4 result = divide_by_four(16) # result now holds 4 print("16 divided by 4 is " + str(result) + "!") result2 = divide_by_four(result) print(str(result) + " divided by 4 is " + str(result2) + "!") def calculate_age(current_year, birth_year): age = current_yea...
506
206
from adjutant.api.v1.models import register_taskview_class from mfa_views import views register_taskview_class(r'^openstack/edit-mfa/?$', views.EditMFA) register_taskview_class(r'^openstack/users/?$', views.UserListMFA)
223
84
# Copyright (c) 2015-2019 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. import numpy as np from astropy.io import fits from ..op import Operator from ..timing import function_timer from .tod_mat...
3,194
971
# Janssen Project software is available under the Apache 2.0 License (2004). See http://www.apache.org/licenses/ for full text. # Copyright (c) 2020, Janssen Project # # Author: Madhumita Subramaniam # from io.jans.service.cdi.util import CdiUtil from io.jans.as.server.security import Identity from io.jans.model.custo...
7,652
2,034
from django.db import models # classification value objects CHOICES_CLASSIFICATION = [ (0, 'unrelated'), (1, 'simple'), (2, 'complex'), (3, 'substring'), ] class Abbreviation(models.Model): long_form = models.TextField(blank=False) abbreviation = models.CharField(max_length=100, blank=False) classification =...
384
137
# This code could be improved but its just a example on how to use the code from the site import requests, base64, random, string token = input("Put code here:\n") headers = { 'authority': 'auth.roblox.com', 'dnt': '1', 'x-csrf-token': requests.post("https://auth.roblox.com/v2/login").headers["x-csrf-tok...
1,709
684
from django.db import models class Roles(models.TextChoices): USER = 'user', 'User' MODERATOR = 'moderator', 'Moderator' ADMIN = 'admin', 'Admin'
160
60
import re from datetime import datetime from PyInquirer import Validator, ValidationError from prompt_toolkit.document import Document # This file contains functions used for validation and Validator classes that use them. # Validators are used by questions. def non_empty(document: Document) -> bool: if not doc...
6,161
1,912
# The MIT License (MIT) # # Copyright (c) 2019 Niklas Rosenstein # # 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 # to use, copy,...
7,113
2,303
import filecmp import os import sys import shutil import subprocess import time import unittest if (sys.version_info > (3, 0)): import urllib.request, urllib.parse, urllib.error else: import urllib from optparse import OptionParser from PyQt4 import QtCore,QtGui parser = OptionParser() parser.add_option("-r",...
15,208
5,078
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Here is the class that controls the bot. It also contains various value manipulation, and one function that lets the bot play one round, from first roll until hold. The intelligence is basically how many rolls the bot is going to do on one round. The easier level on t...
2,174
660
import datetime import logging from typing import Optional from .types import CheckerTaskMessage, EnoLogMessage LOGGING_PREFIX = "##ENOLOGMESSAGE " class ELKFormatter(logging.Formatter): def format(self, record: logging.LogRecord) -> str: if type(record.args) is tuple and len(record.args) > 0: ...
2,068
631
# # 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 us...
3,191
1,041
import os as os from pandas import pandas as p from pandas.compat import StringIO, BytesIO class ReadCsv: def __init__(self, base_dir): self.base_dir = base_dir @staticmethod def all_files(base_path): all_files = [] for file in os.scandir(base_path): if file.is_file()...
1,240
390
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 30 15:28:09 2018 @author: dataquanty """ import numpy as np from math import sqrt, pi, acos,cos from matplotlib import pyplot as plt from scipy.misc import imsave from bisect import bisect_left h , w = 1000, 1000 img = np.ones((h,w)) center = (...
1,364
621
import os import sys sys.path.append('..') import mitogen VERSION = '%s.%s.%s' % mitogen.__version__ author = u'David Wilson' copyright = u'2018, David Wilson' exclude_patterns = ['_build'] extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinxcontrib.programoutput'] html_show_sourcelink = False html_s...
1,083
416
from caendr.services.cloud.postgresql import db from caendr.models.sql.dict_serializable import DictSerializable from sqlalchemy import func, or_ from sqlalchemy.ext.hybrid import hybrid_property class WormbaseGeneSummary(DictSerializable, db.Model): """ This is a condensed version of the WormbaseGene model; ...
1,741
620
from django.core.exceptions import ValidationError from django.db import models from django.forms.models import model_to_dict from decimal import Decimal # Create your models here. class ProductManager(models.Manager): def top_drops(self, n): return self.get_queryset().order_by('-price_drop')[:n] de...
4,137
1,252
# Copyright 2017-present Open Networking Foundation # # 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 agr...
1,890
624
""" Testing Wiki Module """ import unittest from ddt import ddt, data, unpack from ashaw_notes.plugins.wiki import Plugin @ddt class PluginTests(unittest.TestCase): """Unit Testing Plugin""" @unpack @data( (1373500800, 'today: derp note', 'today: derp note'), (137350080...
952
334
#!/usr/bin/env python3 """Converts Cppcheck XML version 2 output to JUnit XML format.""" import argparse import collections from datetime import datetime import os from socket import gethostname import sys from typing import Dict, List from xml.etree import ElementTree from exitstatus import ExitStatus class Cppch...
5,956
1,789
import pytest from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.sites.models import Site from core.models import Identity from organizations.models import Organization @pytest.fixture def valid_identity(): id_string = 'valid@user.test' user = get_user_model()...
2,440
771
# -*- coding: utf-8 -*- """Tests for Descriptor.""" import unittest import numpy as np import orjson from prodec import Descriptor from prodec.utils import std_amino_acids from tests.constants import * class TestDescriptor(unittest.TestCase): """Tests for Descriptor.""" def setUp(self): """Cr...
4,041
1,623
from .env import get_root_logger, init_dist, set_random_seed from .inference import inference_detector, init_detector, show_result from .train import train_detector __all__ = [ 'init_dist', 'get_root_logger', 'set_random_seed', 'train_detector', 'init_detector', 'inference_detector', 'show_result' ]
310
105
#! /usr/bin/env python3 ''' Examine a CherryTree SQLite database and print out the tree in proper heirarchical form and sequence. ''' import argparse import colorama from colorama import Fore, Back, Style import sqlite3 from ct2ad import * def print_xc_node(xc_node, level): ''' Print the node information to...
1,544
571
#!/usr/bin/env python import sys sys.path.append('/opt/lib/python2.7/site-packages/') import math import numpy as np import pylab import nest import nest.raster_plot import nest.voltage_trace import nest.topology as tp import ggplot t_sim = 500 populations = [1, 100] no_recurrent = True neuron_model = 'iaf_psc_e...
2,559
1,060
from django.shortcuts import render,redirect,get_object_or_404 from .forms import * from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import * from django.views.generic import DetailView,DeleteView from django.urls import reverse_lazy from test2.notification impo...
21,008
6,233
__version__ = '0.9.3' from .lock import Lock # noqa from .lock import NeedRegenerationException # noqa
106
38
from pyssian.chemistryutils import is_basis,is_method import unittest class ChemistryUtilsTest(unittest.TestCase): def setUp(self): self.Valid_Basis = '6-311+g(d,p) 6-31g* cc-pVTZ D95V* LanL2DZ SDD28 Def2SVP UGBS2P2++'.split() self.Fake_Basis = '6-311g+(d,p) 6-31*g ccpVTZ D96V* LanL2TZ SDD Def2SP U...
1,550
569
# This is what requests does. try: import simplejson as json except ImportError: import json import logging import requests from .exceptions import * _PROTOCOL = 'https://' _BASE_URL = '{}api.life360.com/v3/'.format(_PROTOCOL) _TOKEN_URL = _BASE_URL + 'oauth2/token.json' _CIRCLES_URL = _BASE_URL + 'circles.j...
4,415
1,339
import numpy as np import pandas as pd import pytest @pytest.fixture def dta(): return pd.DataFrame.from_dict( { 'A': np.arange(1, 16), 'B': pd.date_range('2020-01-01', periods=15), 'C': ['A', 'B', 'C'] * 5, 'D': pd.Categorical(['A', 'B', 'C'] * 5), ...
328
133
""" Objectives: - Which players pass together the most? - What types of position combintations are most frequent in pass-sequences? """ """ Sample Run Script: python manage.py analysis3 --team_uuid="t1326" --print_to_csv python manage.py analysis4 --team_uuid="t1326" --start_date="2016-07-01" python ...
2,976
1,087
from .stock import Stock class Portfolio: def __init__(self, assets): self.stocks = [] self.__populate_stocks(assets) def get_stock(self, stock_name): for stock in self.stocks: if stock.name == stock_name: return stock return None def get_prof...
1,474
456
# %% from HARK.utilities import CRRAutility_inv from time import time import matplotlib.pyplot as plt import numpy as np from HARK.ConsumptionSaving.ConsMedModel import MedShockConsumerType # %% mystr = lambda number: "{:.4f}".format(number) # %% do_simulation = True # %% [markdown] # This module defines consumption...
4,694
1,738
import discord from discord.ext import commands import asyncio import aiohttp import random from datetime import datetime, timedelta import math import json # ##################################################################################### # math parser used by $calc class MathParser: def __init_...
25,325
8,026
##################### ### Base classes. ### ##################### class barrier: synonyms = ["wall"] m_description = "There is a barrier in the way." def __init__(self, passable=False): self.passable = passable def __str__(self): return self.m_description def ...
1,481
440
#!/usr/bin/env ipython import numpy as np #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ class gral(): def __init__(self): self.name = '' sh, mc = gral(), gral() cr = gral() cr.sh, cr.mc = gral(), gral() vlo, vhi = 550.0, 3000.0 #550., 3000. #100.0, 450.0 #...
1,171
625
# Copyright 2018-2019 CRS4 # # 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, softwa...
3,090
1,132
import logging from django.apps import apps from django.contrib.auth.mixins import LoginRequiredMixin from django.http import Http404, HttpResponse, JsonResponse from django.views.generic import TemplateView, View from zentral.core.stores import frontend_store logger = logging.getLogger("server.base.views") class H...
2,598
762
g1 = "#5d9e6d" g2 = "#549464" g3 = "#498758" g4 = "#3d784b" b1 = "#5f7ab8" b2 = "#5a70a3" b3 = "#4d67a3" r4 = "#262626" w1 = "#f0f0f0" w2 = "#d9d9d9" w3 = "#e6e6e6" r1 = "#707070" r2 = "#595959" r3 = "#404040" r4 = "#262626" l1 = "#d95757" l2 = "#d99457" l3 = "#d97857" v1 = "#664f47" v2 = "#4a3d39" v3 = "#382f2c" v4 = ...
176,775
98,907
useless_facts = ["Most American car horns honk in the key of F.", "The name Wendy was made up for the book 'Peter Pan.'", "Barbie's full name is Barbara Millicent Roberts.", "Every time you lick a stamp, you consume 1/10 of a calorie.", "The average person falls asleep in seven minutes.", "Studies s...
172,689
48,189
from libqtile.widget import base from libqtile import bar, hook __all__ = ['She'] class She(base._TextBox): ''' Widget to display the Super Hybrid Engine status. can display either the mode or CPU speed on eeepc computers.''' defaults = [ ('device', '/sys/devices/platform/eeepc/cpufv', 'sys path...
1,502
487
#!/usr/bin/env python from contextlib import contextmanager import os import sys import time srcdir = os.path.dirname(os.path.dirname(__file__)) sys.path.insert(0, srcdir) from ukt import * script = os.path.join(srcdir, 'scripts/kt.lua') server = EmbeddedServer(database='%', server_args=['-scr', script], ...
1,490
573
description = 'Some kind of SKF chopper' pv_root = 'LabS-Embla:Chop-Drv-0601:' devices = dict( skf_drive_temp=device('nicos.devices.epics.pva.EpicsReadable', description='Drive temperature', readpv='{}DrvTmp_Stat'.format(pv_root), monitor=True, ), skf_motor_temp=device('nicos.devic...
2,260
837
class BaseSelector: def __init__(self): pass def select_model(self, X, y, total_time, learners=None, metric=None, save_directory=None): """ Find the best model with its hyperparameters from the autotf's...
1,111
288
nothing = None
16
6
# # 5. Алфавитный переводчик номера телефона. Многие компании используют телефонные # # номера наподобие 555-GET-FOOD, чтобы клиентам было легче запоминать эти номера. # # На стандартном телефоне буквам алфавита поставлены в соответствие числа следующим # # образом: А,В и С=2 ; D,Е и F=З. phone_num = input('nnn-XXX-XXX...
1,623
578
from django.urls import path from .views import index, users, weather app_name = 'admin' urlpatterns = [ path('', index.index, name='index'), path('users/', users.index, name='users.index'), path('users/add', users.add, name='users.add'), path('users/update', users.update, name='users.update'), pat...
450
152
import sys import requests from statistics import mean, stdev from bs4 import BeautifulSoup import matplotlib.pyplot as plt class Disco(): def __init__(self, artist): self.website_url = "https://en.wikipedia.org" disco_soup = self.get_disco_soup(artist) album_urls = self.get_album_urls(dis...
3,360
1,093
#!/usr/bin/env python # # This is a CIA client script for Subversion repositories, written in python. # It generates commit messages using CIA's XML format, and can deliver them # using either XML-RPC or email. See below for usage and cuztomization # information. # # ----------------------------------------------------...
15,013
4,315
# Given a list x of length n, a number to be inserted into the list and a position where to insert the number # return the new list # e.g given [2, 3, 6, 7], num=8 and position=2, return [2, 3, 8, 6, 7] # for more info on this quiz, go to this url: http://www.programmr.com/insertion-specified-position-array-0 def ins...
493
188
from django.conf.urls import url from .views import ( add, clear, remove, remove_single, set_quantity, show ) urlpatterns = [ url(r'^show/$', show, name='carton-tests-show'), url(r'^add/$', add, name='carton-tests-add'), url(r'^remove/$', remove, name='carton-tests-remove'), u...
530
194
# Spectrum Analyzer Code Author: Caleb Wolfe import time import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import numpy as np class SpectrumAnalyzer: def __init__(self,smprate=44100,senistivity=100.0,samplesize=1024): self.__samplerate =smprate self....
4,798
1,644
from haystack.forms import FacetedSearchForm from haystack.query import SQ from django import forms from hs_core.discovery_parser import ParseSQ, MatchingBracketsNotFoundError, \ FieldNotRecognizedError, InequalityNotAllowedError, MalformedDateError FACETS_TO_SHOW = ['creator', 'contributor', 'owner', 'content_typ...
7,992
2,372
from typing import Any, Dict, List import datetime import pandas as pd import plotly.express as px import plotly.figure_factory as ff import plotly.graph_objects as go import streamlit as st from fbprophet import Prophet from fbprophet.plot import plot_plotly from plotly.subplots import make_subplots from streamlit_p...
26,096
8,318
from datetime import date, datetime, timedelta from django.conf import settings from django.conf.urls import url from django.contrib.admin import register, ModelAdmin from django.http import HttpResponse import pytz import xlsxwriter from .models import Computer, Mobile, EC2Instance, FreshdeskTicket, LicensingRule @r...
9,343
2,734
from django.test import Client from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from model_mommy import mommy from django.conf import settings User = get_user_model() class RegisterViewTestCase(TestCase): def setUp(self): self.client = Client(...
3,093
996
""" DUNE CVN generator module. """ __version__ = '1.0' __author__ = 'Saul Alonso-Monsalve, Leigh Howard Whitehead' __email__ = "saul.alonso.monsalve@cern.ch, leigh.howard.whitehead@cern.ch" import numpy as np import zlib class DataGenerator(object): ''' Generate data for tf.keras. ''' def __init__(self, ...
3,360
996
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf def show_batch(ds: tf.data.Dataset, classes: list, rescale: bool = False, size: tuple = (10, 10), title: str = None): """ Function to show a batch of images including labels f...
2,139
672
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Makina custom grains ===================== makina.upstart true if using upstart makina.lxc true if inside an lxc container makina.docker true if inside a docker container makina.devhost_num devhost num if any ''' import os import copy import subprocess...
8,078
2,815
import requests import os EXISTING_ROOT_PEM = requests.certs.where() root_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..", "..")) LOCAL_DEV_CERT = os.path.abspath(os.path.join(root_dir, 'eng', 'common', 'testproxy', 'dotnet-devcert.crt')) COMBINED_FILENAME = os.path.basename(LOCAL_DEV_CERT).s...
1,390
558
from cgi import FieldStorage from datetime import date from io import BytesIO from onegov.core.utils import Bunch from onegov.form import Form from onegov.wtfs.fields import HintField from onegov.wtfs.fields import MunicipalityDataUploadField class PostData(dict): def getlist(self, key): v = self[key] ...
1,866
654
class Cluster(object): """ Object for grouping sets of sites. """ def __init__(self, sites): """ Initialize a cluster instance. Args: sites (list(Site)): The list of sites that make up the cluster. Returns: None """ self.sites = set(site...
3,339
1,085
from airflow import DAG from airflow.utils.dates import days_ago from anyway_etl_airflow.operators.cli_bash_operator import CliBashOperator dag_kwargs = dict( default_args={ 'owner': 'airflow', }, schedule_interval='@weekly', catchup=False, start_date=days_ago(2), ) with DAG('cbs', **da...
2,156
725
import os import boto3 from automation_infra.utils import concurrently from functools import partial def clear_bucket(boto3_client, bucket_name): boto3_client.delete_bucket(Bucket=bucket_name) def clear_all_buckets(boto3_client): bucket_names = [bucket['Name'] for bucket in boto3_client.list_buckets()['Buck...
1,069
371