text stringlengths 38 1.54M |
|---|
from import_modules import *
from jild_hadith_parsing import *
book_jild_json = {}
all_jild_links = get_all_jild_links(book_url)
for jild_link in all_jild_links[:]:
book_jild_jsons = []
book_jild_json = {}
print(jild_link)
jild_response = protect_get_connection_error(url=jild_link)
jild_soup ... |
import os
import numpy as np
import pathlib
from imageio import imread
import cv2
indir = 'data/gray/'
outdir = 'data/flow/'
hsvdir = 'data/flowhsv/'
warpdir = 'data/warped/'
def draw_hsv(flow):
h, w = flow.shape[:2]
fx, fy = flow[:,:,0], flow[:,:,1]
ang = np.arctan2(fy, fx) + np.pi
v = np.sqrt(fx*fx+... |
from javax.swing import *
def hello(event):
print "Hello. I'm an event."
def test():
frame = JFrame("Hello Jython")
button = JButton("Hello",font=("Currier", 100, 60), actionPerformed=hello)
frame.add(button)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(300, 300)
fr... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
import urllib2
import json
import pprint
from cStringIO import StringIO
import datetime, time
import mysql.connector
from mysql.connector.errors import Error
from mysql.connector import errorcode
with open('/home/admin/collect/db_config.json', 'r') as f:
DB_CONFIG = jso... |
import heapq
from collections import defaultdict
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = []
heapq.heappush(queue, [distances[start], start])
while queue:
current_distance, current_node = heapq.heappop(queue)
if dis... |
from flask import Flask
from flask import render_template, request
app = Flask(__name__)
@app.before_request
def antes_request():
print (" Mensaje Antes de Responder la Petición")
@app.after_request
def despues_reques(response):
print (" Mensaje despues de Resolver la Solicitud en el Servidor")
return response
@... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import blib
from blib import getparam, rmparam, msg, errmsg, errandmsg, site
import pywikibot, re, sys, argparse
import rulib
def process_page(index, page, contents, verbose, comment):
pagetitle = str(page.title())
def pagemsg(txt):
msg("Page %s %s: %s" % (index... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
first_name=models.CharField(max_length=256,blank=False,default="First Name")
last_name=models.CharField(blank=Tru... |
a = 5
b = 10
c = a
a = b
b = c
a
b
four = "4"
print(four*3)
my_name = "student"
print("Hi, " + my_name)
age = "15"
print("I am " + age + " years old")
score = 4
count = 5
total = score * count
print(total)
|
def passo1(p1):
p1 = f'--{p1}--'
def passo2(p2):
print( f'{p1} e {p2}')
return passo2
# retorno = passo1('Abrir a porta')
# # teste = retorno('Entrar no quarto')
# passo1('Abrir a porta')('Entrar no quarto')
def verifica_usuario_logado(funcao):
def verifica():
print('[Antes vamos ve... |
from typing import Optional, Set, Tuple
#: Section 3
#: https://mimesniff.spec.whatwg.org/commit-snapshots/609a3a3c935fbb805b46cf3d90768d695a1dcff2/#terminology # noqa: E501
BINARY_BYTES = tuple(
bytes.fromhex(byte)
for byte in (
"00",
"01",
"02",
"03",
"04",
"... |
"""
author:james.bondu
TO-DO
- Use multi Threading for handling of server sending thing ( A separate method to receive images)
Doing
- Multi Threading to both send and receive data
- There must be some way to simply check if its sending or receiving...May be try a separate thread(or main thread )to do the checking f... |
INF = 100000000
h = []
dp = []
def chmin(a, b):
if a > b:
a = b
return a
def rec(i):
#すでにdpが更新されていればリターン
if (dp[i] < INF):
return dp[i]
if i == 0:
return 0
res = INF
#足場i-1からくる
res = chmin(res, rec(i-1)+abs(h[i]-h[i-1]))
#足場i-2からくる
... |
import pandas as pd
import csv
import sklearn.cluster as cluster
import numpy as np
from sklearn.cluster import KMeans
import seaborn as sns
import matplotlib.pyplot as plt
name=[
'label','original_glszm_GrayLevelVariance',
'log-sigma-1-0-mm-3D_firstorder_Minimum',
'log-sigma-3-0-mm-3D_firstorder_Median',
'log-si... |
RECOMMENDED_URL = "http://www.jrvdev.com/ROAR/VER1/Recommnd.asp"
BALANCE_URL = "http://www.jrvdev.com/ROAR/VER1/Overall.asp"
|
import itertools
import os
import random
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
def set_seeds(seed):
"""
Responsible for producing reproducible results
"""
os.environ["PYTHONHASHSEED"] = str(seed)
random.seed(seed)
np.random.seed(seed)
tf.random.set_see... |
#!/usr/bin/env python
# encoding: utf-8
#
# @Author: Jon Holtzman
# @Date: March 2018
# @Filename: mkgrid
# @License: BSD 3-Clause
# @Copyright: Jon Holtzman
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import arg... |
import board
import busio
i2c = busio.I2C(board.SCL, board.SDA)
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
import time
import numpy as np
import matplotlib.pyplot as plt
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Ada... |
# O(n) Time | O(n) Space, where n is total elements in array
def zigzagTraverse(array):
# Write your code here.
if len(array) < 1:
return []
zigzags = []
direction = "down"
row = 0
col = 0
while len(zigzags) < len(array) * len(array[0]):
zigzags.append(array[row][col])
if row == len(array) - 1 and col =... |
import re
import cPickle
from foreclosure import Foreclosure
foreclosures = []
for year in ["2007", "2008", "2009"]:
for q in ["1","2","3","4"]:
f = file("data/spreadsheet%s.cfm" % (year+"Q"+q)).read()
pl = len(foreclosures)
first = True
print year, q
for row in re.findall("<tr>(.*?)</tr>", f, r... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
from scrapy.conf import settings
from scrapy import log
import pymongo
#class ValidateI... |
#!/usr/local/bin/python3
'''
----------------------------------------------------
Author: Vivian Ta
LAB 5-1
1) Create an application that uses a dictionary to hold the following data:
--------------------------------------
(1, 'Bob Smith', 'BSmith@Hotmail.com')
--------------------------------------
(2, 'Sue Jones', 'S... |
<<<<<<< HEAD
=======
>>>>>>> b461db8a2c2a68dba0af42de3df76fd687069fa5
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("Get a blanket. \n")
print(... |
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.collections import LineCollection
from .genomeutil import get_intervaltree
class ColorUniversalDesign():
# Okabe & Ito's color palette
# Color Universal Design (CUD) - How to make figures and presentations ... |
from PIL import Image
def copyImage(source):
dest = Image.new("RGB", source.size)
for x in range(source.size[0]):
for y in range(source.size[1]):
pix = source.getpixel( (x,y) )
dest.putpixel( (x,y), pix)
return dest
def drawBox(source, start, size, color):
endpoi... |
from __future__ import absolute_import
import unittest
from rutermextract.ranker import Ranker
from rutermextract.term_extractor import Term
class RankerTest(unittest.TestCase):
def setUp(self):
self.ranker = Ranker()
def test_rank(self):
terms = [Term(['1'], '1', 1), Term(['2', '2'], '2', 2)... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import shutil
from pathlib import Path
import matplotlib.pyplot as plt
import pytest
import torch
import torch.nn as nn
from _pytest.fixtures import SubRequest
from pytest import MonkeyPatch
from torchgeo.datasets... |
# file libraryuse/libraryuse/management/commands/dbops.py
#
# Copyright 2013 Emory University General Library
#
# 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.apac... |
import sys
test_cases = open(sys.argv[1], 'r')
for test in test_cases:
if test:
line = test.strip().split()
print line[-2]
test_cases.close()
|
x = 5
from tkinter import messagebox
class parameterException(Exception):
def __init__(self,msg):
Exception.__init__(self, msg)
#self.message = msg
#def __str__(self):
# return str(self.message)
def check(num):
if num > 7:
raise parameterException('value error niggaaaaa... |
#!/bin/env python
'''
Banana Cluster Control Agent Daemon
'''
import sys, os
if __name__ == '__main__':
str_abs_basedir = os.path.dirname(os.path.realpath(__file__))
str_abs_rootdir = os.path.dirname(str_abs_basedir)
sys.path.insert(0, str_abs_rootdir)
from lib.bccagentd import bccagentd
bccagentd... |
#
# FFTJet pileup analyzer configuration. Default is the PFJet
# "MC calibration" mode. Here, we collect FFTJetPileupEstimator
# summaries and do not collect FFTJetPileupProcessor histograms.
#
# I. Volobouev, April 27, 2011
#
import math
import FWCore.ParameterSet.Config as cms
fftjetPileupAnalyzer = cms.EDAnalyzer(
... |
# A User class with both a class attribute
class User:
active_users = 0
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
User.active_users += 1
def logout(self):
User.active_users -= 1
return f"{self.first} has logged out"
def full_name(self):
return f"{self... |
# Princeton University licenses this file to You 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 writin... |
import os
dir = "/home/tarena/FTP"
res = 0
q1 = os.path.getsize("/home/tarena/FTP/exercise01.py")
q2 = os.path.getsize("/home/tarena/FTP/pool.py")
q3 = q1+q2
print(q3)
|
# -*- coding: utf-8 -*-
'''
Created on 7 may. 2017
@author: jose
'''
import time
class objSi(object):
'''
classdocs
'''
def __init__(self, _id='',id_si=0,id_sw=0,id_serv=0,id_entorno='PRO',version='',ip='',user='',home=''):
'''
Constructor
'''
self._id=_id
sel... |
#coding:utf-8
#判断一个实例对象是否是某个类型(即由谁实例化)或者是否继承于某个类(即实例对象的原型)
from collections import Iterable
class Person:
pass
p1 = Person()
print(isinstance(p1,Person)) #True,类型
print(isinstance(p1,object)) #True,原型
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import unittest
from selenium import webdriver
class IndexPageTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.get('http://localhost:5000/index')
def test_index_title_display(self):
self.assertIn("Kai", self.driver.title)
def test_table_disp... |
def decorate_1(func):
print("----开始装饰------")
def inner():
print("----使用方法---{}".format(func()))
return inner
k1 = decorate_1(10)
print(k1)
@decorate_1
def test_dec():
print("----测试用的")
#k2 = K1(20)
test_dec()
#print(k2) |
import torch
from torch.autograd import Variable
from torch.autograd import Function
from torch.autograd import gradcheck
import math
import numpy as np
import torch.nn as nn
import os
import scipy.io as sio
def A(input, index):
input_ = torch.reshape(input.t(), (-1, 1))
A_ = input_[index]
ret... |
# Here we will handle different errors
# this will help us to understand the problems of our neural network better
import sys
ERROR_ARRAY_SIZES = 0
ERROR_ARRAY_SIZES_MSG = "Error: array sizes don't match "
def error(e, extra_explanation=None):
if e == ERROR_ARRAY_SIZES:
error_arrays_sizes(extra... |
import requests
import json
import os
current_dir = os.path.dirname(__file__)
class PatentMenuGetter():
def __init__(self):
self.base_url = "https://worldwide.espacenet.com/3.2/rest-services/search?lang=en%2Cde%2Cfr&q=A61K38%2F00&qlang=cql&p_s=espacenet&p_q=A61K38%2F00"
self.headers = {
... |
from practice.models import City, RecentSearch
from practitioner.models import Specialization
def updateRecentSearches(city, spec):
if city != '' and spec != '':
citi = City.objects.get(slug=city)
speciality = Specialization.objects.get(slug=spec)
try:
obj = RecentSearch.objects.get(city=citi, speciality=spe... |
# 平滑图像
# 目标
#
# 在本教程中:
#
# 用各种低通滤波器模糊图像。
# 对图像应用自定义过滤器(二维卷积)。
#二维卷积(图像滤波)
# 将该内核保持在一个像素之上,将该内核下面的所有 25 个像素相加,取其平均值,
# 并用新的平均值替换中心像素。它继续对图像中的所有像素执行此操作。尝试此代码并检查结果:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('./images/test.jpg')
kernel = np.ones((5, 5), np.float32)/25... |
from tkinter import *
from time import sleep
root = Tk()
##################Betting##########
def betH1():
global totalMoney,H1bets
if totalMoney>0:
totalMoney=totalMoney-1
lb.config(text=("£" + str(totalMoney)))
H1bets=H1bets+1
lb1.config(text=("£" + str(H1bets)))
else:
... |
# -*- coding: utf-8 -*-
# @Time : 2018/11/15 14:41
# @Author : lishanshan
import unittest
from ddt import ddt, file_data
@ddt
class Testjson(unittest.TestCase):
def setUp(self):
pass
@file_data('E:/脚本/Test_study/unittest/ddt_study_data/test_data_list.json')
def testlist(self,value):
p... |
"""
The `magpylib.display.plotly` sub-package provides useful functions for
convenient creation of 3D traces for commonly used objects in the
library.
"""
__all__ = [
"make_Arrow",
"make_Ellipsoid",
"make_Pyramid",
"make_Cuboid",
"make_CylinderSegment",
"make_Prism",
"make_Tetrahedron",
... |
'''
Question:
733. Flood Fill
Descrition:
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the im... |
filepath = "sinhala.lexc"
RaNaroot = {}
with open(filepath) as fp:
for line in fp:
x=line.strip().split(' ')
if 'ල්්්්්්්්්්්්්්්්්්්්්්්ල' in x[0]:
RaNaroot[x[0]] = 0
filepath = "hunspell_roots"
with open(filepath) as fp:
for line in fp:
x=line.strip().split(' ')
... |
file = open('day5.txt')
numList = list(map(int, file.read().split("\n")))
# Parts 1 and 2
def getNumSteps(input):
count = 0
nextIndex = 0
nextValue = 0
insideLoop = True
while(insideLoop):
if count == 0:
nextIndex = input[0]
count += 1
input[0] += 1 if ne... |
import sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.cmds as cmds
kPluginNodeName = "MitsubaDielectricShader"
kPluginNodeClassify = "shader/surface/"
kPluginNodeId = OpenMaya.MTypeId(0x87034)
class dielectric(OpenMayaMPx.MPxNode):
def __init__(self):
OpenMayaMPx.M... |
#!/usr/bin/env python3
# vim: set ai et ts=4 sw=4:
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import csv
dates = []
values = {}
with open('ru-newreg.csv', newline = '') as f:
for row in csv.reader(f, delimiter = ',', quotechar = '"'):
... |
from utils import Timer
from utils import Vec2
from utils import pi
import math
DAY=24
PART='a'
print("###############################")
print ("Running solution for day {d} part {p}".format(d=DAY, p=PART))
print("###############################")
timer = Timer()
# Write your code here
lines = []
result = 0
def g... |
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def insert(self,u,v):
self.graph[u].append(v)
def traverse(self, v, visited):
visited[v] = True
for i in self.graph[v]:
... |
import turtle
turtle.mode("logo")
turtle.tracer(False)
turtle.shape("turtle")
turtle.colormode(255)
# 画栅栏
def zhalan(x,y,chang,gao):
turtle.pu()
turtle.seth(0)
turtle.goto(x,y)
turtle.pd()
turtle.fillcolor(255,255,255)
turtle.begin_fill()
turtle.forward(gao)
turtle.right(90)
turtle.... |
from itertools import product
from typing import Union
from model.actions import Action
from model.cards import Card
class State:
def __init__(self,
current_sum: int,
opponent_points: int,
holds_usable_ace: bool):
self.current_sum = current_sum
s... |
__author__ = 'georg.michlits'
filename_1 = input('enter filename_2 (path): ')
filename_2 = input('enter filename_1 (path): ')
file_merge_name = input('enter merged file_filename: ')
file1 = open(filename_1,'r')
file2 = open(filename_2,'r')
file_merge = open(file_merge_name,'w')
print('reading in file1')
for line in f... |
# def max_pairwise_product(numbers):
#
# n = len(numbers)
# max_product = 0
# for first in range(n):
# for second in range(first + 1, n):
# multiplication_in_between = numbers[first] * numbers[second]
# max_product = max(max_product, multiplication_in_between)
# return m... |
import clr
import sys
import System
sys.path.append(r'E:\code\vs\Console\TestDLL\bin\Debug')
d = clr.AddReference('TestDLL')
from TestDLL import *
m = MasterImpl()
s = m.GetString()
print(s)
m.SetMessage("Hello Python")
s = m.GetString()
print(s)
# 调用返回byte
a = b'1234'
print(a)
print(str(a, encoding="utf-8"))
met... |
# BlueGraph: unifying Python framework for graph analytics and co-occurrence analysis.
# Copyright 2020-2021 Blue Brain Project / EPFL
# 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 a... |
from PyQt5.QtGui import QColor, QPixmap
from PyQt5.QtWidgets import QApplication, QSplashScreen, QMainWindow
from PyQt5.QtCore import Qt
# Generate the splash screen
class SplashScreen:
def __init__(self, parent, image=None, after=None):
self.app = parent
image = QPixmap(image)
image = ima... |
"""A collection of Pacman CRCField compatible CRC algorithms"""
import binascii
#==============================================================================
# CRC16 CCITT
#==============================================================================
# Table driver crc16 algorithm. The table is well-documented a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 9 17:39:29 2020
@author: MenesesGHZ
"""
import numpy as np
import json
class ANN:
def __init__(self,input_size=784,output_size=10):
self.weights = np.ones(shape=(output_size,input_size))
self.output = np.zeros(shape=(output_s... |
sl_file = "./Input/Letters/starting_letter.txt"
il_file = "./Input/Names/invited_names.txt"
PLACEHOLDER = "[name]"
with open(il_file, 'r') as il:
invited_names_list = il.readlines()
with open(sl_file, 'r') as sl:
starting_letter = sl.read()
for name in invited_names_list:
stripped_name = name.str... |
import flowio
import numpy
f = flowio.FlowData('001_F6901PRY_21_C1_C01.fcs')
n = numpy.reshape(f.events, (-1, f.channel_count))
|
import entities
from datastreams import namespaces
#from datastreams import dsui
import struct
import event_data
import cPickle
from ppexcept import *
import os
from select import poll, POLLIN
import time
magic_format = "I"
magic_size = struct.calcsize(magic_format)
rawmagic = 0x1abcdef1
raw2magic = 0x2abcdef2
pickle... |
import argparse
import pandas as pd
from sklearn.preprocessing import StandardScaler, OrdinalEncoder
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from joblib import dump
import yaml
import logging
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(mes... |
import json
import click
import requests
import re
import arrow
def read_json(path):
with open(path) as f:
json_dict = json.load(f)
return json_dict
def write_json(path, _dict):
with open(path, "w") as f:
f.write(json.dumps(_dict))
class Issue:
def __init__(self, _id):
url ... |
from PyQt5.QtGui import qRgb
from idacyber import ColorFilter
from ida_kernwin import msg
from collections import Counter
class AutoXor(ColorFilter):
name = "AutoXOR"
def __init__(self):
self.key = 0x80
self.occurence = 0
self.size = 0
def _update_key(self, buffers):
... |
"""Test HTTP API application
"""
import datetime
import json
import os
from unittest.mock import Mock
import pytest
import smif
from flask import current_app
from smif.data_layer.store import Store
from smif.exception import SmifDataNotFoundError
from smif.http_api import create_app
@pytest.fixture
def mock_schedule... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)
# Solution
def plot_innings_runs_histogram():
runs= ipl_df.pivot_table('runs', aggfunc=np.sum ,index='match_code',columns='inning')
runs.plot.hist(histtype='bar')
plt.show()... |
# Implementation of QANet based on https://github.com/andy840314/QANet-pytorch-
#
# @article{yu2018qanet,
# title={Qanet: Combining local convolution with global self-attention for reading comprehension},
# author={Yu, Adams Wei and Dohan, David and Luong, Minh-Thang and Zhao, Rui and Chen, Kai and Norouzi, Mohamma... |
import unittest
from CONSTANTS import FACE_API_KEY, FACE_BASE_URL
from face.FaceAPIWrapper import FaceAPIWrapper
class TestFaceAPIWrapper(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(TestFaceAPIWrapper, cls).setUpClass()
key = FACE_API_KEY
base_url = FACE_BASE_URL
... |
from flask import Flask
import os
PORT = 8080
name = os.environ['NAME']
if name == None or len(name) == 0:
name = "world"
MESSAGE = "Good morning, " + name + "!"
print("Message: '" + MESSAGE + "'")
app = Flask(__name__)
@app.route("/")
def root():
print("Handling web request. Returning message.")... |
import graphlab
import pickle
from graphlab import aggregate as agg
import itertools
authors=graphlab.SFrame('./170331_PURE_Data_Challenge/PURE Data Challenge/authors.csv')
pub_authors = authors.groupby(key_columns='PERSON_ID', operations={'publications':agg.CONCAT('PUBLICATION_ID')})
solo_count = 0
links = dict()
f... |
# coding: utf-8
"""
SevOne API Documentation
Supported endpoints by the new RESTful API # noqa: E501
OpenAPI spec version: 2.1.18, Hash: db562e6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class IndicatorRequestDto(o... |
from pwn import *
pop_3_ret_addr = 0x0809e3e5
pop_2_ret_addr = 0x0809a6fc
pop_1_ret_addr = 0x080481ad
bss_addr = 0x080EC000
bss_len = 0x2000
#p = process('./not_the_same_3dsctf_2016')
p = remote('node3.buuoj.cn', 28377)
elf = ELF('not_the_same_3dsctf_2016')
mprotect_addr = elf.symbols['mprotect']
port = 1 + 2 + 4
... |
import copy
import dataclasses
import pytest
import time
import typing as tp
from pytest import approx
from compgraph import operations as ops
from . import memory_watchdog
KiB = 1024
MiB = 1024 * KiB
class _Key:
def __init__(self, *args: str) -> None:
self._items = sorted(args)
def __call__(sel... |
def calcualte(num):
try:
print(100/num)
except ZeroDivisionError:
print("num value cant be zero")
finally: #It will always be printed
print("Code executes") # #Use case is it can be helpful to close the file if consumed
calcualte(1)
calcualt... |
'''
Extract feature vectors from video frames.
These features come from the Pool5 layers of a ResNet deep
neural network, pre-trained on ImageNet. The algorithm captures
frames directly from video, there is not need for prior frame extraction.
Copyright (C) 2019 Alexandros I. Metsai
alexmetsai@gmail.com
This program ... |
from os import environ
import os
import json
import datetime
from configparser import ConfigParser
from kb_Metrics.metricsdb_controller import MetricsMongoDBController
from bson.objectid import ObjectId
from pymongo import MongoClient
DEBUG = False
def print_debug(msg):
if not DEBUG:
return
t = str(da... |
import sys
sys.stdin = open('input.txt')
DIRS = ((-1, 0), (1, 0), (0, -1), (0, 1))
def dfs(r, c, number):
if len(number) == 7:
result.add(number)
return
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < 4 and 0 <= nc < 4:
dfs(nr, nc, number + graph[nr][nc]... |
from scrapy.item import Item, Field
class Company(Item):
name = Field()
logo = Field()
short_description = Field()
long_description = Field()
founded_date = Field()
category = Field()
# contact
website = Field()
blog = Field()
twitter = Field()
phone = Field()
email =... |
from flask import Flask, jsonify, request,abort, make_response
from upcoming_fights import upcoming_fights as u
import json
app = Flask(__name__)
events = ['one','two','three']
with open('Data/winners.json') as json_data:
d = json.load(json_data)
@app.route('/')
def index():
return "STILL HERE!"
@app.route('/ap... |
# -*- coding:utf-8 -*-
# @Time: 6/5/20 11:49 AM
# @Author:bayhax
# absolute_import 不会与库冲突,python
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery, platforms
from django.apps import apps
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'UGC.set... |
#!/usr/bin/env python
import time
import rospy
print "[Robotics Indoor SDK] initializing ROS node.."
rospy.init_node('positioning', anonymous=True)
print "[Robotics Indoor SDK] ROS node started, initializing positioning system.."
#import lib.x86.robotics_indoor_sdk
import lib.armv7l.robotics_indoor_sdk
while True... |
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randint(100, size=(100))
y = np.random.randint(100, size=(100))
colors = np.random.randint(100, size=(100))
sizes = 10 * np.random.randint(100, size=(100))
plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')
plt.colorbar()
... |
import os, sys
from iotbx import pdb
def run(filename, verbose=True):
print "run",filename
pdb_inp = pdb.input(filename)
hierarchy = pdb_inp.construct_hierarchy()
for model in hierarchy.models():
if verbose: print 'model: "%s"' % model.id
for chain in model.chains():
if verbose: print 'chain: "%... |
from django.contrib import admin
from .models import Category, Task, Author, Book
from django.utils import timezone
from django.utils.translation import ngettext
from django.contrib import messages
# Register your models here.
@admin.action(description="in this action we want update due_at field")
def update_due_at(... |
from os import listdir
from os.path import isfile, join, dirname, realpath
import time
import json
from functools import partial
import logging
import click
from obswebsocket import obsws, requests
import numpy
import cv2
from mss import mss
logging.basicConfig(level=logging.ERROR)
host = "localhost"
port = 4444
VA... |
###
### starts at the tree root and explores all of the neighbor nodes. save it the queue
### when it is at the present depth prior to moving on to the nodes at the next depth level.
### Keep running until it run out of the nodes.
### At the end node, it saved in the queue is the path and x_coor made it to keep t... |
#!/usr/bin/python
import SocketServer
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
import serial
import time
import sys
from subprocess import call
import os
import socket
from socket import error as socket_error
import os.path
i... |
import itertools
from logging import *
import sys
import numpy as np
import matplotlib.pyplot as plt
basicConfig(stream=sys.stderr, level=DEBUG)
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm... |
# -*- coding: utf-8 -*-
#@Author : lynch
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Input, Dense,Dropout,LSTM,Bidirectional
import matplotlib.pyplot as plt
import numpy as np
impo... |
##########################################
# Calculator Functions
##########################################
# Function1: add two lists together using Lambda and Map
# each element of list1 will be added to the corresponding element of list2
def add_lists(list1, list2):
return map(lambda x, y: x+y, list1, li... |
#! /usr/bin/env python
# coding: utf-8
# 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
#
#
#
# 例如:
# 给定二叉树: [3,9,20,null,null,15,7],
#
# 3
# / \
# 9 20
# / \
# 15 7
#
#
# 返回其层次遍历结果:
#
# [
# [3],
# [20,9],
# [15,7]
# ]
#
#
#
#
# 提示:
#
# ... |
import pandas as pd
import numpy as np
import plotly.graph_objects as go
df = pd.read_excel('corn.xlsx', index_col=0)
#print (df.head())
#
arr = df.to_numpy()
data = arr.reshape(30, 12)
rows = data.shape[0]
cols = data.shape[1]
data_new = np.copy(data)
for x in range(0, rows):
for y in range(0, cols):
... |
from flack.request import Request
from flack.response import Response
from flack.view import View
class Index(View):
def get(self, request: Request, *args, **kwargs):
body = self.engine.render('home.html', context={
'name': 'home'
})
return Response(body=body, headers={'Content... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from rest_framework import generics
from .serializers import BucketlistSerializer
from .models import Bucketlist
#ListCreateAPIView is a generic view which provides GET (list all) and POST method handler
class CreateVi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.