index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
5,900
33b6a4c76079ed698809b29772abb59a34831472
from django.db import models from django.utils import timezone from django.contrib.auth.models import User, Group # Create your models here. def default_expiration(): return timezone.now() + timezone.timedelta(days=10) class Category(models.Model): name = models.CharField(max_length=200) description = ...
5,901
3fdb29797894737edae37ad7890e14cb9ce705e8
import pygame naytto = pygame.display.set_mode((740, 500)) pygame.display.set_caption("Piirtäminen") x = 100 y = 300 def main(): while True: tapahtuma = pygame.event.poll() if tapahtuma.type == pygame.QUIT: break naytto.fill((0, 0, 0)) pygame.draw.line(naytto, (0, 0, ...
5,902
42021b762737a2eb21866ba029ece4ac120152cd
class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] naive -- o(n^2) """ ## StefanPochmann solution #2 def countSmaller(self, nums): def sort(enum): half = len(enum) / 2 if half: left = sort(enum...
5,903
ff924b803a875d3f6201baa2c1251a6c5b8cde61
from django.http import request from restapp.ExcelSheet import * '''ApiHomeDict={} class LoadDict(): e = ExcelSheetAll() ApiHomeDict = e.apiHomeDict() print ApiHomeDict class ReturnApi: def returnDict(self): return ApiHomeDict''' '''if "ApiDictionary" in request.session: print...
5,904
9247896850e5282265cd08240f6f505e675ce5f0
n = int(input()) num = list(map(int, input().split())) plus_cnt = 0 div_max = 0 for i in num: div = 0 while i > 0: if i % 2 == 0: i //= 2 div += 1 else: i -= 1 plus_cnt += 1 div_max = max(div_max, div) print(plus_cnt + div_max)
5,905
aff439361716c35e5f492680a55e7470b4ee0c42
from numpy import empty import pickle from dataset import Dataset from image import Image f = open("./digitdata/trainingimages", "r") reader = f.readlines() labels = open("./digitdata/traininglabels", "r") lreader = labels.readlines() trainImageList = [] j = 0 i = 0 while(j < len(reader)): image_array = empty([...
5,906
b4b80e40d12486881e37dd7ddeeef9c76417ebd9
def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" %(a, b) return a - b def multipy(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % (a, b) return a / b print "Let's do some...
5,907
7f9046582ff03d1c72d191a8f78c911cbc8a0650
#!/usr/bin/env python """ Power calculation based for admixture mapping. @ref: Design and Analysis of admixture mapping studies, (2004). @Author: wavefancy@gmail.com Usage: PowerCalculation.py -r aratio -n nhap PowerCalculation.py -h | --help | -v | --version | -f | --format Not...
5,908
a6c45ab3df0a692cd625d8203e1152e942a4cd6c
# DISCLAIMER # The "Math" code was taken from http://depado.markdownblog.com/2015-09-29-mistune-parser-syntax-highlighter-mathjax-support-and-centered-images # The HighlightRenderer code was taken from https://github.com/rupeshk/MarkdownHighlighter # MarkdownHighlighter is a simple syntax highlighter for Markdown syn...
5,909
603a73a7cc0487fcabb527ebc21d44cb95817ecb
def checkRaiz(): a = int(input("Informe o primeiro coeficiente: ")) b = int(input("Informe o segundo coeficiente: ")) c = int(input("Informe o terceiro coeficiente: ")) delta = (b*b) - (4*a*c) if (delta < 0): print("Não tem raiz real") elif (delta == 0): print("Existe uma raiz...
5,910
0dc556336cee9e5f41c036c6fcf6da950216693c
from twindb_backup.copy.binlog_copy import BinlogCopy from twindb_backup.status.binlog_status import BinlogStatus def test_get_latest_backup(raw_binlog_status): instance = BinlogStatus(raw_binlog_status) assert instance.get_latest_backup() == BinlogCopy( host='master1', name='mysqlbin005.bin',...
5,911
9dd5db441044c808274493f16a912d1b65a6c28b
print("Leer 10 números enteros, almacenarlos en un vector y determinar en qué posiciones se encuentran los números con mas de 3 dígitos") count=1 lista=[] while count<11: numero=int(input('Introduzca su %d numero:' %(count))) lista.append(numero) count=count+1 listanueva=[] s= ',' f...
5,912
1cba7889370cc7de47bb5cd1eaeadfece056e68a
#Problem available at: https://www.hackerrank.com/challenges/weather-observation-station-6/problem SELECT DISTINCT CITY from STATION where substr(CITY,1,1) in ('a','e','i','o','u');
5,913
731110b02c8a09dc84042a99c14eef990ae33cd2
""" Have the function CharlietheDog(strArr) read the array of strings stored in strArr which will be a 4x4 matrix of the characters 'C', 'H', 'F', 'O', where C represents Charlie the dog, H represents its home, F represents dog food, and O represents and empty space in the grid. Your goal is to figure out the least...
5,914
9feb24da78113310509664fa9efcf5f399be5335
# Import smtplib for the actual sending function import smtplib # Import the email modules we'll need from email.message import EmailMessage # Open the plain text file whose name is in textfile for reading. with open("testfile.txt") as fp: # Create a text/plain message msg = EmailMessage() msg.set_content...
5,915
dcb57ecf2c72b8ac816bb06986d80544ff97c669
from http import HTTPStatus from ninja import Router mock_post_router = Router() @mock_post_router.get( "/mock_posts", url_name="mock_post_list", summary="전체 mock post의 list를 반환한다", response={200: None}, ) def retrieve_all_mock_posts(request): return HTTPStatus.OK
5,916
d30e5e24dd06a4846fdde3c9fcac0a5dac55ad0d
import sys import os from django.conf import settings BASE_DIR=os.path.dirname(__file__) settings.configure( DEBUG=True, SECRET_KEY='ki==706e99f0ps9w5s*!kx%1^=5jq_k1c&4r@#e&ng9=xlm5_', ROOT_URLCONF='sitebuilder.urls', MIDDLEWARE_CLASSES=(), INSTALLED_APPS=( 'django.contrib.staticfiles', 'django.contrib.webd...
5,917
b318f5d443dbf8e4442707839649149e75653295
#!/usr/bin/python import socket import sys host = '10.211.55.5' port = 69 try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except: print "socket() failed" sys.exit(1) filename = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7...
5,918
7cc9d445d712d485eaebd090d2485dac0c38b3fb
# file /home/hep/ss4314/cmtuser/Gauss_v45r10p1/Gen/DecFiles/options/16303437.py generated: Wed, 25 Jan 2017 15:25:22 # # Event Type: 16303437 # # ASCII decay Descriptor: [Xi_b- -> (rho- -> pi- pi0) K- p+]cc # from Configurables import Generation Generation().EventType = 16303437 Generation().SampleGenerationTool = "Si...
5,919
8e26a6b50539fa5f498aa2079a2625214e5b4d03
# 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 u...
5,920
ffb6379f2f2611fd8aa73f3a3c15fed4550d348f
############################################################################## # # Copyright (c) 2005 Nexedi SARL and Contributors. All Rights Reserved. # Yoshinori Okuji <yo@nexedi.com> # Christophe Dumez <christophe@nexedi.com> # # WARNING: This program as such is intended to be ...
5,921
08e5e8515528eae400a59bfc0c58b8d7b4affd7e
# coding: utf-8 ## ROC for CLEF-IP2010 patents ####### ROC for clef-ip2010 patents # In[ ]: def vectorize_corpus(corpus,tokenizer,vocabulary,max_ngram_size): # tokenize text from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from...
5,922
fcc12b26308e3031de7e8fcf4ad43ec92279d400
__author__ = 'jamjiang' class Person: def __init__(self, name): self.name = name def sayHi(self): print 'hi!, I am', self.name david = Person('David') david.sayHi() Person('leo').sayHi()
5,923
1298c2abae519a5365cc0d9d406196db987eb219
from collections import defaultdict def k_most_frequent(arr:list, k:int): ''' ''' counts = defaultdict(int) for n in nums: counts[n] += 1 counts = [(k,v) for k,v in counts.items()] ordered = list(reversed(sorted(counts, key=lambda d: d[1]))) return [o[0] for o in ordered[:k]] num...
5,924
0eaba8f570772de864f52168a597b47a4150d015
# -*- coding:utf-8 -*- from common import * import itertools def iteration_spider(): max_errors = 5 num_errors = 0 for page in itertools.count(1): url = 'http://example.webscraping.com/view/-{}'.format(page) html = download(url) if html is None: num_errors += 1 if num_errors == max_errors: break ...
5,925
649c0c0f170b50fe51f5eaf11908e968f66625c9
import os import shutil def flatCopyWithExt(srcDir, dstDir, ext): if not os.path.exists(dstDir): os.makedirs(dstDir) for basename in os.listdir(srcDir): if basename.endswith(ext): pathname = os.path.join(srcDir, basename) if os.path.isfile(pathname): shutil.copy2(pathname, dstDir) def move...
5,926
9d0727970c760a9a8123c5c07359ba5c538cea3c
# CS 5010 Project # Team Metro # Test the data cleaning import unittest from cleaning_data import dfClean # import the dataframe we created after cleaning the data class DataTypesTestCase(unittest.TestCase): # we will test that each column has the correct data type # note that there is a strange occurenc...
5,927
7636925982434b12307383ba7b01f931f7ea6e24
from mininet.cli import CLI from mininet.term import makeTerms from mininet.util import irange from log import log from utils import (UITextStyle, display) from dijkstra import (get_routing_decision, get_route_cost) # Check if route directly connects two switches def isDirect(route): return (len(route) == 2) # ...
5,928
cfea7848dfb41c913e5d8fec2f0f4f8afaaa09f3
import sys reload(sys) sys.setdefaultencoding('utf-8') import xml.etree.ElementTree as ET tree = ET.parse('iliad1.xml') root = tree.getroot() file = open('iliad1_clean.txt','w') for l in root.iter('l'): file.write(''.join(l.itertext()) + "\n") file.close()
5,929
08c3155a5fbf6c94f5885c12cfc7c917313ae9c7
from abc import ABCMeta, abstractmethod, ABC from domain.models.network_information import NetworkInformation class AbstractTensorboardExportService(ABC): __metaclass__ = ABCMeta @abstractmethod def save_tensorboard(self, network_info: NetworkInformation) -> None: raise NotImplementedError
5,930
2678aac08104a580e866984bc4cf4adf8cb8ac5c
from __future__ import division, print_function, unicode_literals import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from pyglet.gl import * from pyglet.window import key from cocos.actions import * from cocos.director import director from cocos.layer import Layer from cocos.scene...
5,931
f19056222be713c1556817d852af14d04483c9a3
i = 0 num = '' while len(num) < 1e6: i += 1 num += str(i) prod = 1 for i in xrange(0, 7): prod *= int(num[10 ** i - 1]) print prod
5,932
b3c22b4a453aa55da980b090df2749ff9f1066e6
#game that has a timer and you need to stop the timer #with 0 at the end. import simplegui #necessary global variables #time for the timer time = 0 #the display for the timer(string form) watch = '' #tries and correct presses tries = 0 correct = 0 #changes time to watch(number to string of form A:B...
5,933
f4519fa82ffc6bf945c7bb36d3761a708a06f641
import os from flask import Flask, jsonify, request, abort, make_response from flask_sqlalchemy import SQLAlchemy from .models import User from .config import app_config app = Flask(__name__) app.config.from_object(app_config[os.getenv('FLASK_ENV', 'production')]) db = SQLAlchemy(app) @app.route('/api/v1/users/<i...
5,934
f3aaa6ae7a9a57946bdb035a4d52e84541c1a292
import turtle from turtle import color import random screen = turtle.Screen() screen.setup(width=500, height=400) colours = ["red", "pink", "blue", "purple", "black", "green"] y_pos = [100, 60, 20, -20, -60, -100] user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will ...
5,935
cc81e13bba0ea0186966bce7f5aac05bb106e971
import sys import os def my_add(a, b): return a + b
5,936
d0991d8ea47379a0c1de836b5d215c99166ad049
import sys sys.path.append('../') import constants as cnst import os os.environ['PYTHONHASHSEED'] = '2' import tqdm from model.stg2_generator import StyledGenerator import numpy as np from my_utils.visualize_flame_overlay import OverLayViz from my_utils.flm_dynamic_fit_overlay import camera_ringnetpp from my_utils.gene...
5,937
337309da79ce9d90010fef5c171b6b344e6dc63f
"""Test Spotify module""" from spoetify.spotify import Spotify from nose.tools import assert_equal def test_search_track(): sp = Spotify() t = sp.search_track("avocado") assert_equal(t.id, "1UyzA43l3OIcJ6jd3hh3ac")
5,938
006e1088e72201fab7eebd1409c025b5dba69403
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str ...
5,939
7d1ca15129b1bf6b713e1d5eda4436d4a8539ad1
import numpy as np class nearest(svm): name="MLLKM2" def __init__(self): svm.__init__(self) def fit(self,x,y): self.x=x self.y=y def predict(self,x): diff=np.subtract(x,self.x) distance=np.linalg.norm(diff,axis=1) dmin= np.argmin( distance ) ...
5,940
4dac8e7e695c473cb73ceaf3887373bcc0a08aff
# from datetime import datetime from datetime import datetime, time, timedelta # today = datetime.now() # previous_day = today - timedelta(days=1) # previous_day = previous_day.strftime("%Y%m%d") # print(today) # print(previous_day) print(datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%Y-%m-%d 00:00:00')) # def...
5,941
2a500968cf6786440c0d4240430433db90d1fc2f
n = int(input()) p = [220000] + list(map(int, input().split())) cnt = 0 m = 220000 for i in range(1, n+1): now = p[i] m = min(m, now) if now == m: cnt += 1 print(cnt)
5,942
29c1a989365408bf5c3d6196f7afc969be63df85
def patternCount(dnaText, pattern): count = 0 for i in range(0, len(dnaText) - len(pattern)): word = dnaText[i:i+len(pattern)] if (word == pattern): count = count + 1 return count def freqWordProblem(text, k): countWords = [] for i in range(0, len(text) - k): pa...
5,943
88343b9c5cac3510e8cea75ac5b11f517ddc164b
from __future__ import absolute_import from __future__ import division from __future__ import print_function from keras.layers import Dense, Input from keras.layers import Conv2D, Flatten, Lambda from keras.layers import Reshape, Conv2DTranspose from keras.models import Model from keras.losses import mse, binary_cross...
5,944
87e17eb6fa91be09ac9afa43c4e58054faa77477
# Generated by Django 3.1.2 on 2020-10-29 06:04 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
5,945
90ae6fe37cea2c07d8308498c62460c10ca46846
# -*- coding: utf-8 -*- """ Created on Wed Oct 4 20:55:22 2017 @author: Ivan """ # ----------- # User Instructions # # Modify the test() function to include two new test cases: # 1) four of a kind (fk) vs. full house (fh) returns fk. # 2) full house (fh) vs. full house (fh) returns fh. # # Since the program is stil...
5,946
4318c99b3de9bb9c44eed57525c9ccbe82a17276
#!/usr/bin/python # # Script written by Legoktm, 2011 # Released into the Public Domain on November, 16, 2011 # This product comes with no warranty of any sort. # Enjoy! # from commands import getoutput def notify(string, program=False): if not program: command = 'growlnotify Python -m "%s"' %string else: command...
5,947
9e02b1a90d61de6d794dd350b50417a2f7260df6
from django import forms from django.contrib.auth.models import User from .models import TblPublish , TblSnippetTopics, TblSnippetData, TblLearnTopics, TblLearnData, TblBlog, TblBlogComments,TblLearnDataComments, TblBlogGvp, TblLearnDataGvp,TblSnippetDataGvp, TblHome, TblAbout, TblQueries from django.contrib.auth.forms...
5,948
fa880adcb9f009ffc206de59e8284ac6350fef4c
from django.db import models #from ingredients.models import * class Unit(models.Model): short_name = models.CharField(max_length=20) full_name = models.CharField(max_length=255, null=True) weight_in_grams = models.FloatField(default=1.0) def __str__(self): return f"{self.short_name}"
5,949
9527743802a0bb680ab3dcf325c0f7749a51afc6
i = 100 while i >= 100: print(i) i -= 1 print(i)
5,950
6111c9730c556ab3ab95f7685ffa135a2bbeb2ca
from __future__ import with_statement from fabric.api import * from fabric.colors import * from fabric.utils import puts from fabric.context_managers import shell_env env.hosts = ['git@tweetset.com'] def deploy(): "deploys the project to the server" with prefix('source /srv/django-envs/tweetset/bin/activate')...
5,951
2075e7e05882524c295c8542ca7aefae2cf3e0fc
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the storage format CLI arguments helper.""" import argparse import unittest from plaso.cli import tools from plaso.cli.helpers import storage_format from plaso.lib import errors from tests.cli import test_lib as cli_test_lib class StorageFormatArgumentsHe...
5,952
83bac8176caafc5551089c4bef5c1f38e1e8d4da
# block-comments.py ''' Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment). Paragraphs inside a block comment are separated by a line con...
5,953
679ca76212b90261683d59899c1189280b6b6e8c
#!/user/bin/env python3 -tt """ https://adventofcode.com/2017/day/7 """ import sys import re # Global variables task="d-7" infile=task + ".input" with open('input/' + infile) as file: input = file.read() file.close() class Node: parent = None children = None weight_sum = 0 def __init__(self, na...
5,954
7747cbb1a1ed191b616b0d1bcfd51cdea05067f5
from bs4 import BeautifulSoup import re class Rules: def __init__(self): self.ruleCollection = { "1" : self.rule1, "2" : self.rule2, "3" : self.rule3, "4" : self.rule4, "5" : self.rule5, "6" : self.rule6, "7" : self.rule7, "8" : self.r...
5,955
e26fa69ea1f0bee82b4108ac5a541a6175645728
import numpy as np import cPickle from features import create_features, PROJECT from parse import load_data from dict_vectorizer import DictVectorizer videos, users, reviews = load_data() orig_X = np.array([(x['date'], x['text'], x['user']) for x in reviews]) feats = create_features(orig_X, None) v = DictVectorizer(s...
5,956
459dd9302f7100ad02119cc94b735b19287f21e5
import tensorflow as tf import numpy as np import time import os from sklearn.metrics import roc_curve import matplotlib.pyplot as plt from src.model import get_args from src.funcs import linear from src.youtubeface import load_ytf_data from src.lfw import load_lfw_data from src.facescrub import load_fs_data from src...
5,957
3770e59c5bd6837a0fb812f80c6549024e06a9e4
''' Functional tests for the Write Stream ''' from behave import given, when, then from OSC import OSCClient, OSCMessage, OSCServer @given('I want to send an integer') def step_impl (context): pass @given('I want to send a float') def step_impl (context): pass @given('I want to send two integers with one ...
5,958
2343a9d3e253b5a0347b5890a5d7b9c3be777669
import tkinter import csv import datetime import time root = tkinter.Tk() root.title("Attendance") root.geometry("+450+250") ts = time.time() date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d') fileName = "Attendance/Attendance_"+date+".csv" # open file with open(fileName, newline="") as file: reader ...
5,959
ae998fb17b8d6f4f5c8871a0ebe86a039501ec99
# -*- coding: utf-8 -*- __all__ = "corner" import logging import numpy as np from corner.core import corner_impl try: from corner.arviz_corner import arviz_corner except ImportError: arviz_corner = None def corner( data, bins=20, *, # Original corner parameters range=None, axes_sc...
5,960
9586dc118be4388491770d823a38e8068e3b91cb
from django.contrib import admin from .models import Contactus,ContactusAdmin,Company,CompanyAdmin,Products,ProductsAdmin,Brands,BrandsAdmin # Register your models here. admin.site.register(Contactus,ContactusAdmin), admin.site.register(Company,CompanyAdmin), admin.site.register(Products,ProductsAdmin), admin.site.reg...
5,961
6623ac194e380c9554d72a1b20bf860b958dda97
from django.http import HttpResponse from django.shortcuts import render from .models import game def index(request): all_games = game.objects.all() context = { 'all_games' : all_games } return render(request,'game/index.html',context) def gameview(response): return HttpResponse("<h1>Ludo ...
5,962
ce263424b856c07e04bd66cda7ebda646583b1fe
S=input() T=int(input()) B=abs(S.count('L')-S.count('R'))+abs(S.count('U')-S.count('D')) print(B+S.count('?') if T==1 else max(B-S.count('?'),(B-S.count('?'))%2))
5,963
719f7b7b2d8df037583263588e93d884ab3820fe
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd gp = pd.read_csv('graph6.csv') N=gp['Starting-node'].max() M=gp['Ending-node'].max() N=max(N,M) gp=gp.sort_values(by='Cost') gp=gp.reset_index() gp=gp.reset_index() gp['tree label']=gp['level_0'] index=gp['index'].max() gp.drop('index',axis...
5,964
596f7dfacc931f5e756c71b8622f4001df19934b
from rest_framework import serializers from plan.models import RoughRequirement, DetailedRequirement from plan.models import OfferingCourse, FieldOfStudy, IndicatorFactor from plan.models import BasisTemplate class SimpleOfferingCourseSerializer(serializers.ModelSerializer): class Meta: model = OfferingCou...
5,965
cc1a1491ffbcf470705aeea079faac290dbaa25e
# this is the example code from the t0p-level README..d from spatialmath import SE3 import roboticstoolbox as rtb import swift robot = rtb.models.DH.Panda() print(robot) T = robot.fkine(robot.qz) print(T) # IK T = SE3(0.7, 0.2, 0.1) * SE3.OA([0, 1, 0], [0, 0, -1]) sol = robot.ikine_LMS(T) # solve IK, ignore additio...
5,966
7aa426723f5311b5abec4a7ace9d3ec1e5e31d9a
''' 这部分理解参考: https://www.bilibili.com/video/BV1QA411H7tK?from=search&seid=17305042509580602672 图文代码地址: https://blog.csdn.net/qq_30758629/article/details/112527763 ''' import threading import time data=0 lock=threading.Lock() #创建一个锁对象 def func(): global data print("%s is acquire lock..\n" %threading.curr...
5,967
8cf6a9243182a4f6b68199a8967e06790396dc10
#THIS IS PYTHON3 import tkinter as tk from tkinter import * from PIL import ImageTk from PIL import Image #to handle non-gif image formats import cv2 import numpy as np from statistics import mode import time import random import predict as ml def calcSuccess(predictedCounter, randAssault): vidLabel.pack_forge...
5,968
48e3259698788904e000eb15b5443067b0c3e791
#alds13c from collections import deque d_stack=deque() res_stack=deque() s = input() for i in range(len(s)): #print(d_stack,res_stack) if s[i]=="\\": d_stack.append(i) elif s[i]=="/": if len(d_stack)==0: continue left = d_stack.pop() area = i-left #res_s...
5,969
436cc06778bf9ac9e04a897f4a4db90c595d943c
# load the dependencies from airflow import DAG from datetime import date, timedelta, datetime # default_args are the default arguments applied to the DAG and all inherited tasks DAG_DEFAULT_ARGS = { 'owner': 'airflow', 'depends_on_past': False, 'retries': 1, 'retry_delay': timedelta(minutes=1) } with DAG('twitte...
5,970
cfa0937f1c49b52283c562d9ab1cb0542e71b990
import matplotlib.pyplot as plt from partisan_symmetry_noplot import partisan_symmetry for k in range(1,100): a=[] for i in range(1,100): a.append([]) for j in range(1,100): a[i-1].append(partisan_symmetry([5*i/100,.20,5*j/100],1000,False)) plt.imshow(a) plt.colorbar() p...
5,971
aa47b7c74b9b6b8a7f014de4bd58236edeba485d
import os class User(object): def __init__(self, meta): meta.update({ 'groups': meta.get('groups', []) + [meta['username']] }) self.meta = meta @property def username(self): return self.meta['username'] @property def groups(self): return self....
5,972
cdd929ee041c485d2a6c1149ea1b1ced92d7b7ab
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-08-03 02:31 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Creat...
5,973
41294c803cf42611fa003f21b74a49dd5576a8e8
# Copyright (c) 2020, Galois, Inc. # # All Rights Reserved # # This material is based upon work supported by the Defense Advanced Research # Projects Agency (DARPA) under Contract No. FA8750-20-C-0203. # # Any opinions, findings and conclusions or recommendations expressed in this # material are those of the author(s) ...
5,974
661d82adc7d0746635fb57abf6d0e70ee615ada4
# -*- coding: utf-8 -*- file1 = raw_input("Enter the path of your first file: ") file2 = raw_input("Enter the path of your second file: ") Basex = open(file1).read().split() Basey = open(file2).read().split() if Basex != Basey: print("The files are different!") else: print("The files are the same!")
5,975
efe5921afb160b7b5a953cdd0c2f90f64b5f34c9
""" Make sure overwriting read-only files works as expected (via win-tool). """ import TestGyp import filecmp import os import stat import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['ninja']) os.makedirs('subdir') read_only_files = ['read-only-file', 'subdir/A', 'subdir/B', 'subd...
5,976
e1ecc08f66e094841647f72b78bcd29ed8d32668
import requests import json l = list() with open ( "token.txt", "r") as f: token = f.read() # создаем заголовок, содержащий наш токен headers = {"X-Xapp-Token" : token} with open('dataset_24476_4.txt', 'r') as id: for line in id: address = "https://api.artsy.net/api/artists/" +...
5,977
cc6f02f9e1633fa15b97af5f926e083a65a8336e
# Problem 20: Factorial digit sum def factorial(num): sum = 1 while num != 0: sum *= num num -= 1 return sum def sum_digits(num): sum = 0 while num != 0: sum += num % 10 num //= 10 return sum print(sum_digits(factorial(100)))
5,978
30a57197e3156023ac9a7c4a5218bfe825e143d9
# Fix a method's vtable calls + reference making #@author simo #@category iOS.kernel #@keybinding R #@toolbar logos/refs.png #@description Resolve references for better CFG # -*- coding: utf-8 -*- """ script which does the following: - adds references to virtual method calls - Identifies methods belong to a specific ...
5,979
021cbd1bd22f9ec48db2e52b2a98be169bbfdbbd
# -*- coding: utf-8 -*- # @Author: huerke # @Date: 2016-09-03 10:55:54 # @Last Modified by: huerke # @Last Modified time: 2016-09-03 15:54:50 from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler...
5,980
603d7df0639def2b620cca2299077674e35a74b2
from wrapper import SeleniumWrapper from selenium.webdriver.common.by import By class PageDetector: def __init__(self, driver): self.selenium = SeleniumWrapper(driver) def detect(self): if self.selenium.wait_for_presence(locator=(By.ID, "teams-app-bar"), timeout=30): if sel...
5,981
3b5141a86948df6632612f6c9d7fc0089acc60aa
#!/usr/bin/env python # -*- coding: utf-8 -*- import random class Role: """ 角色类 卧底 平民 """ def __init__(self,key_word="",role_id = 0): self.key_word = key_word self.role_id = role_id #平民-0;卧底-1; class User(Role): """ 用户类 玩家 """ def __init__(self,id,role_i...
5,982
c414e5d3934f741540fb5721a529b48f95e17016
# -*- coding: utf-8 -*- import sqlalchemy as sa import ujson from aiohttp import web, WSMsgType from .db import TLE from .log import logger from .utils import parse_sa_filter, parse_sa_order, check_sa_column, get_sa_column async def query(request): filters = [] if 'filters' not in request.query: rai...
5,983
705bc651e7d12769bcf5994168fe6685a6bae05d
#!/usr/bin/env python import sys import requests import numpy as np import astropy.table as at if __name__=='__main__': targets = at.Table.read('targets_LCO2018A_002.txt', format='ascii') headers={'Authorization': 'Token {}'.format(sys.argv[1])} for x in targets['targetname']: obs = requests.get('h...
5,984
86c053b7d4c752182965755ad5b6ba6937ce6f86
import unittest from dispatcher.task import * from mock import * class TestTask(unittest.TestCase): def test_init(self): task_attr = ['filename=C:\\Users\\kcheng\\PycharmProjects\\first_project\\dummy_task2.py', 'frequency=1D', 'time=09:45', 'description=invalid time'] task = T...
5,985
963e736fd4a942fb1c51e1e0a357ad6be48aed9a
#Una empresa les paga a sus empleados con base en las horas trabajadas en la semana. #Realice un algoritmo para determinar el sueldo semanal de N trabajadores #y, además, calcule cuánto pagó la empresa por los N empleados. base = int(input("Dinero por hora trabajada: ")) emp = int(input("Dime el nº de empleados...
5,986
ca25739583d3b7ff449fbd2f56a96631981c815d
# -*- coding: utf-8 -*- import sys from os import path try: import DMP except ImportError: sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from DMP.modeling.vectorMaker import VectorMaker from DMP.modeling.variables import KEY_TOTAL, KEY_TRAIN, KEY_VALID, KEY_TEST from DMP.dataset.dataHan...
5,987
635b02e03578d44f13530bd57ab1a99987d4909d
# -*- coding: utf-8 -*- """ Created on Wed May 16 10:17:32 2018 @author: pearseb """ #%% imporst import os import numpy as np import netCDF4 as nc import matplotlib.pyplot as plt import matplotlib.cm as cm import cmocean.cm as cmo import seaborn as sb sb.set(style='ticks') import mpl_toolkits.basemap as bm import p...
5,988
40ee790f4272c05c1619eb7b2cc66a8b57bbe8a8
# -*- coding: utf-8 -*- from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ class StaffApp(CMSApp): name = _('Staff') urls = ['blog.urls', ] app_name = 'staff' apphook_pool.register(StaffApp)
5,989
4abcca52095a169b71d2527ce52b8367534c42a4
# -*- python -*- # ex: set syntax=python: # vim: set syntax=python: import os import re from collections import defaultdict, namedtuple from enum import Enum from pathlib import Path import buildbot.www.authz.endpointmatchers as ems from buildbot.changes.filter import ChangeFilter from buildbot.changes.gitpoller impo...
5,990
1ad40ef3aa7c81b6eee4fe0b98bcdd2f1110ef8d
#!/usr/bin/env python # On CI, you can pass the logging and the password of dockerhub through # the environment variables DOCKER_USERNAME and DOCKER_PASSWORD import getpass import os import subprocess import sys from builtins import input SCRIPT_DIR = os.path.realpath(os.path.join(__file__, '..')) ROOT_DIR = os.path...
5,991
2c2ad4b6e8c5055afa3dfb3b540a44bda65fa004
""" A web-page. """ import re import pkg_resources from .components import Link, Javascript, inject class Page: """A web-page presenting container. Args: favicon (str): The file name for the favorite icon displayed in a browser tab(default=None) title (str): The page title, disp...
5,992
652918e09a3506869c939be39b71a06467459f8a
import configparser # CONFIG config = configparser.ConfigParser() config.read('dwh.cfg') # DROP TABLES drop_schema="DROP SCHEMA IF EXISTS sparkifydb;" set_search_path="SET SEARCH_PATH to sparkifydb;" staging_events_table_drop = "DROP TABLE IF EXISTS staging_events;" staging_songs_table_drop = "DROP TABLE IF EXISTS s...
5,993
c0e1c0c4545777a669fac19900239ab9baade242
""" Physical units and dimensions """ from sympy import * from sympy.core.basic import Atom from sympy.core.methods import ArithMeths, RelMeths class Unit(Atom, RelMeths, ArithMeths): is_positive = True # make (m**2)**Rational(1,2) --> m is_commutative = True def __init__(self, name, a...
5,994
414fa4021b21cea0dc49380aebfe67f0204f0574
def multiplica(): one = int(input('1º: ')) two = int(input('2º: ')) print('a multiplicação é: ', one*two) def soma(): one = int(input('1º: ')) two = int(input('2º: ')) print('a soma é: ', one+two) def subtra(): one = int(input('1º: ')) two = int(input('2º: ')) ...
5,995
54a6405e3447d488aa4fca88159ccaac2506df2c
#!/usr/bin/env python import serial from action import Action import math comm = serial.Serial("/dev/ttyACM3", 115200, timeout=1) #comm = None robot = Action(comm) from flask import Flask from flask import send_from_directory import os static_dir = os.path.join(os.getcwd(), "ControlApp") print "serving from " + sta...
5,996
0bc53130a4248178f4c3fabbae7d2546f0d5b8fd
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Article(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100, default='admin') content = models.TextField(max_length=5000) ...
5,997
327e9dcba49419b8a8c320940e333765c1d9b980
# Standard Library Imports # Third Party Imports from kivy.clock import Clock from kivy.properties import StringProperty from kivy.uix.screenmanager import Screen, ScreenManager from kivy.uix.widget import Widget # Local Imports from client.source.ui.kv_widgets import ModalPopupButton, SubmissionPopup, FailedSubmissi...
5,998
dc6cbf43424a31f1aefde8bd71b6f1b7ecf8166b
vect = [0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 5.723585101952381, 0.0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0, 0.0, 0, 0.0, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 0, 0.0, 0.0, 0.0, 0, 0....
5,999
5b8322761975ebec76d1dccd0290c0fb1da404e5
# 문제 설명 # 길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다. a와 b의 내적을 return 하도록 solution 함수를 완성해주세요. # 이때, a와 b의 내적은 a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] 입니다. (n은 a, b의 길이) # 제한사항 # a, b의 길이는 1 이상 1,000 이하입니다. # a, b의 모든 수는 -1,000 이상 1,000 이하입니다. # 입출력 예 # a b result # [1,2,3,4] [-3,-1,0,2] 3 # [-1,0,1] [1,0,-1] -2 # 입출력...