text stringlengths 38 1.54M |
|---|
import pytest
from yads import yads
import json
import tempfile
from exceptions import *
@pytest.fixture
def tempfile_name():
fd, path = tempfile.mkstemp(suffix=".txt", prefix="test_file")
return path
def test_invalid_ttl(tempfile_name):
data_store = yads(tempfile_name)
key = "A"
simple_json = "... |
import forecastio
from secrets import FORECAST_IO_API_KEY
import arrow
def get_preci_prob_by_loc_time(lat, lng, time):
time = time.datetime
forecast = forecastio.load_forecast(FORECAST_IO_API_KEY, lat, lng, time, units="us")
byHour = forecast.currently()
return byHour.precipProbability
|
# How to have the 'concept' of numbers?
# Let counting happen by how many times you apply a function to an argument
def zero(x): # don't call the function x
def fn(y):
return y # apply zero times
return fn
def one(x):
def fn(y):
return x(y) # apply once
return fn
def two(x):
de... |
from wordpress_project import *
def main():
welcome()
if discovery_version() == False:
print("finish!")
else:
https_and_hsts()
search_important_headers()
discovery_admin_panel()
discovery_wordpress_with_robots_file()
discovery_usernames_with_... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import urllib, urllib2
uri_base = "http://127.0.0.1:12345/ltp"
data = {
's': '我爱北京天安门',
'x': 'n',
't': 'all'}
request = urllib2.Request(uri_base)
params = urllib.urlencode(data)
response = urllib2.urlopen(request, params)
content = response.read().strip()
pri... |
#!/usr/bin/env python
################################################################################
## Copyright 2017 "Nathan Hwang" <thenoviceoof>
##
## 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... |
# Exceptions, APIs and Protocols
################################################################################
# few exception types
# IndexError # integer index is out of range
# KeyError # look-up in a mapping fails
# ValueError # object is of the right type, but contains an inappropriate value.
# TypeError
z = ... |
"""
dp[j]表示可以使用的硬币方法
dp[j-coins[i]]表示使用一个coins[i]拼接成j的方法
同时,由于按硬币面值从小到大考虑,dp[j]为前i种类型硬币
进行组合时的组合数,当组成j的币值种类中包含coins[i]时,
计算如下:
组成面值和为j的硬币中,最后一枚不使用coins[i]时的组合数,即上一步所求结果dp[j]
组成面值和为j的硬币中,最后一枚使用coins[i]时的组合数,即dp[j-coins[i]]
这两个事件构成了事件的全体,因此dp[j] = dp[j]+dp[j-coins[i]]
"""
class Coins:
def countWays(self, n... |
import re
from collections import Counter
from aocd import data
def generate_coords(claim):
return [(x, y) for x in range(claim[1], claim[1] + claim[3]) for y in range(claim[2], claim[2] + claim[4])], claim[0]
def part_1(data):
coords = [coord for coords, id_ in [generate_coords(claim) for claim in data] f... |
#Известен ГОД. Определить, будет ли этот год високосным, и к какому веку этот относится.
#Високосный год это каждый 4 год.
year = int(input())
if year % 4 == 0:
print("Високосный")
else:
print("Не високосный")
print(year//100+1, "\tВек") |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import Queue
import sys
from threading import Thread
# working thread
class Worker(Thread):
worker_count = 0
timeout = 2
def __init__(self, work_queue, result_queue, **kwargs):
Thread.__init__(self, **kwargs)
self.id = Worker.worker_count
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayEcapiprodDataPutResponse(AlipayResponse):
def __init__(self):
super(AlipayEcapiprodDataPutResponse, self).__init__()
self._data_version = None
@property
... |
from PIL import Image, ImageFont, ImageDraw
from string import *
def main():
file = open('trainingLists.txt', 'w')
fontList = [ImageFont.truetype("C:\Windows\Fonts\OCRAEXT.ttf", 18),
ImageFont.truetype("C:\Windows\Fonts\AGENCYR.ttf", 18),
ImageFont.truetype("C:\Windows\Fonts\AR... |
import h5py as h5
import numpy as np
import pytest
import six
from nexusformat.nexus import *
field1 = NXfield((1,2), name="f1")
field2 = NXfield((3,4), name="f2")
field3 = NXfield((5,6), name="f3")
def test_group_creation():
group1 = NXgroup()
assert len(group1) == 0
group2 = NXgroup(field1)
... |
# -*- coding: utf-8 -*-
from selenium.webdriver.chrome.webdriver import WebDriver
success = True
wd = WebDriver(r"myDir\chromedriver.exe")
wd.implicitly_wait(60)
def is_alert_present(wd):
try:
wd.switch_to_alert().text
return True
except:
return False
try:
wd.get("http://localhost... |
# Given pointers to the head nodes of 2 linked lists that merge together at some point,
# find the node where the two lists merge. The merge point is where both lists point to the same node,
# i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different,
# and neither will... |
from netmiko import ConnectHandler
import os
ciscoasa = {
'device_type': 'cisco_asa',
'ip': '192.168.1.76',
'username': 'cisco',
'password': os.getenv('ciscopass'),
}
conn = ConnectHandler(**ciscoasa)
config_commands = ['pager 0', 'logging permit-hostdown']
output = conn.send_config_set(config_comma... |
#BOJ11724 연결 요소의 개수 20210224
import sys
from collections import deque
input = sys.stdin.readline
def main():
n,m = map(int, input().split())
adj = [ [] for _ in range(n+1)]
for _ in range(m):
a,b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
q = deque()
cnt =... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import astropy.constants as c
import astropy.units as u
import sys
import matplotlib.animation as animation
sys.path.insert(0, '../')
from matplotlib.colors import LogNorm
from six.moves import cPickle as pickle
# In[7]:
import pyathena as pa
# ... |
from flask import Flask, jsonify, abort, request
from flask_script import Manager
# 导入认证的类库
from flask_httpauth import HTTPBasicAuth
from flask_restful import Api,Resource
app = Flask(__name__)
manager = Manager(app)
api=Api(__name__)
auth = HTTPBasicAuth()
#设置认证的回调函数
#设置认证的回调函数,需要认证时自动回调,成功返回True
@auth.... |
from django.shortcuts import render
# from django.template import loader
from django.views.generic import View
from django.views import generic
# Create your views here.
class IndexView(generic.TemplateView):
template_name = 'exchange/index.html'
|
#use ordered set
def newNumeralSystem(number):
alphaStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphaMap = {}
numberMap = {}
finalAns = []
for i in range(len(alphaStr)):
alphaMap[alphaStr[i]] = i
for i in range(len(alphaStr)):
numberMap[i] = alphaStr[i]
#print(... |
from django.db import models
from django.contrib.auth.models import User
from django_jalali.db import models as jmodels
from .utils import get_kebab_case, get_formatted_jdatetime
# from .model_mixins import LogMixin
from .value_choices import (
WORK_UPDATE_TYPES,
ATTENDANCE_ACTION_TYPES,
AVAILABIL... |
from game_picture.player import *
from game_picture.mob import Mob
from game_picture.explosion import Explosion
from game_picture.pow import Pow
import pygame
import os
import random
'''
初始化格式
'''
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("飞机大战11.0")... |
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^$', 'home.views.home', name = 'home'),
#these 3 are for editing the database info as staff
url(r'^usermanage', 'home.views.users', name = '... |
import pytest
from maha.constants import (
ALEF_SUPERSCRIPT,
ARABIC,
ARABIC_NUMBERS,
BEH,
EMPTY,
FATHA,
KASRA,
)
from maha.parsers.functions import parse
from maha.parsers.templates import Dimension, DimensionType
from maha.rexy import Expression, ExpressionGroup
from tests.utils import lis... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pathlib import Path
import sys
import time
from typing import List, Optional
def read_proc(pid: int) -> dict:
f = Path('/proc') / str(pid) / 'status'
result = {}
for line in open(f).readlines():
k,v = line.split(':')
result[k.strip()] = v.... |
from sqlalchemy import Column, Integer, String, Boolean
from init import db
class Msg(dict):
def __init__(self, success=False, msg='', obj=None):
super(Msg, self).__init__({'success': success, 'msg': msg, 'obj': obj})
class User(db.Model):
__tablename__ = 'user'
id = Column(Integer, primary_key... |
import unittest
import copy
import datetime
from anchore_engine.db import ImagePackageVulnerability
class TestImagePackageVulnerabilityHashing(unittest.TestCase):
def test_cmp(self):
c1 = ImagePackageVulnerability()
c1.pkg_name = 'testpkg1'
c1.pkg_version = '1.0'
c1.pkg_arch = 'x86... |
import numpy as np
import astropy.io.fits as fitsio
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import mk_sample
filters = ['a','w','u','b','v','i','z','d','j','s','h']
def mk_stamps(drop_filt,sample_type,cut_type='no_cut',s=67):
if cut_type=='neg_nuv':
sample = mk_sam... |
# Задание - 1
# Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
#
# Блок - схема
# https://drive.google.com/file/d/1RI4u-DGMvbfC7f_qaUMVbSWK1Pmy7F7Q/view?usp=sharing
print('Введите трехзначное число')
a = int(input('a = '))
if 99 < a < 1000:
a_1 = a // 100
a_2 = a // 10 % 10
... |
# Generated by Django 3.1.3 on 2020-12-03 18:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('listing', '0004_auto_20201129_1211'),
]
operations = [
migrations.RenameField(
model_name='listing',
old_name='red_r... |
import os
import pytest
import six
from .find import find_all, find_one
from ..testing.utils import apply_fs
def test_find_no_files(tmpdir):
with tmpdir.as_cwd():
paths = list(find_all(os.getcwd(), ('readthedocs.yml',)))
assert len(paths) == 0
def test_find_at_root(tmpdir):
apply_fs(tmpdir, {'... |
#! usr/bin/env python
# -*- coding:utf-8 -*-
'test'
__author__ = 'HUSKY'
import sys,os
import time
print('just test...')
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals
from contextlib import closing
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.event import listens_for
from psycopg2.extensions import new_type, register_type
from last_fm.app import app
__all__ = [b"db"]
db = SQLAlc... |
import mgrs
from RPLCD.i2c import CharLCD
import time
import gps
# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
#lcd definitions
lcd=CharLCD(i2c_expander='PCF8574', address=0x27)
sample='$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.... |
from django.db import models
class Team(models.Model):
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
photo = models.ImageField(upload_to='photos/%Y/%m/%d')
designation = models.CharField(max_length=32)
facebook_url = models.URLField(max_length=255)
Ins... |
#!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
#!/usr/bin/env python
# coding: utf-8
import os
current_dir = os.path.dirname(os.path.realpath(__file__))
def get_certs():
return (
open(os.path.join(current_dir, "certs", "ali_private_key.pem")).read(),
open(os.path.join(current_dir, "certs", "ali_public_key.pem")).read()
)
def get_certs_... |
"""
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
"""
class Solution:
def generateParenthesis(self, n: int) -> list:
res = []
self.helper('', res, 0, 0, n)
return res
def helper(self, cur, res, left, right, n):
if right ... |
import pandas as pd
import glob
import datetime
# #readAllFiles
all_files = glob.glob("*.csv")
df = pd.concat((pd.read_csv(f) for f in all_files))
# # df = pd.read_excel("em290301_bike.xlsx",sep=";")
# print(df.head())
# print(df.shape)
#
# #concatenate all columns into one
df['concat'] = pd.Series(df.fillna('').value... |
import numpy as np
import networkx as nx
import scipy.stats as stats
from point_process import *
from graph_manip import *
import sys
def let_hawkes_fly(target, alpha, maxgen=100):
G = nx.read_edgelist('%s/%s.txt' % (target, target), nodetype=int)
theta = alpha / lambda_max(G)
T = exact_hawkes_maxgen... |
#!/user/bin/env python3
#---------------------------------------------------------------------#
# Script Name Ops Challenge 12
# Author Kimberley Cabrera-Boggs
# Date of last revision October 20, 2020
# Description of purpose Network Security Tool w/Scapy Part 2 of 3
#-------... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-17 16:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... |
from django.db import models
from datetime import datetime
class Realtor(models.Model):
name = models.CharField(max_length=200, verbose_name="اسم")
photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name="تصویر")
description = models.TextField(blank=True, verbose_name="توضیحات")
phone = m... |
# coding=utf-8
from pymongo import MongoClient
from lxml import html
import requests
base_url = "https://sou.zhaopin.com/?pageSize=60&jl=664&in=10100&jt=23,160000,045&kt=3"
headers = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
clien... |
#!/usr/bin/env python
import roslib
roslib.load_manifest('beginner_tutorials')
import rospy
from geometry_msgs.msg import Twist
import curses.wrapper
import curses
def talker(screen):
pub=rospy.Publisher('/RosAria/cmd_vel',Twist)
rospy.init_node('keyboard_vel_cmd')
twist=Twist()
while not rospy.is_shutdown():
k... |
import os
import sys
from credentials import SPOTIFY_AUTH_TOKENS
import spotipy
import webbrowser
import spotipy.util as util
from spotipy.oauth2 import SpotifyOAuth
import json
from json.decoder import JSONDecodeError
SCOPE = 'user-read-private user-read-playback-state user-modify-playback-state'
SPOTIPY_CLIENT_ID = ... |
rows = int(input("How many rows?: "))
k = 0
for row in range(rows,0,-1):
for col in range(0,k):
print(end=" ")
for col in range(0,row):
print("*",end=" ")
print()
k += 1
|
# Generated by Django 3.2.6 on 2021-10-05 00:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cadastros', '0008_alter_atividade_arquivo'),
]
operations = [
migrations.AlterField(
model_name='atividade',
name='a... |
"""Main Run File"""
import robot_library
def main():
"""Main Routine"""
bot = robot_library.Robot()
bot.part_a6()
bot.part_a2()
bot.part_a3()
bot.part_b7()
bot.create_plots()
main()
|
"""Loads in from json file and populated the locations table"""
import json
from sqlalchemy import func
from model import Location
from model import User
from model import connect_to_db, db
from server import app
def load_location_data():
"""Load location data from zipasaur.json into locations database"""
... |
la = iface.activeLayer()
feat = la.getFeatures()
feat = [f for f in feat]
for i in feat:
g = eval(i.geometry().asJson())['coordinates'][0]
if len(g)>1:
la.select(i.id())
|
"""DB Service Module
Single service to handle all database interactions.
Uses Lazy Pirate Pattern
The goal is to minimize `psycopg2.connect` calls (which is expensive).
"""
import logging
import psycopg2
import zmq
logger = logging.getLogger(__name__)
class Server:
"""Single server that interacts with DB"""
... |
import numpy as np
from stl import mesh
import math
import sys
Point_1 = np.array([-25,0,0])
Point_2 = np.array([-24.14815,7.07,-6.47])
Point_3 = np.array([-24.373,0,-5.56])
Normal = np.array([-0.99,0,-0.11])
def counter_clockwise_check(P1,P2,P3,N):
V1 = np.subtract(P2,P1)
V1 = V1/np.linalg.norm(V... |
import math
print("Este programa retorna o tepo estimado de download para um dado tamanho de arquivo e velocidade internet")
arquivo = float(input("Digite o tamanho do arquivo em MB: "))
velocidade = float(input("Digite a velocidade da sua internet em mbps: "))
tempo = (arquivo*8.0)/(velocidade*60.0)
print(f"Seu arqui... |
class Solution(object):
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
import collections, heapq
res = []
count = collections.Counter(words)
heap = [(-n, word) for word, n in count.items()]
... |
# -*- coding: UTF-8 -*-
import uuid
from .managers import *
# django imports
from django.db import models
from django.db.models.signals import m2m_changed, post_save, post_delete
from django.dispatch import receiver
from django.utils import timezone
class Area(models.Model):
title = models.TextField( default = '... |
'''from django import forms
from .models import Lecturer
class PostForm(forms.ModelForm):
class Meta:
model = Lecturer
fields = ['bank', 'account', 'career', 'certification', 'profilephoto', 'idphoto']
'''
from django import forms
from lecturer.models import Lecturer
class PostForm(forms.ModelForm... |
from numpy import *
a = float(input('Aceleracao: '))
v = float(input('Velocidade inicial: '))
n = int(input('Numero: '))
t = arange(n)
d = zeros(n)
k = ((a*(t**2))/2)+v*t
print(k) |
from django.db import models
from django.contrib.auth import settings
class Cat(models.Model):
class Meta:
verbose_name = ('Кот')
verbose_name_plural = ('Коты')
User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,verbose_name='Хозяин')
Name = models.CharField(max_le... |
"""
Functions generate images from a step file.
Author: Drew
"""
import cadquery as cq
import re
from wand.image import Image
from wand.color import Color
import os
import requests
from PIL import Image as I
from PIL import ImageDraw as D
# import zipfile
# import json
VIEWS = {'x': (1, 0, 0),
'-x': (-1, 0... |
# Module for processing student data.
from ...student import Student
from ..memory_store import MemoryStore
from . import exam_tools
ID_FIELD_NAME = "studentId"
def get_students():
"""
Gets the results of students with at least one exam score.
:returns: String List of student IDs.
"""
student_... |
__author__ = 'MOLTRES'
import os
import datetime
import pandas as pd
from util.futuresdatabase import FuturesDatabase
instrument_list = ['GC', 'CL', 'ZB']
futures_db = FuturesDatabase()
for instrument in instrument_list:
table_name = instrument + '_LAST'
futures_db.drop_table_if_exist(table_name)
f... |
from rdflib import Namespace, Graph, Literal, RDF, URIRef
from rdfalchemy.rdfSubject import rdfSubject
from rdfalchemy import rdfSingle, rdfMultiple, rdfList
from brick.brickschema.org.schema._1_0_2.Brick.UndefinedMeasurement import UndefinedMeasurement
from brick.brickschema.org.schema._1_0_2.Brick.Water import Water... |
def FT_HDP(soup, tag, tbl, home, away):
_0, _1, _2, _3 = [], [], [], []
_4, _5, _6, _7 = [], [], [], []
_8, _9, _10, _11 = [], [], [], []
_12, _13, _14 = [], [], []
try:
for i in soup.find(tag, tbl):
# print(i)
# print(" ")
nullodd = '1.00'
o... |
import json
import requests
import smtplib
from email.mime.text import MIMEText # 导入模块
from datetime import datetime
from .db.api import SQL
from .db import config
from functools import wraps
from flask import session
from .service_exception import GetOpenIdException
from . import config as service_config
def login... |
"""
miRACL - MultI-label Relation-Aware Collaborative Learning
for Unified Aspect-based Sentiment Analysis
# Sentence Representation
A. Word Embeddings - Pretrained distil-USE (multi-lingual sentence embeddings)
B. Features:
0. Sharing Feature: Dropout -> CNN -> Dro... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
replaces = [(b'gear', '0001_initial'), (b'gear', '0002_auto_20150925_1031'), (b'gear', '0003_auto_20150925_2358'), (b'gear', '0004_auto... |
# Generated by Django 3.0.6 on 2020-05-24 05:43
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Departmen... |
from django.db import models
from enum import Enum
from django.db.models.deletion import CASCADE
# Create your models here.
class Quarto(models.Model):
quarto_id = models.AutoField(primary_key=True)
nome = models.CharField(blank=False, null=False, max_length=30)
numero = models.IntegerField(blank=False... |
import string
import random
import tkinter as tk
# tkinter set-up
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
root2 = tk.Tk()
words = tk.Frame(root2)
words.pack()
wordList = ['PROGRAMMING','CODE','ENCRYPTION','ALGORITHM','BOOLEAN','STRING','INTEGER','ARRAY','INTERNET','CIPHER','CAESAR','VARIABLES... |
# -*- coding: utf-8 -*-
#JI-69
from Tkinter import *
root = Tk()
drawpad = Canvas(root, width=400,height=725, background="grey")
drawpad.grid(row=0, column=1)
screen = drawpad.create_rectangle(50,50,350,250, fill = "white")
#Buttons 1-9
button0 = drawpad.create_rectangle(112.5,650,162.5,675, fill = "white")
button1 =... |
# -*- coding:utf-8 -*-
#!python3
'''
auth : yi.chen
date :
desc : CART
'''
import pickle
import numpy as np
from DecisionTree.treePlotter import treePlotter
def loadDataSet(filename):
"""
:param filename: 文件路径
:return: dataMat
"""
fr = open(filename)
dataMat = []
for line ... |
from __future__ import absolute_import
import pytest
import doctest
import os
import numpy as np
import pandas as pd
import neurokit as nk
run_tests_in_local = False
#==============================================================================
# BIO
#===============================================================... |
import gevent
from common import *
class TestResult(BaseTestCase):
def test_ack_1_message(self):
self.assertEqual(self.post(['foo']), [1])
messages=self.pull()
self.assertDictContainsSubset({'id':1,'message':'foo'}, messages[0])
self.assertInDatabase(
'queue1_rst',
... |
import argparse
import pandas as pd
from tkinter import *
from tkinter import ttk
from tkinter import scrolledtext
import os
from pydub import AudioSegment
from pydub.playback import play
import threading
import logging
from datetime import datetime
class PlayAudioSample(threading.Thread):
"""plays the sound corr... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import calendar
from datetime import datetime
def ut(date_time):
return calendar.timegm(date_time.timetuple())
def dt(unix_time):
return datetime.utcfromtimestamp(float(unix_time))
|
#!/usr/bin/python3
# This decrypts the protected µCTF Hollywood code ("stage2") and writes it to a file suitable for opening with IDA
# We re-implement the Hollywood function that decrypts code before execution
# If X is the address of the value to decrypt, we use X+2 as the key and *X as the value to decrypt
# Some ... |
import math
class Grid:
def __init__(self, options, width):
self.x = 0
self.y = 0
self.options = options
self.width = width
self.height = math.ceil(len(self.options)/self.width)
self._grid = self.generateGrid()
def generateGrid(self):
resGrid = []
... |
import doctest, math
def distance(p1, p2):
'''
>>> distance((0, 0), (3,4))
25
>>> distance((0,0), (1,1))
2
'''
return (pow(p1[0]-p2[0],2) + pow(p1[1]-p2[1],2))
if __name__ == "__main__":
doctest.testmod()
|
from django.template import Library
from django.conf import settings
from mgcprojects.models import mlProjects
register = Library()
@register.inclusion_tag("mgccms/snippet/top_digg.html")
def projects_top_digg():
return {
'news': mlProjects.objects.filter(status=2).select_related(depth=1).order_by("-d... |
#!/usr/bin/env python3
import sys
def num_pcg(fname):
count = 0
for line in open(fname):
fields = line.rstrip("\r\n").split()
if line.startswith("#!"):
continue
if "gene" in fields[2] and "protein_coding" in line:
count = count + 1
# print('check')
print(count)
test_output = num_pcg(sys.argv[1]) |
import logging
from django.db import models
from blobstore_storage.storage import BlobStoreStorage
class Category(models.Model):
name = models.CharField(max_length=40, unique=True)
def __unicode__(self):
return unicode(self.name)
class File(models.Model):
file = models.FileField(
storage=... |
#!/usr/bin/env python3
import json
import time
import lzma
import glob
from datetime import datetime
import timeout_decorator
import instaloader
import sys
import os
TIMEOUT = 7200
@timeout_decorator.timeout(TIMEOUT)
class DownloadComments():
"""
Classe para coletar comentários de posts do instagram. Utili... |
# -*- coding: utf-8 -*-
import hr_employee
import base_agency
import account_journal
import account_move_line
import res_users
import account_invoice
import account_account
|
from django.db import models
# Create your models here.
class math(models.Model):
operands = (('+', '+'), ('-', '-'), ('x', 'x'), ('/', '/'))
num1 = models.CharField(max_length=10)
num2 = models.CharField(max_length=10)
operation = models.CharField(max_length=1, choices=operands)
|
# pylint: skip-file
# pylint: disable=too-many-public-methods
class ReplicationController(DeploymentConfig):
''' Class to wrap the oc command line tools '''
replicas_path = "spec.replicas"
env_path = "spec.template.spec.containers[0].env"
volumes_path = "spec.template.spec.volumes"
container_path =... |
import tensorflow as tf
from tensorflow.python.ops import rnn, rnn_cell
import numpy as np
import matplotlib.pyplot as plt
import time
if(tf.__version__.split('.')[0]=='2'):
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# Load MNIST dataset
import input_data
mnist = input_data.r... |
'''
Module: maze
Author: David Frye
Description: Contains the Maze class.
'''
import collections
import random
import time
from cell import Cell
from region import Region
from utility import Direction
class Maze:
'''
Class: Maze
Description: Represents an individual maze, consisting of multiple cells.
'''
DEFA... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-17 02:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('search', '0006_auto_20161017_1046'),
]
operations = [
migrations.AlterUniqueTogether(... |
# Given a list of daily temperatures T, return a list such that, for each day in the input,
# tells you how many days you would have to wait until a warmer temperature. If there is no
# future day for which this is possible, put 0 instead.
# For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, ... |
# -*- coding: utf-8 -*-
# 55.7522200 широта
# 37.6155600 долгота
# working google key for google maps directions API!
# AIzaSyDhefiliHi_T2eke5NRHzKWvGqj7OteDog
# example request
# https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=AIzaSyDhefiliHi_T2eke5NRHzKWvGqj7OteDog... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20150202_2124'),
]
operations = [
migrations.AlterField(
model_name='user',
name=... |
def getIntList(intFileName):
# Get a list of integers from a file
intFile = open(intFileName)
intList = []
for line in intFile:
# Iterate through the lines of the file and add each integer to list
intList.append(int(line.strip()))
intFile.close()
return intList
def filterFastaWithIndexes(fastaFileN... |
import eventlet
from oa import oauth
from db import db
from ma import ma
import json
from datetime import datetime
from flask import Flask, jsonify
from flask_socketio import SocketIO
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_apscheduler import APScheduler
from flask_jwt_extend... |
import argparse
from IAA import calc_agreement_directory
from Dependency import *
from Weighting import *
from pointAssignment import *
from Separator import *
def calculate_scores_master(directory, tua_file = None, iaa_dir = None, scoring_dir = None, repCSV = None):
print("IAA PROPER")
iaa_dir = calc_agreem... |
import cv2
import numpy
img = cv2.imread("smallgray.png", 0)
print(img)
# cv2.imwrite("newsmallgray.png", img)
print(img[0:2, 2:4])
print("=" * 100)
ims = numpy.hstack((img,img))
print(ims)
lst = numpy.hsplit(ims, 2)
print(lst)
|
import os, datetime, shutil, sys
installe = raw_input('Install nncloudtv package(y/n): ')
if installe == 'y':
os.chdir("../../nncloudtv")
os.system("mvn clean compile install -DskipTests")
os.chdir("../nnqueue/installer")
os.chdir("..")
os.system("mvn clean compile")
os.system("mvn clean assembly:assembly -Dsk... |
# Generated by Django 2.2.3 on 2019-08-05 15:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('community', '0012_cronlog'),
]
operations = [
migrations.AlterField(
model_name='cronlog',
name='cronjob_comment',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.