text stringlengths 38 1.54M |
|---|
import argparse
import hashlib
import json
import os
import re
import shutil
import sys
import tarfile
from datetime import datetime
from pathlib import Path
import requests
class GetBaktaDatabaseInfo:
"""
Extract bakta database information to make a json file for data_manager
"""
def __init__(
... |
'''
Write a Python script to display the -
a) Current date and time
b) Current year
c) Month of year
d) Week number of the year
e) Weekday of the week
f) Day of year
g) Day of the month
h) Day of week
'''
import datetime
print ("a) Current date and time:", datetime.datetime.today())
print ("b) Current year:", datetim... |
from flask import Flask, request, jsonify
import numpy as np
import pickle
import keras
import firebase_admin
from firebase_admin import firebase
app = Flask(__name__)
@app.route('/api/v1/identifysolat', methods=['POST'])
def identifySolat():
# get JSON from request. The JSON should be like this: { "data": [[[],... |
import django.dispatch
middlepeople_viewed = django.dispatch.Signal(
providing_args=["middlepeople", "request"])
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
import datetime
from article import models
# Create your views here.
def home(request):
posts = models.Article.objects.all()
return render(request, 'home.html', locals())
|
def make_sales_order(doc, handler=""):
se = frappe.new_doc("Sales Order")
for se_item in doc.items:
se.append("items", { "item_code":se_item.item_code, "item_group": se_item.item_group, "item_name":se_item.item_name, "amount":se_item.amount, "qty": se_item.qty , "uom":se_item.uom, "conversion_factor": s... |
from .fake_upnp_device import FakeDeviceDescriptor, FakeAsyncUpnpDevice
from .fake_upnp_service import UpnpServiceMock
from .connection_manager import FakeConnectionManagerService
from upnpavcontrol.core import didllite
from .format_didllite import format_didllite
didl_musictrack = """
<DIDL-Lite xmlns:dc="http://purl... |
# Generated by Django 2.2 on 2019-04-15 11:58
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),
]
opera... |
from sys import exit
from os import environ
from typing import List
from boucanpy.core import (
set_log_level,
make_logger,
set_log_format,
get_uvicorn_logging,
logger,
)
from boucanpy.core.security import create_bearer_token
from boucanpy.db.session import db_register, session
from boucanpy.db.uti... |
# Generated by Django 3.0 on 2019-12-15 18:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('order', '0018_auto_20191215_1834'),
]
operations = [
migrations.RemoveField(
model_name='report',
name='filename',
),
... |
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import random
from math import pi,cos,sin, trunc
import numpy as np
# Funcion que genera vectores de longitud l
def vectorL(l=0.75, d=1, rendijas=10):
x1,y1 = random.uniform(0,d*rendijas), random.uniform(0,d*rendijas)
tetha = ra... |
import zipfile
import io
import numpy as np
from tifffile import TiffFile
from pyspark import SparkContext, SparkConf
import hashlib
from scipy import linalg #linalg contains a method svd
#from skimage import data #from the “scikit-image” package
def getOrthoTif(zfBytes):
#given a zipfile as bytes (i.e. from reading... |
#####################
# NVIDIA GPU STUFF
#####################
import subprocess, re
import numpy as np
import argparse
# Nvidia-smi GPU memory parsing.
# Tested on nvidia-smi 370.23
def nvidia_smi(idx=None, args=None):
if idx is None and args is None:
return "nvidia-smi"
elif idx is None and not arg... |
#!/usr/bin/env python3
import logging
from jsonschema.exceptions import ValidationError
from validation.validators import (
endlines_validator,
format_validator,
run_validations,
schema_validator,
)
logging.basicConfig(level="INFO")
VALIDATIONS = {
"json": ("./ethereum/**/*.json", format_validato... |
import re
filename = 'time_tests.txt'
pattern = ''
lines = None
temp = []
with open(filename, 'r') as file:
lines = file.readlines()
file.close()
for line in lines:
line = line.strip()
if line.startswith('size'):
if '1024' in line:
line = line.replace('1024', '1KB')
elif '1... |
'''
*****************
Date: 2020-04-26
Author: Allen
*****************
'''
data_list = [1, 3, 5, 7, 9]
data_list_iterator = iter(data_list)
print(data_list_iterator)
value = next(data_list_iterator)
print("value1 = ", value)
#for i in range(5):
#value = next(data_list_iterator)
#print("value = ", value)
fro... |
def gridGame(grid, k, rules):
# Write your code here
a = 0
b = 0
magic = list()
for _ in rules:
if _ == 'alive':
magic.append(_)
g = 0
while g < grid_rows:
h = 0
count = 0
while h < grid_columns:
r = g - 1
wh... |
"""Beating the Bubble: Utilities
Alexandre Bucquet, Jesus Cervantes, Alex Kim
Python 2.7
This module defines common utility functions.
"""
import math, random
from collections import defaultdict
import numpy as np
import pandas as pd
# VECTOR FUNCTIONS -------------------------------------------------------------... |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
from rest_framework.parsers import MultiPartParser,FormParser
from rest_framework import permissions
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from rest_framework import generics,viewsets,filters,status
from rest_framework.serializers import Serializer
from rest_framew... |
import csv
import re
x = 0
def add():
first = input('First name: ')
last = input('Last name: ')
email = input('Email: ')
input_phone = input('Phone: ')
split_phone = list(input_phone)
phone_list = []
for x in split_phone:
if x in '1234567890':
phone_list.append(x)
phone = ''.join(phone_list)
key = fi... |
'''
Created on Feb 22, 2014
Retrieve the sentences from the Database after they have been clustered and
save them in the sentsXX.txt files.
@author: rojosewe
'''
import pickle
import pylab
import csv
import numpy as np
import MySQLdb as mdb
con = mdb.connect('localhost', 'root', 'hollywood1984', 'RNCToWork')
dataf... |
try:
import ujson
except ImportError:
import json as ujson
from utility_functions import data_dict_load
import pymongo
import os
import json
import shutil
import gzip
def write_keyed_json_file(base_directory, base_name, nth_file, file_batches_dict, query_results_dict, key_orders,
us... |
from pexpect import pxssh
import time
Found = False
def connect(host, user, password):
global Found
try:
s = pxssh.pxssh()
s.login(host, user, password)
print '[+] Password Found: ' + password
Found = True
except Exception, e:
if 'password refused' in str(e):
print "wrong : " + password
else:
pri... |
# Generated by Django 3.1 on 2020-08-28 08:36
from django.db import migrations, models
import membership.models
class Migration(migrations.Migration):
dependencies = [
('membership', '0014_auto_20200827_2137'),
]
operations = [
migrations.AlterField(
model_name='review',
... |
# Dependencies
from flask import Flask, request, jsonify
import traceback
import pandas as pd
import numpy as np
import string
from nltk.corpus import stopwords
import pickle
from flask_cors import CORS, cross_origin
import json
from scipy import sparse
from annoy import AnnoyIndex
# Your API definition
app = Flask(__... |
import random
from string import ascii_uppercase
from bottle import post, request
import re
import numpy as np
import Prima1
@post('/Prima', method='post')
def Start():
n = int (request.forms.get('GetValue'))
M = np.random.randint(0,2,(n,n))
np.fill_diagonal(M, 0)
m = np.tril(M) + np.tril(M,-1).T
fo... |
__author__ = 'andy17'
class GraphModel(object):
def __init__(self,name=None):
self.name = name
def logPrior(self,z):
pass
def getParams(self):
pass
import mars
import moon |
from django.shortcuts import render, redirect
from .models import Product, Cart, Slide
from django.contrib import messages
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
import json
from django.http import JsonResponse
# Create your views here.
def add_product(... |
# Time: O(1)
# Space: O(N)
class TicTacToe:
def __init__(self, n: int):
self.rows = [0] * n
self.cols = [0] * n
self.diagonal = 0
self.antidiagonal = 0
self.n = n
def move(self, row: int, col: int, player: int) -> int:
df = 1 if player == 1 else -1
self.... |
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, func, DateTime, delete
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy.orm import relationship
engine = create_engine("sqlite+pysqlite://", echo=True, future=True)
Base = declarative_base()
def print_classes():
... |
from direct.gui.DirectGui import DirectFrame, DirectLabel, DirectWaitBar
from panda3d.core import TextNode
from objects.defaultConfig.Consts import *
class PartyListUI ():
"""
A UI container element that appears to the top right, detailing
connected party members.
"""
def __init__ (self):... |
# 使用多个fixture
import pytest
@pytest.fixture()
def user():
print("获取用户名")
a = "yoyo"
return a
@pytest.fixture()
def psw():
print("获取密码")
b = "123456"
return b
def test_1(user, psw):
print("测试账号:%s, 密码:%s" % (user, psw))
assert user == "yoyo"
if __name__ == "__main__":
pytest.m... |
from transparentemail.services.Emails.editableEmail import EditableEmail
from transparentemail.services.Emails.email import Email
from transparentemail.services.serviceEmail import ServiceEmail
class OutlookCom(ServiceEmail):
def get_primary_email(self, email: Email) -> Email:
return (
Editab... |
"""
This file if for manupulation of denchar out files:
We really dont need this since VESTA can visualize cube files which denchar can write
Since finding that out I have to eddited this document and will load denchar files straight into VESTA
"""
def condition_data(*args, **kwargs):
import glob,os
fi... |
import os
import cv2
from opts import opts
from datasets.dataset_factory import dataset_factory
from detectors.detector_factory import detector_factory
MODEL_PATH = '/home/yuqingz/autonomous_driving/exploration/img_ctnet/CenterNet/models/ddd_3dop.pth'
TASK = 'ddd'
EXP_ID = 'waymo2kitti'
DATASET = 'kitti'
CLASS_NAME = ... |
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.array([2,9,5,5,3,7,1,8,6,2]).reshape((-1, 1))
y = np.array([69,98,82,77,71,84,55,94,84,64])
model = LinearRegression().fit(x, y)
'''
You can obtain the coefficient of determination (𝑅²) with .score() called on model:
'''
r_sq = model.score... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. codeauthor:: Cédric Dumay <cedric.dumay@gmail.com>
"""
from typing import AnyStr, Optional, Any, Dict
import jaeger_client
import opentracing
import six
from jaeger_client import SpanContext
from jaeger_client.constants import SAMPLED_FLAG, DEBUG_FLAG
from jaeger... |
def solution(n):
ans = []
for i in range(n):
tmp = i*2+1
if tmp > n:
break
ans.append(tmp)
return ans |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Candidate',
fields=[
('id', models.AutoField(au... |
import psycopg2
from db_personal import *
from temp_objects import *
from getpass import getpass
"""
passw = getpass("Please enter the password for your postgres account:")
movie1 = tempMovie("The Lion King", None, None, None, "1994", 95, "PG", 6.0, True, False)
person = tempPerson("Matthew Broderick", "actor")
... |
#! /usr/bin/env python
import sys
import os
import string
import getopt
import copy
import math
if "FIASCO" in os.environ:
sys.path.append(os.environ["FIASCO"])
from fiasco_utils import *
#################
#
# Main
#
#################
# Check for "-help"
if len(sys.argv)>1:
if sys.argv[1] == "-help":
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from sure import expect
import httpretty
import re
import tests
import gerrit_ldap_sync
from gerrit_ldap_sync import config
httpretty.HTTPretty.allow_net_connect = False
@httpretty.activate
def test_dry_run():
# config.debu... |
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from config import config
from flask_admin import Admin
from flask_login import LoginManager
bootstrap = Bootstrap()
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
def creat... |
#!/user/bin/even Python3
# -*- coding:utf-8 -*-
# __init__.py.py
#
# author:zhaohexin
# time:2020/1/8 10:12 下午 |
from app import db, bot
from app.models import User, MainMenuItems
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from app.telegram_bot import texts
from app import Config
from telegram import ParseMode
import json
import math
import dialogflow_v2 as dialogflow
def command_start(update, context):
... |
a=input("ingrese 2 numeros separados por un espacio "+'\n').split(" ")
suma= int(a[0]) + int(a[1] )
print("La suma de los numeros es "+'\n', suma)
|
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
import gluttony
setup(
name='Gluttony',
version=gluttony.__version__,
description= "A tool for find dependencies rela... |
from loguru import logger
import pytest
# Базовые проверки на то, что все сервисы отвечают
@pytest.mark.asyncio
async def test_film(make_get_request):
logger.info('test for film api alive')
response = await make_get_request('film')
assert response.status == 200
assert len(response.body) == 50
log... |
__title__ = 'yahoo_weather'
__description__ = 'Python library for yahoo weather new API'
__url__ = 'https://github.com/M-Ahadi/yahoo_weather'
__version__ = '1.0.8'
__author__ = 'Mojtaba Ahadi'
__author_email__ = 'm.ahadi@outlook.com'
__license__ = 'Apache 2.0' |
def sort(arr, start, end):
center = 0
if(start < end):
center = (start + end) // 2
sort(arr, start, center)
sort(arr, center+1, end)
else: return
temp = []
i, j = start, center+1
# add small item to temp arr
while(i<=center and j<=end):
if(arr[i] <= arr[j]):
temp.append(arr[i])
... |
from yacs.config import CfgNode as CN
_C = CN()
## Battle tensor options
_C.BATTLE = CN()
# move options
_C.BATTLE.MOVE = CN()
_C.BATTLE.MOVE.ACCURACY = True
_C.BATTLE.MOVE.BASE_POWER = True
_C.BATTLE.MOVE.MOVE_MULT = True
_C.BATTLE.MOVE.PP = True
_C.BATTLE.MOVE.PRIORITY = True
_C.BATTLE.MOVE.CAT = True
_C.BATTLE.MOVE... |
import numpy as np
from sklearn import preprocessing
import itertools
import cPickle
from sklearn.svm import SVC
import performance_metrics
from sklearn.model_selection import train_test_split
import matplotlib
from pandas import DataFrame
from matplotlib import pyplot
from PIL import Image
X=[]
Y=[]
def SVM(x_train... |
n = [1]
k = [1]
while True:
N, K = map(int, input().split())
if N == 0 and K == 0:
break
elif N == 0 or K > N:
break
else:
n.append(N)
k.append(K)
del n[0]
del k[0]
result = []
for i in range(len(n)):
num = n[i]
den = min(k[i],n[i]-k[i])
d = den
p = 1
... |
import argparse
import os
import time
import numpy as np
import torch
import torch.nn.functional
import torch.optim as optim
import torch.utils.data
from torch.optim.lr_scheduler import StepLR
from torchvision import transforms
from dataset import BarcodeDataset
from evaluator import Evaluator
from model import Mode... |
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
sim_matrix = np.random.rand(4,4)
G=nx.Graph()
for i in range(0,4):
for j in range(i+1,4):
G.add_edge(i,j,weight=sim_matrix[i][j])
'''
#加入带权边
G.add_edge(1,2,weight=0.6)
G.add_edge(1,3,weight=0.2)
G.add_edge(3,4,weight=0.1)
G.add_edge(... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 22:26:18 2020
@author: verni
"""
''' Program to reverse a string'''
input_str = input("Enter string to reverse: ")
print(input_str[::-1])
|
import time
import board
import busio
import adafruit_mpu6050
import json
import socket
import signal
import sys
from queue import Queue
i2c = busio.I2C(board.SCL, board.SDA)
mpu = adafruit_mpu6050.MPU6050(i2c)
while mpu.acceleration:
print(mpu.acceleration)
time.sleep(0.1) |
from django.db import models
# Create your models here.
class Csv(models.Model):
file_name = models.FileField(upload_to='csvs/',max_length=100)
uploaded =models.DateField(auto_now_add=True)
activated = models.BooleanField(default=False)
def __str__(self):
return "File id: {}".format(self.id) |
#!/usr/bin/env python3
import pytest
from codoc.domain.model import Graph, Node, Dependency, NodeType
import examples as exampleModule
@pytest.fixture
def create_graph():
def _func(**kwargs):
kwargs.setdefault("nodes", [])
kwargs.setdefault("edges", [])
return Graph(**kwargs)
return ... |
import re
from colorama import Fore, Back
from django.contrib.auth.models import Permission
from icecream import ic
from Functions.make_fields_permissions import make_fields_permissions
def convert_to_list(django_boject):
flat_object = django_boject.values_list('codename', flat=True)
return list(flat_object... |
from rest_framework import viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
class DataApi(APIView):
def __init__(self):
self.result = ""
def get(self, request, **args):
return Response(data = "Hello, Django is working")
|
# Generated by Django 2.1.3 on 2019-02-13 14:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ARNN', '0004_auto_20190211_1134'),
]
operations = [
migrations.AlterField(
model_name='network',
name='last_accessed... |
import json
import logging
import random
from celery import Celery
from flask import Flask, request, jsonify
from gtbaas.gt_tool import GtTool
from gtbaas.server.daemon import Daemon
app = Flask(__name__)
tool = GtTool()
log = logging.getLogger(__name__)
app.config.update(
CELERY_BROKER_URL='redis://localhost:... |
from django.db import models
from django.utils import timezone
class Player(models.Model):
player = models.ForeignKey('auth.User', on_delete=models.CASCADE)
name = models.CharField(max_length=10)
def register(self):
self.save()
def __str__(self):
return self.name |
# File: Graph.py
# Description: Functions with a Graph of the USA
# Student's Name: Derek Wu
# Student's UT EID: dw29924
# Partner's Name: Victor Li
# Partner's UT EID: vql83
# Course Name: CS 313E
# Unique Number: 50205
# Date Created: 25 November, 2019
# Date Last Modified: 25 November, 2019
clas... |
from unittest import TestCase
from mock import Mock, patch, call
from omnium.run_control import Task, TaskMaster
from omnium.setup_logging import setup_logger
class TestTask(TestCase):
def test_task_init(self):
t0 = Task(0, 'S0', None, 'cycle', 'analysis', 'cloud_analysis',
['atmos.pp1... |
import uuid
from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qs
class Handler(BaseHTTPRequestHandler):
# noinspection PyPep8Naming
def do_GET(self):
query_params = parse_qs(self.path[2:])
code = query_params['code'][0]
state = uuid.UUID(query_params['state'... |
# Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
import math
v0 = float(input("velocidade inicial: "))
a = math.radians(float(input('angulo: ')))
D = float(input('distancia: '))
g = 9.8
R = ((math.pow(v0, 2)*mat... |
import sys
import random
from numpy import array
from math import ceil
try:
import pygame
pygame.mixer.pre_init(buffer=32)
pygame.init()
except:
print("\n! ERROR !\nFant ikke pygame-modulen.\n"
+ "Hvordan installere pygame:\n\n"
+ "WINDOWS: pip install pygame\n"
+ " MAC: pip... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32 # Messages used in the node must be imported.
'''
"my_callback" is the callback method of the subscriber. Argument "msg" contains the published data.
'''
def my_callback(msg):
rospy.loginfo("received data from topic_py: %d", msg.data)
rospy.init_node... |
import logging
from config import Config as cfg
logging.basicConfig(format='%(levelname)s:%(message)s', level=cfg.logging_level)
class Hand:
def __init__(self):
self.cards = []
def __getitem__(self, item):
return self.cards[item]
def __len__(self):
return len(self.cards)
de... |
'''
Дана последовательность N целых положительных чисел.
Рассматриваются все пары элементов последовательности,
разность которых чётна, и в этих парах, по крайней мере,
одно из чисел пары делится на 17. Порядок элементов в паре неважен.
Среди всех таких пар нужно найти и вывести пару с
максимальной суммой элементов. Ес... |
print('from ch30_streams import Processor')
from ch30_streams import Processor
print()
print('class Uppercase(Processor)')
class Uppercase(Processor):
def converter(self, data):
#print('Uppercase.converter, data =', data)
return data.upper()
print()
print('class c_html_write')
class c_html_write:
... |
# -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
from unittest.mock import patch
import pytest
from foglamp.services.core.service_registry.service_registry import ServiceRegistry
from foglamp.services.core.service_registry.exceptions import DoesNotExist
from foglamp.service... |
from flask import Flask,render_template,request,redirect,url_for
from werkzeug.utils import secure_filename
import os
import cv2
import random
import sys
import json
import shutil
import time
from codecs import open
from threading import Lock
def randColor():
rc = random.randint(20, 150)
gc = random.randint(20... |
from toolbox.aoc.days2019 import day01
def test_uppercase():
assert "loud noises".upper() == "LOUD NOISES"
def test_reversed():
assert list(reversed([1, 2, 3, 4])) == [4, 3, 2, 1]
def test_get_fuel_required():
"""For example:
For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-08-26 10:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orgs', '0003_auto_20180825_1721'),
]
operations = [
migrations.AlterField(
... |
from socket import *
import sys
HOST = 'localhost'
PORT = 2000
Addr = (HOST, PORT)
clientSocket = socket(AF_INET, SOCK_STREAM)
try:
clientSocket.connect(Addr)
except Exception as err:
print ("Can not Connect to (%s:%s)" % Addr)
sys.exit()
print("Success connect to (%s:%s)" % Addr)
def prompt():
sys.stdout.w... |
#Beakjoon_14891_톱니바퀴
#https://www.acmicpc.net/problem/14891
#회전 함수
def rotate(num,dir) :
global gear
lst=gear[num]
if dir==-1 :
temp=lst[0]
lst=lst[1:]
lst.append(temp)
return lst
else :
temp = lst[-1]
lst = lst[:-1]
lst.insert(0,temp)
ret... |
# Lab Number: 2
# Program Inputs: Births per second (float), deaths per second (float), migration per second (float),
# Program Inputs (2): Current population (integer), number of years in future (float)
# Program Outputs: Estimated population (integer)
# This block asks the user for the three inputs that change popul... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 4 14:09:35 2019
@author: gaurava
"""
import configparser
import logging
import os
from uuid import uuid4
from flask import Flask, request
from flask.logging import default_handler
from blockchain import *
from consensus import *
os.system("clea... |
#!/usr/bin/env python
# coding: utf-8
%matplotlib inline
# In[12]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
import seaborn as sns
# # WEEK 1
Data Exploration:
1. Perform descriptive analysis. Understand the variables and their corresponding values. On ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from engine.engine_utils.common import *
from engine.logger import scanLogger as logger
def run_domain(http, ob):
'''
Rejetto HTTP File Server‘ParserLib.pas’代码注入漏洞
CVE-2014-6287
CNNVD-201409-986
此插件仅通过响应header的server字段判断是否存在低版本HFS
HFS(HTTP File Server)... |
import prospect.io.read_results as bread
import matplotlib.pyplot as plt
import numpy as np
from prospect.models import model_setup
from prospect.io import write_results
from prospect import fitting
from prospect.likelihood import lnlike_spec, lnlike_phot, write_log
import sys
import argparse
import pickle
import os
im... |
from z3 import *
def add_def(s, fml):
name = Bool("%s" % fml)
s.add(name == fml)
return name
def relax_core(s, core, Fs):
prefix = BoolVal(True)
Fs -= { f for f in core }
for i in range(len(core)-1):
prefix = add_def(s, And(core[i], prefix))
Fs |= { add_def(s, Or(prefix, core[i... |
# 演算法分析機測
# 學號 10727124 10727125 10727155
# 姓名 劉宇廷 石慕評 曾博暉
# 中原大學資訊工程學系
import sys
import math
import random
from fractions import Fraction
def Cal( num, n1, n2 ):
if num == 1:
answer = n1 + n2
elif num == 2:
answer = n1 - n2
elif num == 3:
answer = n1 * n2
else:
if n2 == 0:
... |
from collections import deque
n = int(input())
l = list(map(int, input().split()))
m = int(input())
q = deque()
for i in range(m):
while q and l[i] >= l[q[-1]]:
q.pop()
q.append(i)
for i in range(m, n):
print(l[q[0]], end=' ')
while q and q[0] <= i - m:
q.popleft()
while q and l[i] ... |
#! /usr/bin/python
import sqlite3
import sys
conn = sqlite3.connect('baza.db')
c = conn.cursor()
c.execute("CREATE TABLE yt (url text)")
conn.commit()
conn.close()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 17 16:33:42 2018
@author: admin558
"""
a=b'1' #byte类型
print(a)
import urllib.request as r #导入联网工具包, 打开网址,读取内容转换为str
data=r.urlopen('http://api.openweathermap.org/data/2.5/weather?q=chongqing&mode=json&units=metric&lang=zh_cn&APPID=6a67ed641c0fda8b69715c43518b6996').rea... |
import numpy as np
def GetData(datapath):
Dist = np.zeros((10, 10))
with open("a.txt") as file:
data = np.array(file.read().split())
count = 0
# print(len(data))
print(data)
for i in range(10):
for j in range(10):
if data[count] == '0':
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 03:54:38 2018
@author: 宮本来夏
"""
import numpy as np
import tensorflow as tf
def mnist_double(batch_y,task):#mnistを二値分類に帰着
n = len(batch_y)
y_new = [[0 for j in range(1)] for i in range(n)]
if task == "OrS":
for i in range(n):
... |
i_user = "whoisthebest"
i_pass = "anthonyisthebest"
new_user = input("Username:\n")
new_pass = input("Password:\n")
l = 0
while new_user == i_user and new_pass == i_pass:
print("You're the best!")
stop = input("No more looping\n")
while new_user != i_user and new_pass != i_pass and l < 3:
new_user = input... |
"""
misleading_gradient_contours
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Plots the contours of the function from misleading_gradient.py"""
#### Libraries
# Third party libraries
import matplotlib.pyplot as plt
import numpy
X = numpy.arange(-1, 1, 0.02)
Y = numpy.arange(-1, 1, 0.02)
X, Y = numpy.meshgrid(X, Y)
Z =... |
import os
import config
from base import *
class Tpl(Base):
def __init__(self):
self.name = "tpl"
self.version = "git"
self.compilers = [config.COMPILER_MAC_GCC, config.COMPILER_MAC_CLANG, config.COMPILER_WIN_MSVC2010, config.COMPILER_UNIX_GCC]
self.arch = [config.ARCH_M32, con... |
#!/usr/bin/env python2
import fresh_tomatoes
import tmdbsimple
import media
# After creating an account at themoviedatabase.org, you can add your API
# Key below
tmdbsimple.API_KEY = ""
def get_movie_info(ids):
""" Takes the ids of each movie and fetches data from
themoviedatabase.org
"""
for x in r... |
'''
Created on Jan 16, 2018
@author: tvandrun
'''
def mat_find1(M, x):
i = 0
found = False
while not found and i < len(M):
j = 0
while not found and j < len(M[i]) :
found = M[i][j] == x
j += 1
i += 1
if found :
return (i-1, j-1)
else :
... |
import datetime
import arr as randomList
now = datetime.datetime.now()
def selectionSort(sortList) :
if len(sortList) < 2 :
return sortList
# 找出数组中最小值,将其放到第一位
# 找出数组第二小的值,将其放到第二位
for i in range(len(sortList) - 1) :
smallest = sortList[i]
location = i
for j in range(i, ... |
# -*- coding: utf-8 -*-
# Copyright 2018 ICON Foundation 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 ... |
dictionary = {}
def main():
with open("text.txt") as file_object:
contents = file_object.read()
words = contents.split()
num_words = len(words)
for word in words[:]:
if word not in dictionary:
dictionary[word] = words.count(word)
# total = dictionary.get(wo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.