index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
17,300
dd24c22f5ecb13eefac3be66e3a8aede4a750867
""" @author: Ferdinand E. Silva @email: ferdinandsilva@ferdinandsilva.com @website: http://ferdinandsilva.com """ import os class qqFileUploader(object): def __init__(self, allowedExtensions = [], sizeLimit = 1024): self.allowedExtensions = allowedExtensions self.sizeLimit = sizeLimit...
17,301
6c7a8df13d243d691f94c81f55b4390dc965f532
import pandas as pd import numpy as np import os import sys import time from getArgs import getArgs from getConfig import getConfig from getData import getData from getModelParms import getParms from preProcess import preProcess from nn import run from calcMAPE import calcMAPE from calcRMSE import ...
17,302
1b66a5953f1dba8e310661570d43ea5695738197
# get the list of clusters in the account import boto3 import datetime import json import pprint ecs_client = boto3.client('ecs') cw_client = boto3.client('cloudwatch', region_name='us-east-1') ec2_client = boto3.client('ec2') asg_client = boto3.client('autoscaling') def cluster_list(): return ecs_client.list_clus...
17,303
1266c10d0834fb0cff11560eda342f149333632a
#Professor Fernando Amaral #2 Calculadora de somar inteiros val1 = input("Informe o primeiro valor: ") val2 = input("Informe o segundo valor: ") val1 = int(val1) val2 = int(val2) val3 = val1 + val2 print("Total dos valores: ", val3) #segunda versao val1 = input("Informe o primeiro valor: ") val2...
17,304
da611729e7bafd2d807c7905178b4fc19557babc
# Generated by Django 1.11.6 on 2017-10-17 12:10 from django.db import migrations, models import pretalx.submission.models.submission class Migration(migrations.Migration): dependencies = [ ("submission", "0010_auto_20171006_1118"), ] operations = [ migrations.AddField( model...
17,305
a3b844c3dce3b1294eaa08179eb6ad055d6c7536
import pytest from typing import List def circular_rotation(array: List[int], rotations: int) -> List[int]: rotations = rotations % len(array) array = array[-rotations:] + array[:-rotations] return array @pytest.fixture def get_fixtures(): first_input = [ [1, 2, 3], 2 ] first_out...
17,306
328387f44b0a99e0d28498df605e83b7497b201b
ag = "kuty" # write a function that gets a string as an input and appends an a character to its end def appendA(text): return text + "a" ag = appendA(ag) print(ag)
17,307
8fdc059728bf11a0a45e80ea46aadfa0c97a8e8e
def maxProfit(prices): min_price = prices[0] max_profit = -float('inf') for i in range(1, len(prices)): if prices[i] < min_price: min_price = prices[i] else: max_profit = max(max_profit, (prices[i] - min_price)) return max_profit prices = [10, 7, 5, 8, 11, 9] ...
17,308
1e9630b51dd0cec9507cc8ef69a469715c7dea92
"""" A ride in an Amusement park starts at the ground level. it moves either up or down. Write a program to count the number of sinks. A raise is defined as a move above ground from start position followed by any string of moves up or down until the ride reaches the start position again. A sink is defined as a move bel...
17,309
9fcaf27df8cfab03dff0b7fb45a900ed9f5815a7
import numpy as np import pandas as pd import matplotlib.pyplot as plt from timeseries import convert_data_to_timeseries input_file='data_timeseries.txt' data1 = convert_data_to_timeseries(input_file,2) data2 = convert_data_to_timeseries(input_file,3) dataframe=pd.DataFrame({'first':data1,'second':data2}) d...
17,310
df59b2d76095910e0c126ae204938ca2d0747f4e
def rotate_left(arr, count): ''' In place left rotation: temp = arr[:count] arr = arr[count:] arr.extend(temp) ''' return arr[count:] + arr[:count] def main(): n, d = map(int, input().split()) arr = list(map(int, input().split())) print(f'Input array: {arr}') print(f'Rot...
17,311
a5e42410c7c7ba586a3b1b27ec322900e596d65b
""" Parses data and returns download data. """ import logging import re import string from os import PathLike from os.path import join, realpath, splitext from typing import Dict, List, Optional, Tuple from ..models import (AnimeListSite, AnimeThemeAnime, AnimeThemeEntry, AnimeThemeTheme, AnimeTh...
17,312
a59fab43ad5ff9f0f4c152fdd714b76901fc864c
from astropy.coordinates import SkyCoord def parse_coords(s): if 'RA' in s['CTYPE2']: frame = 'fk5' if 'GLON' in s['CTYPE2']: frame = 'galactic' skyc = SkyCoord(s['CRVAL2'],s['CRVAL3'],unit='deg',frame=frame) glon = (skyc.galactic.l.degree)[0] glat = (skyc.galactic.b.degree)[0] ...
17,313
d19c500afdfe0611fea0a47d67e3a86aeee0c319
from sys import * script, weather_info = argv d = {} with open(weather_info, 'r', encoding = 'utf-8') as f: for line in f.readlines(): l = line.strip().split(',') d[l[0]] = l[1] # line = f.readline() # while line: # l = line.strip().split(',') # d[l[0]] = l[1] # ...
17,314
e2f1c2d6a369f2ca804892aa5fbff947221c1a3d
### # [PROG] : Smallest and largest number in a list # [LANG] : Python # [AUTH] : BooeySays # [DESC] : Enter a bunch of numbers and the script will start # when a negative number is entered. After, it will # spit out the smallest and the largest number from # the list. # [EDTR] : PyCh...
17,315
66f2b3b0962175e0c3408550e32f2de0187770e5
def leapyears(x): if(x%400 == 0): y = "The year " + str(x) + " is a 400-leap year" return(y) if(x%100 == 0): y = "The year " + str(x) + " is not a leap year" return(y) else: if(x%4 == 0): y = "The year " + str(x) + " is a leap year"...
17,316
502a57b72a9abaac004927ee808bea5ee4c03733
from InstrumentServiceBack.settings.base import * CURRENT_ENV = 'dev'
17,317
6849cd20932c0ae2decb6f6b3391a4e0e1743b6d
#!/usr/bin/env python # # Schulze Voting Scheme # https://en.wikipedia.org/wiki/Schulze_method # Input is an iterable of ballots # All ballots must have the same candidates # Each ballot must have all candidates # # A ballot is a list of candidates, with candidates occuring earlier # in the list being prefered over c...
17,318
38f31c0c25a9071ffc79b8fe4ff40307ef431a4b
#!/usr/bin/env python # Copyright 2015, Institute for Systems Biology. # 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 app...
17,319
50edaa69803048edb84a838e37b6ec9fa662e3de
from typing import Tuple, Dict import difftools.maximization as dm import difftools.algebra as da import numpy as np from joblib import Parallel, delayed from numba import njit from numba.pycc import CC cc = CC("trial") @cc.export("trial_with_sample_jit", "(i8, i8, i8, i8[:,:], f8[:,:], f8[:,:])") @njit def trial...
17,320
e9cd8c60772e1a4da21dcb172e3d0aa69906a123
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2014-08-08 20:12:27 import time from sqlalchemy import INTEGER, Column, Integer, String, select, text, update from sqlalchemy.dialects.mysql import TINYIN...
17,321
e7d205d25a2a30eb95dfd3df8f6ece8525fbaf51
#24 2628 하 수학 종이자르기 ###메모리 초과..#### ''' #가로 세로 width, height = map(int, input().split()) #자르는 횟수 n = int(input()) #자르는 위치 cut_garo = [] cut_sero = [] boxes = [] for i in range(n): temp = [int(x) for x in input().split()] # print(temp) if temp[0] == 0: cut_garo.append(temp[1]) else: cu...
17,322
e17b12b90c4e48b0dc976617633f851b35f4587b
# -*- coding: utf-8 -*- """ @author: Wei, Shuowen https://leetcode.com/problems/shortest-distance-from-all-buildings/ https://blog.csdn.net/qq_37821701/article/details/108906696 """ import collections class Solution: def shortestDistance(self, grid): def helper(i,j): visited = set() ...
17,323
3d9693593d26a18534aa1f3eca5447d2ddb7bcd2
# 4: Maak nu één functie ‘print_dictionary’ die de verschillende elementen overloopt waarbij # telkens key & value samen op één lijn worden afgeprint. # De functie heeft als parameters een naam (voor de dictionary) en de dictionary zelf. # Voorbeeld: def print_dictionary (dict, naam): print ("voor de verzameling {...
17,324
40f0d074aebf57b1e0870c34c7a7ff4d1fe74e3d
#Arquivo destinado aos menus de perguntas. Sao dois menus import curses import actions import getData import menu import pyrebase import textPrint import scoreboard import play import screen import perguntasActions # funcao destinada ao menu Perguntas onde # as opcoes sao Adicionao Pergunta, Editar Pergunta e Retorn...
17,325
758c9383cbde5dfa15ee1fd766630a8ec01861b2
#!/usr/bin/env python from datetime import datetime import csv import json month_mapping = { 'ene': 'Jan', 'feb': 'Feb', 'mar': 'Mar', 'abr': 'Apr', 'may': 'May', 'jun': 'Jun', 'jul': 'Jul', 'ago': 'Aug', 'sep': 'Sep', 'oct': 'Oct', 'nov': 'Nov', 'dic': 'Dec', } def ...
17,326
220d8b857825724bb7add6ef1163185d3fc0ba14
""" Student.py 20210917 ProjectFullStack """ class Student: # class variable to track the number of students # that exist student_count = 0 def __init__(self, name, age, student_id, courses): """Constructor for the Student class""" self.name = name self.age = age self...
17,327
bd70623dc78f27f6afdad405ee67db4a35a0d70e
''' Class Fraction input: 2 fractions output: add and substraction capabilities using the function ''' class fraction(object): def __init__(self, num,deno): self.num = num self.deno = deno def __str__ (self): return str(self.num) + '/' + str(self.deno) def getnum (self): ...
17,328
66a019ee6a5a25ab74ea8e36408a97b399ca168d
import logging import pandas as pd from lib.constant import Datasets from lib.data.accidents.scrappers import get_urls_by_dataset from lib import utils urls_map = get_urls_by_dataset() dtypes_file_path = 'resources/dtypes/raw.yml' read_csv_kwargs_by_year = { 'default': { 'sep': ',', 'header': 0,...
17,329
5ae6d412a388802c9b4811d8d4a209ce5925b80d
def count_letters_digits(sentence): letter_count=0 digit_count=0 for letter in sentence: if letter.isdigit(): digit_count+=1 if letter.isalpha(): letter_count+=1 result=[letter_count,digit_count] return result sentence='hi bro how are 9999' print(count_letters_digits(sentence))
17,330
d9f8e87afafade484f0fc6ba237f7a35e0722cb6
#Antecessor e Sucessor de um número num = float(input("Digite um número: ")) ant = num - 1 suc = num + 1 print("Antecessor: {} \nSucessor: {}" .format(ant,suc))
17,331
e17b1111f2f7a66d18f78220f9782691f6598845
"""Program that outputs one of at least four random, good fortunes.""" __author__ = "730395347" # The randint function is imported from the random library so that # you are able to generate integers at random. # # Documentation: https://docs.python.org/3/library/random.html#random.randint # # For example, consider t...
17,332
b8bdc84a8d316c54d07ef3e9ecc44383a29d3650
class Database(): def __init__(self, database_name): # name needs to have '.txt' at the end self.database_name = database_name # appends a new data to the database def write(self, data): file = open(self.database_name, 'a') file.write(str(data) + '\n') print('Suc...
17,333
e7193fb0656cf8a07def59c7db3ae8498aebfdc4
from flask import ( Blueprint, request, current_app, jsonify) from werkzeug.exceptions import BadRequest from network_simulator.controller.return_value import ReturnValues libvirt_network_api_bp = Blueprint("libvirt_network_api", __name__) @libvirt_network_api_bp.route("/create", methods=["POST"]) def add_and_c...
17,334
b393ddfe720e84efb22a2a741b1e1880e50c192f
import codecademylib3_seaborn import matplotlib.pyplot as plt from sklearn import datasets from sklearn.cluster import KMeans # From sklearn.cluster, import KMeans class iris = datasets.load_iris() samples = iris.data # Use KMeans() to create a model that finds 3 clusters model = KMeans(n_clusters = 3) # Use .fit() ...
17,335
160eaae3449edcb7eaa3a5953c1064cd4ae07ae4
import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': """TI = 0.11""" # #FAST # FAST4 = np.array([1.35137908, 1.71541373, 1.98567876, 1.3984026 , 0.94911793, # 0.67718382, 0.64275145, 0.77966465, 1.02635052]) # FAST7 = n...
17,336
b0834b238d35de8e24453cb4e131b2f6509d17cd
f = open(r"e:\downloads\a-small-attempt0.in", "r") #f = open(r"e:\downloads\the_repeater.txt", "r") def char_count(s): res = [] i = 0 while i < len(s): c = s[i] j = i+1 while j < len(s) and s[j] == c: j += 1 res.append((c, j-i)) i = j ...
17,337
0670325b9836545025df08d3c92caa672b4b1497
from data import Data class DraftSim: def __init__(self, teams: int = 12, years_data: int = 2020): self.df = Data.get_pfr_fantasy_totals_df(years_data) self.number_of_teams = teams def run_sim(): pass
17,338
37d6381dccfa0b90dfd9d32dd3bb57f20f595ba6
import csv import os import fcntl import config #This module will hold the statuses of the LED's on the BPS. #path name to file file = config.directory_path + config.files['Lights'] #returns integer where 9 LSB are status of 9 LED's def read(): lights = [] os.makedirs(os.path.dirname(file), exist_ok=True) ...
17,339
7da8ea6e852216e09ef2b9357afae9da8448fd0d
# Writes __init__.py file for animals/harmless folder from .birds import Birds
17,340
53550298484249e123c3116cc4a74935bac2c38c
from rest_framework import serializers from inventario.models import Pc class PcSerializer(serializers.ModelSerializer): class Meta: model=Pc fields=('id_pc','procesador_pc','velocidad_pc','memoria_ram','almacenamiento','tarjeta_video','marca','tipo_equipo','numero_serie','modelo','codigo_activo','...
17,341
50e7c75cca7a96dec89ee96f3cc1eaca78bc9d9f
""" __ConditionSet1orMoreConditionBranchPart1_Complete_MDL.py_____________________________________________________ Automatically generated AToM3 Model File (Do not modify directly) Author: gehan Modified: Mon Mar 2 14:25:28 2015 _________________________________________________________________________________________...
17,342
b9dffba29e049d84ee9b2324985c626ebe2140ea
from etkinlik import * for i in range(2): for j in range(4): #kare çizimi ciz(50) #50 birim kenar çiz solaDon() #sol yöne dön #bir sonraki katın çizilmeye başlanacağı #noktaya git solaDon()#kuzey yönüne dön git(50) #Karenin sol üst köşesine git sagaDon()#Üçgen çi...
17,343
683339d596782f411e8b2b963d5a0c3802264ff7
from typing import Tuple, Sequence def check_index_is_valid(shape: Tuple[int, ...], index: Tuple[int, ...]) -> None: if len(shape) != len(index): raise ValueError("Length of desired index {} must match the length of the shape {}.".format(index, shape)) for i in range(len(index)): if index[i] >...
17,344
cbd12fed3d2a24e9620d8de2183f4331cbd3cd51
import sqlite3 class Conecta(object): def __init__(self): self.conect() def conect(self): self.con = sqlite3.connect('db.db', timeout=1) def fechaConexao(self): self.con.close() def defineCursor(self): self.cursor = self.con.cursor() def insereDadosUsuarios(self,...
17,345
08ead39776286102ca6488536e7c1afd9d43689b
from startiot import Startiot from L76GNSS import L76GNSS from pytrack import Pytrack import pycom import time from machine import Pin from lib.onewire import DS18X20 from lib.onewire import OneWire from lib.deepsleep import DeepSleep pycom.heartbeat(False) # disable the blue blinking iot = Startiot() pycom.rgbled(0x...
17,346
4f2a5481f03fb59e27c33c414c117b0e6343d2d0
import requests import json import base64 import os apikey = "4fc3a688d6aaf8c4368bad7acf78c9e7" if (True): input = "upload" outputformat = "pdf" headers = {'Content-Type': 'application/json'} urlbegin = "https://api.convertio.co/convert" data_begin = { "apikey": apikey, "input": "up...
17,347
9b460e24a802b1ba775509a8e98a58d825f0cbf6
m,n = input().strip().split() h = input().strip().split() a = set(input().strip().split()) b = set(input().strip().split()) totalHappiness = 0 for i in h: if i in a: totalHappiness+=1 elif i in b: totalHappiness-=1 else: pass print(totalHappiness)
17,348
a03c9df4b937f3849dc5a52611285f8464447373
# Lawrence McAfee # ~~~~~~~~ import ~~~~~~~~ from modules.node.HierNode import HierNode from modules.node.LeafNode import LeafNode from modules.node.Stage import Stage from modules.node.block.CodeBlock import CodeBlock as cbk from modules.node.block.HierBlock import HierBlock as hbk from modules.node.block.ImageBlock ...
17,349
cfc821f584e2cdad1333d3b352915c368662aee9
n = int(input()) s = input() def solve(n, s): count = 0 for c in s: if c == 'A': count += 1 if count > n - count: print("Anton") elif count < n - count: print("Danik") else: print("Friendship") solve(n, s)
17,350
782d113145c05643b6068a5cbd510865d322662b
"""Abstract away the terminal control sequences""" from sys import stdin import termios TERMATTRS = None def save(): """Save the terminal state so that we can restore it at the end (called in game setup)""" global TERMATTRS TERMATTRS = termios.tcgetattr(stdin) def restore(): """Bring the terminal ba...
17,351
b96c25322568cc35b2981ac1a77713d9e5b79173
# Generated by Django 2.1.7 on 2019-03-01 09:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('posts', '0004_remove_comment_comment'), ] operations = [ migrations.AddField( model_name='comment', name='comment', ...
17,352
bf8db8c7acf6e9b6a6c75ab93d5dd13d4f0a5b2a
# coding=utf-8 import requests import re, sys, os import json import threading import pprint import sys reload(sys) sys.setdefaultencoding('utf-8') class spider: def __init__(self, sid, name): self.id = sid self.headers = {"Accept": "text/html,application/xhtml+xml,application/xml;", ...
17,353
62326ff417cb9d48ce8caa83e3f42f46bdbbfd4e
def get_derivative_at_point(function, x, h = 1e-7): return (function(x + h) - function(x)) / h def square(x): return x ** 2 def get_left_derivative_at_point(f, x, h = 1e-7): return (f(x) - f(x - h)) / h print(get_derivative_at_point(square, 4)) print(get_left_derivative_at_point(square, 4)) print(get_de...
17,354
4476734ddfa4b0a15e00e9985ed7fde36c2ee98b
#!/usr/bin/python2.7 import os import shutil def config_bashrc(): try: shutil.copy2(os.path.expanduser("~/.bashrc"), os.path.expanduser("~/.bashrc.bak")) f = open(os.path.expanduser("~/.bashrc"), "r+a") lines = f.readlines() command = 'PROMPT_COMMAND="history -a;$PROMPT_C...
17,355
197efbeb290e4e8eabf8316dc355151d80a6b6b9
class Cajero: efectivo = 0 billetes = None def __init__(self, efectivo, billetes): self.efectivo = efectivo self.billetes = billetes def dardinero(self, pedido, cliente): if pedido > self.efectivo: print("No se dispone de efectivo suficiente. El efectivo disponible ...
17,356
7f816521995f0ad353c360067aabc0f7ee5410ce
#encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8') import numpy as np from DBUtils import * from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cross_validation import train_test_split from sklearn.naive_bayes import BernoulliNB from sklearn.naive_bayes import MultinomialNB fro...
17,357
437ba5c847ab09303848b0030bd6c36e1c3220fe
#!/usr/bin/env python # coding: utf-8 # ___ # # <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> # ___ # # NumPy # # NumPy (or Numpy) is a Linear Algebra Library for Python, the reason it is so important for Data Science with Python is that almost all of the libraries in the PyData ...
17,358
293fd73802efb587fad1601ca0beffd992933124
# Copyright 2015 Confluent Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
17,359
a23bdfd3e1d2168bfa58590fd3851fcdfb0fe479
# Generated by Django 3.0.4 on 2020-05-10 20:42 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='WordEng', fields=[ ('id', models.AutoField(...
17,360
9f7b602d943d10a3e39eb9e2d36a6990f3a7ce72
names=['bob','alice','tom','jerry'] print(names[0]) print(names[1].title()) print(names[2].upper()) print(names[-1]) message=names[0]+",nice to meet u!" print(message) brands=("stusst","supreme","palace") print("I would like to own a "+brands[1].title()+" pailide\n") name_list=['dingding','lala','dixi','po'] invited=[...
17,361
384afaafe357119fd0bea9b4e57349f67ea6965b
from SQL import querys as qy import sqlite3 # initialise the two tables for database def initTabel(connection): cursor = connection.cursor() __execute_command(cursor,qy.get_create_table_query()) __execute_command(cursor,qy.get_create_tx_table_query()) __execute_command(cursor,qy.get_create_filtered_OP...
17,362
cd28d526c6772ce02d9eb985e13a918fec3973e5
# -*- coding:utf-8 -*- from scrapy.spider import Spider, Request from bs4 import BeautifulSoup class MySpider(Spider): name = "csdn" allowed_domains = ["blog.csdn.net"] start_urls = [ "http://blog.csdn.net/temanm" ] # 获取blog页数 和相应的链接 def parse(self, response): based_url = "http...
17,363
57e9c51eeef9bc0a16f2d5c44d2a4527b6abe7ef
# -*- coding: utf-8 -*- """ Created on Fri Mar 15 18:30:50 2019 @author: Akhil """ import random class StudentQueue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item, AT, BT): self.lst = [] self.lst.append(item) s...
17,364
96ceb4ac7335111bf3873b52b036421fc425f913
import sqlite3 as lite SCHEMA = { 'settings': [ "key PRIMARY KEY", "value_1", "value_2" ], 'torrents': [ 'id PRIMARY KEY', 'artist', 'album', 'release', 'quality', 'added DATETIME', 'downloaded BOOLEAN' ], 'user': [ 'username P...
17,365
88fb868b7adae0654b4941660e8e3e9f9162a2fb
#!/usr/bin/python # Sample download of large blob file from Google Cloud Storage # using (chunked) resumable downloads # https://googlecloudplatform.github.io/google-resumable-media-python/latest/google.resumable_media.requests.html#chunked-downloads import io import urllib3 import google.auth.transport.requests as t...
17,366
1af32d90f37a51337209e146de2a18d53c25a3f7
import json def get_stored_username(): filename = 'username.json' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: return None else: return username def get_new_username(): username = input('What\'s your name: ') filename = 'u...
17,367
925388fb236a065e16a1f54dee2c1007feccc8f5
from __future__ import division import numpy as np import soundfile as sf from scipy.signal import spectrogram import scipy.stats from sklearn import linear_model from . import timbral_util def warm_region_cal(audio_samples, fs): """ Function for calculating various warmth parameters. :param audio_samp...
17,368
086be2ec13dcd7af28fb06290ca287c375a9fa6f
#!/usr/bin/env python # encoding: utf-8 import os import time import argparse import sys sys.path.append('..') sys.path.append('.') import tensorflow as tf from sklearn.utils import shuffle from keras.callbacks import TensorBoard from keras.models import Model, load_model from keras.utils.vis_utils import plot_model...
17,369
8912ae21856ce4c73cce10739595938b9dc4947d
#!/usr/bin/env python # SUMMARY: hey' # COMPLETE # START HELP # this is an example of a simple script written in python. # END HELP import sys # when attempting to complete a variable, # --complete will be passed, with the full argument set. # for example, # $ cb file_example foo a --complete # will pass all arguments...
17,370
1f4d8294919fedd85500291554319f9b2c14b021
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 30 14:12:14 2019 @author: jaimiecapps """ import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler import tensorflow as tf import matplotlib.pyplot as plt df = pd.re...
17,371
435e1a3ef0cdd91a0933d63347497647f623074b
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-07-09 00:34 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tasabido', '0016_auto_20160708_1158'), ] operations = [ migrations.RenameField( ...
17,372
6f0d4f340cf33738886ed807a66d47feed5e96a2
import string import math import readline locationCode = {'A':10,'B':11,'C':12,'D':13,'E':14,'F':15,'G':16,'H':17,'I':34,\ 'J':18,'K':19,'L':20,'M':21,'N':22,'O':35,'P':23,'Q':24,'R':25,\ 'S':26,'T':27,'U':28,'V':29,'W':32,'X':30,'Y':31,'Z':33}; def check(id): if(len(id) != 10 or not(id[0].isalpha()) or not(id[1...
17,373
3287e33e29f7abb8fcb038554c9fe6c39c54c879
def expand_volume(self): is_thin = self.volume_detail['thinProvisioned'] if is_thin: self.debug('expanding thin volume') thin_volume_expand_req = dict(newVirtualSize=self.size, sizeUnit=self.size_unit) try: (rc, resp) = request((self.api_url + ('/storage-systems/%s/thin-volum...
17,374
5dc5c2e1fb5274960874ef90a484d5c32e8bddea
# DAY 001 # PART 001 input_array = [] with open('Data/input001.txt', 'r') as raw_data: for line in raw_data: input_array.append(int(line)) freq = 0 for adjust in input_array: freq += adjust print('1-loop freq: %i' % freq) # PART 002 freq = 0 freqs = [] dup_found = False while not dup_found: for...
17,375
24872930c925604876d516b8e10560aa04fa553a
file = open("input1","r") i = int(input('Digit the number of the line that you want to change: '))-1 text = input('Write the text you want to append: ') list_of_lines = [] for line in file: counter = 1 element = str(counter)+'. '+ line.strip('\n') counter+=1 list_of_lines.append(element) list_of_lines[...
17,376
8c8044af8676dccb1596ba1ead010fa5407e8a94
""" Logic for dashboard related routes """ from flask import Blueprint, render_template from .forms import LogUserForm, secti,masoform from ..data.database import db from ..data.models import LogUser, Stats from datetime import datetime, timedelta import urllib2 import json import os blueprint = Blueprint('public', __...
17,377
645315bc923aa5c22c7f89d9abbbf3b5fe13c29d
# -*- coding: utf-8 -*- """ """ from __future__ import division, print_function, absolute_import import numpy as np from numpy import pi try: _ = np.use_fastnumpy from numpy.fft import fft, ifft, rfft, irfft except AttributeError: from scipy.fftpack import fft, ifft from numpy.fft import rfft, irfft f...
17,378
0d8fb5c2707f94821641c1d58682beea5ae54341
from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from .models import * from .serializers import * from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status @api_vie...
17,379
29aa554943dd05bcce36dc3b837970a933226667
# https://www.hackerrank.com/challenges/correlation-and-regression-lines-6/problem import fileinput def compute_correlation_coefficient(xs, ys): n = float(len(xs)) sum_X = sum(xs) sum_Y = sum(ys) sum_XX = sum(list(map((lambda x: x ** 2), xs))) sum_YY = sum(list(map((lambda y: y ** 2), ys))) su...
17,380
e8d74c4e5f4460c2e78d7e0d050efd7db3c39c34
import cv2 import numpy as np from src.config import get_algorithm_params import dlib NO_FACE_IN_FRAME = "NO_FACE_IN_FRAME" FACE_DETECTED = "FACE_DETECTED" FACE_TRACKER = "FACE_TRACKER" class FaceTracker: def __init__(self): self.params = get_algorithm_params(FACE_TRACKER.lower()) # load dlib de...
17,381
bec3cb9699efcda931317facac82485fa90d2234
def expand(self, obj, items): block = [item.raw for item in obj.parents] block.append(obj.raw) current_level = items for b in block: if (b not in current_level): current_level[b] = collections.OrderedDict() current_level = current_level[b] for c in obj.children: i...
17,382
a3cc31c80a54748d0c03dfdce7b6fe0435e8c3e2
## import pandas as pd from datetime import timedelta import re df = pd.read_csv('Downloads/data_file (1).csv') tstamp_df = pd.DataFrame(columns=['TIME STAMP']) timestamps=[] dic={'JAN':'01', 'FEB':'02', 'MAR':'03', 'APR':'04','MAY':'05','JUN':'06', 'JUL':'07','AUG':'08','SEP':'09','OCT':'10','NOV':'11','DEC':'12...
17,383
03ba7cd194b99a794938fb5c1501c96e7695bccc
import numpy as np from scipy.ndimage import median_filter class AdvancedFilter: def mean_blur(self, arr): new = [] window_size = 10 for d in range(3): im_conv_d = median_filter(arr[:, :, d], size=(window_size, window_size)) new.append(im_conv_d) im_conv = n...
17,384
f3093c65a53cf77dfbebd0fd34bc9235ec018662
#!/usr/bin/env python # -*- coding: utf-8 -*- from starlette.status import HTTP_403_FORBIDDEN, HTTP_401_UNAUTHORIZED from epicteller.core.error.base import EpictellerError class IncorrectEMailPasswordError(EpictellerError): message = '邮箱或密码不正确' class UnauthorizedError(EpictellerError): status_code = HTTP_4...
17,385
bab2b2260beed6996a5c9171c5378f7514d6e051
#!/usr/bin/python2 # -*- coding: utf-8 -*- import re,sys,commands, getopt, subprocess from subprocess import Popen, PIPE # comment line start with detec_co ="#" # pfad / name from host for display comments _PFAD_host = "/common/usr/dhcp/hosts.conf" # status check_snmp _unknow = -1 _ok = 0 _warning = 1 _crit...
17,386
c8b8dfcacb391da815b941d406ff7c34c3ea6183
# # @lc app=leetcode id=566 lang=python3 # # [566] Reshape the Matrix # # @lc code=start from typing import List class Solution: def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]: m, n = len(mat), len(mat[0]) res = [[0] * c for _ in range(r)] if m == r and n =...
17,387
72246040950324182a943ea88ab9a63c6d563872
# -*- coding: utf-8 -*- """ The darshan.common module provides common functionality required by mulitple modules. """
17,388
580acc794a6fdd9f4a452151ec503606cbb03929
# coding=utf-8 # start_vpn.py # save current connected server connected_server = 'tmp_server.log' # save connected server history server_history = 'server_histroy.log' # save openvpn config file openvpn_config_file = 'tmp_openvpn_config.ovpn' # get_ip.py # http/https proxy server url proxy_url = {'http': '127.0.0.1:...
17,389
ea5d7f976206e3a487ebfea588efb9961be915f6
class Solution: def canFinish(self, numCourses: int, prerequisites: [[int]]) -> bool: adj_list = defaultdict(list) vertices_with_no_incoming_edges = [] stack = deque() indegree_graph = defaultdict(int) for i in range(numCourses): indegree_graph[i] = 0 ...
17,390
107d33bced5de679ed44f77f662dcbd1595f3edb
# 11.6 (Algebra: multiply two matrices) Write a function to multiply two matrices. The # header of the function is: # def multiplyMatrix(a, b) # To multiply matrix a by matrix b, the number of columns in a must be the same as # the number of rows in b, and the two matrices must have elements of the same or # compatible...
17,391
73e8cdb89460becdf389b5ea83812f92ff340def
# full_name = lambda first, last: f'I am {first} {last}' # # result = full_name('Guido', 'van Rossum') # # print(result) x = lambda a, b: a * b print(x(3, 4))
17,392
70f053c976389a131db70720b7981e4b94e01aa6
from .generate_service import InfrastructureGMLGraph, ServiceGMLGraph class VolatileResourcesMapping(dict): # key to store a bool for indicating whether it is a successful mapping (taken from the AbstractMapper's earlier realizations) WORKED = 'worked' # key to store a dict of AP names, for each time ins...
17,393
254701d5a080eb8cb40ace40f6478a4efd5a2a51
from transformers import BertModel, BertTokenizer from functools import wraps import numpy as np from utils.base_classes import BaseEmbedder from utils.indexer_utils import get_text_by_ind, get_new_ind_by_ind, prepare_indexer, test_queries from text_utils.utils import create_logger from config import logger_path, Model...
17,394
06d803ccbe313e65584759e0f91decd7fc458f35
from plone import api def setoAuthTokenFromCASSAMLProperties(event): """ This subscriber is responsible for the update of the oauth_token from the CAS authentication. """ user = api.user.get(event.properties['username']) user.setMemberProperties(mapping=dict(oauth_token=event.properties['oauth...
17,395
fc9865c0b25b494f3ad25eecc1a9704a8089d56f
# called by demo_global_writer from tensorboardX import GlobalSummaryWriter writer = GlobalSummaryWriter.getSummaryWriter() writer.add_text('my_log', 'greeting from global1') for i in range(100): writer.add_scalar('global1', i) for i in range(100): writer.add_scalar('common', i)
17,396
c75df5c5cf6f39fdd7a78b1eb02878b93a02f2e9
import os import argparse import sys import pickle from pathlib import Path from jax import random from sklearn.decomposition import PCA from generate_data import gen_source_data from models import init_invertible_mlp_params, invertible_mlp_fwd from train import train def parse(): """Argument parser for all co...
17,397
0de8988a8329ad56340b81d93794a79363e18815
# -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with th...
17,398
99676e2960761432327a9ab01a9259ae19766355
import multiprocessing as mp import sys def add_print(num): total.value += 1 print total.value #print "\r" + str(total.value) # sys.stdout.write("Num: " + str(total.value) + "\r") # sys.stdout.flush() def setup(t): global total total = t if __name__ == "__main__": total = mp.Value('i'...
17,399
60fcbdbd6546af4eb739d15217ef6fb1f8edec9c
import json from cloudant.client import CouchDB USERNAME = 'admin' PASSWORD = 'password' DATABASE = 'dbname' client = CouchDB(USERNAME, PASSWORD, url='http://127.0.0.1:5984', connect=True) # Open an existing database db = client[DATABASE] # Define the end point and parameters endpoint = DATABASE + '/_find' params =...