text stringlengths 8 6.05M |
|---|
import sys
import os
dir_path = str(os.path.dirname(os.path.realpath(__file__)))
dir_path = dir_path[:-7]
print(dir_path)
sys.path.insert(0, dir_path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'FAM.settings'
from django.conf import settings
import django
django.setup()
from sources.models import StockExchange, C... |
import cv2
from cnn.cnn_mult import *
import pickle
import os
from torch.utils.data import Dataset
import torchvision.transforms as transforms
import numpy.ma as ma
import numpy as np
from image_utils import (EnhancedCompose, Merge, RandomCropNumpy, Split, to_tensor,
BilinearResize, CenterCropN... |
number = 23
flag = 1
while flag == 1:
guess = int(raw_input('Enter a number:'))
if guess == number:
print 'Congrats on your success!'
flag = 0
elif guess < number:
print 'Ops, it is a little bit higher.'
else:
print 'Ops, it is a little bit smaller.'
print 'Done.' |
from selenium import webdriver
from time import sleep
# import xlrd
import random
import os
import time
import sys
sys.path.append("..")
# import email_imap as imap
# import json
import re
# from urllib import request, parse
from selenium.webdriver.support.ui import Select
# import base64
import Chrome_driver
import em... |
#!/usr/bin/env python2
# vim: set fileencoding=utf8
import base64
import requests
import time
import os
import sys
import argparse
import random
from HTMLParser import HTMLParser
import select
from urllib2 import *
s = '\x1b[%d;%dm%s\x1b[0m' # terminual color template
parser = HTMLParser()
##################... |
# Copyright 2020 Open Source Robotics 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 law... |
#!/usr/bin/env python3
import os
exe_set = set()
for pid in os.listdir('/proc'):
if pid[0].isdecimal() is False:
continue
try:
rp = os.path.realpath('/proc/{}/exe'.format(pid))
except Exception as e:
pass
exe_set.add(rp)
list_d = list(exe_set)
list_d.sort()
for rp in list_d... |
class Process(object):
last_scheduled_time = 0
def __init__(self, id, arrive_time, burst_time):
self.id = id
self.arrive_time = arrive_time
self.burst_time = burst_time
def __repr__(self):
return ('[id %d : arrive_time %d, burst_time %d]' %
(self.id, self.... |
def get_smiles(path_to_file: str) -> set():
"""
Функция построчно считывает файл и записывает из него все смайлики.
Возвращает набор уникальных элементов (множество)
:param path_to_file: str
:return: set()
"""
smiles_set = set()
with open(path_to_file, encoding="cp1251") as file:
... |
from .bot_review import * # noqa
from .human_review import * # noqa
|
'''
Created on Dec 8, 2015
@author: Xu Xu
'''
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import patches
#generate the grade of restaurant in nyc
def grades_of_nyc_by_year(data):
totaldata=data.groupby(['year','grade']).size().unstack()
pd.DataFrame(totaldata).plot(kind='bar')
plt.... |
"""
Tools for satellite related calculations
"""
import math
import ephem
from catalog.models import TLE
class SatelliteComputation(object):
"""
Tools for satellite related computation
"""
G = 6.67408e-11
EARTH_MASS = 5.98e24
def __init__(self, **kwargs):
self.observer = e... |
# Goal: Make an implementation of the sed command
# v1: Just work with the input stream:
# ls -l | sed "s/jamesbryant/cynicalneon/"
# - find the specified string and replace with static string
# v2: Use sed formatting to replace the string
# v3: Use Sed formatting.
import argparse
import glob
import os
im... |
"""
将 VOC XML 转换为 COCO JSON
@Author: patrickcty
@filename: det_xml2json.py
"""
import os
import json
from xml.etree.ElementTree import parse
def convert_binary_to_coco(xml_file_dir, out_file, all_xmls=None, cls_name='zawu'):
"""
将给定文件夹下的 xml 文件转换为一个 json 文件,类别标签视为二分类
Parameters
----------
xml... |
#!/usr/bin/env python3
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Javascript client side code opens EventSource on the browser
body = """<html><body><h1>Streaming baby!</h1>
<ul id="events">
... |
import threading
import numpy
import pyaudio
import struct
import random
from datetime import datetime as dt
import time
import math
MAX_SOUNDTYPE = 3
#指定周波数でサイン波を生成する
def genewave(frequency, length, rate,type):
length = int(length * rate)
factor = float(frequency) * (math.pi * 2) / rate
if type == 0:
... |
class colors:
RED = '\x1b[0;31;1m'
GREEN = '\x1b[0;32;1m'
YELLOW = '\x1b[0;33;1m'
BLUE = '\x1b[0;34;1m'
PURPLE = '\x1b[0;35;1m'
END = '\033[0m' |
from os import system
system("pip install --upgrade matplotlib")
|
# endi tuple xaqida tuplening listdan farqi buning elemetnlarini o'zgartirib bo'lmaydi lisdagi kabi
numbers=(1,2,3,4)
#numbers[0]=12
print(numbers)
coordinates=(1,2,3)
x,y,z=coordinates # bu degani shu tuple elementlarini shu xarflarga ta'minla degani buni listda xam ishlatsak bir xilda ishlaydi
print(x)
print(y)
prin... |
import socket
HOST_IP="127.0.0.1"
HOST_PORT = 54831
HOST_PORT_RECEIVE = 58927
DEST_IP_ADDRESS = "127.0.0.1"
DEST_PORT_NO = 58913
BUFSIZE = 4096
buffer_to_send='I am client'
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receiveSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSock.bind((HOS... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
from web_backend.nvlserver.module import nvl_meta
from sqlalchemy import BigInteger, String, Column, Boolean, DateTime, Table, ForeignKey, func
from sqlalchemy.dialects.postgresql import JSONB
location_type = Table(
'location_type',
nvl_me... |
#!/usr/bin/env python
import katcp_wrapper
import time, struct, socket
#bitstream = 'pkt_p2s_2015_May_08_1620.bof.gz'
bitstream = 'pkt_32_to_8_2017_Nov_08_1625.bof.gz'
roach = 'r1511'
katcp_port = 7147
mac_base = (2<<40) + (2<<32)
fabric_ip_string = '10.32.127.88'
fabric_ip = struct.unpack('!L',socket.inet_aton(fa... |
import SimpleITK as sitk
import pandas as pd
import quandl, math
import numpy as np
from sklearn import preprocessing, svm
from sklearn.model_selection._validation import cross_validate
from sklearn.linear_model import LinearRegression
from sklearn.metrics import jaccard_similarity_score
from sklearn.metrics import con... |
from sys import argv #import com-line input
from os.path import exists #import exists() method
script, copying_file, empty_file = argv #assign vars to argv
print "Copying from %s to %s" % (copying_file, empty_file) #print statement
indata = open(copying_file).read() #var = open first, then read or write
print "The ... |
#!/usr/bin/env python
# date: 2017/11/24 v1.0 # date: 2018/2/9 v2.0
# author: zss
### Input All transcripts.gtf list file
### Output Five type Count "*_Alternative_summary.txt"
import sys,commands,os
def CountAstala(GTF_astalavista):
Sample = "CK"
Dict = {}
Type1 = 0
Type2 = 0
Type3 = 0
... |
from board2 import *
from minmax import *
from eval import *
b = Board().withSize(size=5)
evaluator = Pipeline(
(MFlatCoverage(), 1.0),
(MDjikstraDistance(), 4.0)
)
print (evaluator)
ai = Minmax(evaluator)
while True:
score, (type, args) = ai(b)
b = b.apply_move(type, *args)
print(b)
if b.get_winner() != 0:
... |
import random
import time
space = "--------------------------------------------------------\n"
values = ('sasso', 'carta', 'forbici')
while True:
player = input("\nInserire Sasso Carta o Forbici\n").lower().strip()
pc = random.choice(values)
time.sleep(1)
if player in values:
if player == "sasso"\
and pc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 23 16:33:04 2021
@author: Guoxin Sun
Paper: "Strategic mitigation against wireless attacks onautonomous platoons"
It is a numerical example of the proposed security game based mitigation framework.
Please refer to the paper for detailed explanat... |
from doh.private import CRISISNET_APIKEY
import json
import requests
def query_crisis(endpoint, **custom_params):
params = {'apikey': CRISISNET_APIKEY}
params.update(custom_params)
baseurl = 'http://api.crisis.net/'
fullurl = baseurl + endpoint
r = requests.get(fullurl, params=params)
return r... |
class adecide:
def decide(self,na,nd):
if nd>15:
self.x=0
elif nd<10 and na>15:
self.x=1
elif na>6 and na>(2*nd):
self.x=0
else:
self.x=0
return self.x
def win(self,nd):
if nd>0:
self.victory=0
else:
self.victory=1
return self.victory
def cont(self,na,nd):
self.t=adecide(... |
import cv2 as cv
def hi():
hybrid1 = cv.imread("hybrid1.jpg", cv.IMREAD_GRAYSCALE)
hybrid2 = cv.imread("hybrid2.jpg", cv.IMREAD_GRAYSCALE)
h1_low_pass = cv.GaussianBlur(hybrid1, (3, 3), 0)
h2_low_pass = cv.GaussianBlur(hybrid2, (5, 5), 0)
h2_high_pass = hybrid2 - h2_low_pass
hybrid = h2_high_p... |
# Solve with breadthfirst search |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from head import *
from django_frame_solution import DjangoFrameSolution
class DjangoFrameMain():
"""
此类负责处理每个连接实例,包括收发包,解析等操作
"""
def __init__(self, client):
self.client = client
self.fileno = client.fileno()
def main_receivor(self, ):... |
#!/usr/bin/env python
import psycopg2
conn = psycopg2.connect(database="hpc", user="hpc", password="123456", host="localhost", port="5432")
print "Open database successfully"
cursor = conn.cursor()
cursor.execute("delete from rank_toponehundred;")
conn.commit()
conn.close()
|
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.core.util_rules.system_binaries import OpenBinary
from pants.engine.environment import EnvironmentName
fro... |
# -*- coding:utf-8 -*-
from fraction import Fraction
def solve_it(a, b): # ax + b = 0
if a != 0:
return -b / a
elif b != 0:
return "No solution"
else:
return "Any number"
if __name__ == '__main__':
print(solve_it(Fraction(0, 2), Fraction(0, 4)))
|
import unittest
from katas.kyu_6.reverse_or_rotate import revrot
class ReverseOrRotateTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(revrot('123456987654', 6), '234561876549')
def test_equals_2(self):
self.assertEqual(revrot('123456987653', 6), '234561356789')
def ... |
import sqlite3,csv
from sqlite3 import Error
import os
FILE = "movies.db"
MOVIES_TABLE = "Movies"
class Movies:
def __init__(self):
self.conn = None
try:
self.conn = sqlite3.connect(FILE)
except Error as e:
print(e)
self.cursor = self.conn.cursor()
... |
# Odd numbers in range
for i in range(1, 21):
if i % 2 != 0:
print("The odd number is {}".format(i))
|
import sublime, sublime_plugin
class PrintCodeCommand(sublime_plugin.WindowCommand):
def run(self):
syntax = self.window.active_view().settings().get('syntax')
allString = self.window.active_view().substr(sublime.Region(0, self.window.active_view().size()))
newFile = self.window.new_f... |
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
import psycopg2
import os
SQLALCHEMY_DATABASE_URI = "postgresql+psycopg2://w205:MIDS@localhost/postgres"
e = create_engine(SQLALCHEMY_DATABASE_URI)
app = Flask(__name__)
api = Api(app)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'Click>=6.0',
'Cerberus==1.0.1',
'lxml',
]
test_requirements = ... |
import logging
logging.basicConfig(format='%(asctime)s %(name)s %(filename)s@%(lineno)d %(levelname)s %(message)s', level=logging.INFO)
log = logging.getLogger('speed-cam')
|
# -*- coding: utf-8 -*-
from collections import Counter
class Solution:
def numFriendRequests(self, ages):
result = 0
counts = Counter(ages)
for age1, count1 in counts.items():
for age2, count2 in counts.items():
if age1 // 2 + 7 < age2 <= age1:
... |
from django.db import models
from geopy.geocoders import Nominatim
def location():
geolocator = Nominatim(user_agent="https://ba531876.ngrok.io")
loc = geolocator.geocode("5 Shaaban Robert St, Dar es Salaam")
class Organizer(models.Model):
name = models.CharField(max_length=255,null=False,blank=False)
... |
import pandas as pd
import csv
import plotly.express as px
df=pd.read_csv("data.csv")
mean=df.groupby(["student_id","level"],as_index=False)["attempt"].mean()
fig=px.scatter(mean,x="student_id",y="level",size="attempt",color="attempt")
fig.show() |
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import errno
import logging
import os
import sys
import psutil
from fasteners import InterProcessLock
from pants.util.dirutil import safe_delete
logger = logging.getLogger(__name__)
d... |
def is_valid(x, y):
if (0 <= x < 8) and (0 <= y < 8):
return True
return False
def minimum_steps(start_x, start_y, target_x, target_y):
q = []
arr_x = [-2, -1, 1, 2, 2, 1, -1, -2]
arr_y = [1, 2, 2, 1, -1, -2, -2, -1]
rows = 8
column = 8
arr = [[-1 for i in range(column)] for j ... |
# this script is used to create new dataset with entities and positions
import json
from data_loader import remove_invalid_token, remove_return_sym, lower_case
from tqdm import tqdm
fewrel_train_file = './dataset/fewrel/train_wiki.json'
fewrel_valid_file = './dataset/fewrel/val_wiki.json'
fewrel_relation_file = './dat... |
if __name__ == '__main__':
s = input()
alphanumeric =False
alphabetical= False
digits = False
lowercase = False
uppercase= False
for letter in s :
alphanumeric =alphanumeric or letter.isalnum()
alphabetical= alphabetical or letter.isalpha()
digits = digits or letter.isdigit()
lowercase = ... |
aa,bb=list(map(int,input().split()))
ll=list(map(int,input().split()))
for i in range(bb):
q,s=list(map(int,input().split()))
print(min(ll[q-1:s]))
|
from Sieve_of_Eratosthenes import *
from Miller_Test import *
# list of primes till 100
primes = sieve_of_eratosthenes(100)
for p in primes:
if miller_test(p, 50):
print(f'{p} is prime')
else:
print(f'{p} is composite')
|
import aStarHelperFunctions
'''
* Function Name: a_star_search() --> Performs A* path finding for the passed nodes
* Input: (startNode, goalNode, traversable_nodes, current_dir) -->
* Start of the path, Goal of the path, List of passable(traversable) nodes and current facing direction
* Output: -1 if no path i... |
import os
from fabric.api import sudo
from fabtools import files
def upload_template(p, dest, ctx, mode='644'):
files.upload_template(
p.name,
dest,
ctx,
use_jinja=True,
template_dir=str(p.parent),
use_sudo=True,
mode=mode,
backup=False,
cho... |
import numpy
import json
import cv2
import numpy as np
import os
import scipy.misc as misc
# Add Ignore to vessel
#############################################################################################
def show(Im):
cv2.imshow("show",Im.astype(np.uint8))
cv2.waitKey()
cv2.destroyAllWindows(... |
# Modifications Copyright 2016-2017 Reddit, Inc.
#
# Copyright 2013-2016 DataStax, 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
#
# Unle... |
__author__ = 'apple'
## Get Shapefile Fields - Get the user defined fields
from osgeo import ogr
daShapefile = r"ne1.shp"
dataSource = ogr.Open(daShapefile)
daLayer = dataSource.GetLayer(0)
layerDefinition = daLayer.GetLayerDefn()
for i in range(layerDefinition.GetFieldCount()):
print layerDefinition.GetField... |
import pandas as pd
from main import get_data,get_commu_info,headers
from lxml import etree
import re
from get_commu_list_lianjia import get_commu_ls_page
# 安居客根据更细致的细分区域获取更完整的小区列表
# 获取浦东的板块名称列表
def get_bankuai_info(url):
"""拿到一个区的url,获取这个区的细分板块名称和url"""
res_elements, _ = get_data(url, headers)
urls = ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import discord
import json
from DrinkShop import runLoki
with open("account.info", encoding="UTF-8") as f:
accountDICT = json.loads(f.read())
class BotClient(discord.Client):
async def on_ready(self):
print('Logged on as {} with id {}'.format(self.user, sel... |
#!/usr/bin/env python3
import wpilib as w
from time import sleep
class Sparky(w.IterativeRobot):
def robotInit(self):
# Motors to PWM channels
l_motor = w.Talon(0)
r_motor = w.Talon(1)
self.lift_motor = w.VictorSP(2)
# Drivetrain control
self.drivetrain = w.Robot... |
from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QPainter, QPen, QBrush
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QTimer
import random
import Object
import Physik
class Game(QWidget):
def __init__(self, UI, number_of_objects):
super().__init__()
self.title = "Game"
se... |
# Generated by Django 3.0.1 on 2019-12-29 07:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DistributorInfo',
fields=[... |
import psycopg2
from api.constants import POSTGRES_ADAPTER
def connect_to_postgres(host, port, username, password, db_name, **kwargs):
try:
conn = psycopg2.connect(
host=host, user=username, password=password, dbname=db_name, port=port
)
except Exception as e:
print(str(e)... |
'''
This function calculates Fibonocci number at nth place using Dynamic Programming
'''
fibHash = {}
def fibDP(n):
if n == 1:
return 1
if n == 0:
return 0
if n in fibHash:
print "resued"
return fibHash[n]
# store the computed value in Hash table
# Memoization
fibHash[n-1] = fibDP(n-1)... |
import glob
import os
import unittest
import tempfile
import pytouch
if __name__ == '__main__':
class BaseDirectoryPathTest(unittest.TestCase):
def test_base_path(self):
name = 'test usr/local'
base_path = '/usr/local'
bp = pytouch.BaseDirectoryPath(name=name,
... |
'''
zip(*strs) : 星号用来将列表分离成一个个元素,zip()将所有可遍历参数对应的位置的元素组合成元组。如zip([1,2],[2,3],[3,4]) = (1,2,3),(2,3,4)
长度由最短的元素的长度决定. enumerate()将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列。enumerate(zip([1,2],[2,3],[3,4]))=
0 (1, 2, 3)
1 (2, 3, 4)
这里就将每个单词的相同位置的字母取出组成元组,然后set()来判断是否是相同的
'''
class Solution:
# @return a string
def longestCo... |
import csv
from collections import namedtuple
from datetime import datetime
from typing import Tuple
class DataPoint(namedtuple('DataPoint', ['date', 'value'])):
__slots__ = ()
def __le__(self, other):
return self.value <= other.value
def __lt__(self, other):
return self.value < other.va... |
#判断用户登录
#先定义数据库里的用户名密码
uid = "admin123"
password = "123456"
#再输入用户名密码
username = input("输入用户名:")
passwd = input("输入密码:")
if username != "" and passwd != "":
if username == uid and passwd == password:
print("登陆成功!")
else:
print("用户名或密码错误!")
else:
print("用户名或密码不能为空!")
|
import pandas as pd
import os
import sys
import csv
from datetime import datetime
import getopt
import argparse
class DataSampler:
def __init__(self, tweets_dataset_path: str, sample_n: int,
random_state: int, text_col: str, annotator_name: str,
save_taken: bool, out_folder: str... |
import numpy as np
import matplotlib.pyplot as plt
# this function plots the graph for mistakes as a function of number if instances
# use matplotlib to plot the graphs. This function plotts two graphs one for
# number of attributes =500 and when number of attributes=1000
def readAndPlot():
getPlotFor1000()
g... |
import signal
from datetime import timedelta, datetime
from time import sleep as time_sleep, time
class Timer(object):
timers = []
def __init__(self, func, duration, repeat=True):
self.duration = timedelta(seconds=duration)
self.func = func
self.repeat = repeat
self.last_call ... |
import datetime
import os
import time
import warnings
import presets
import torch
import torch.utils.data
import torchvision
import utils
from coco_utils import get_coco
from torch import nn
from torch.optim.lr_scheduler import PolynomialLR
from torchvision.transforms import functional as F, InterpolationMode
def ge... |
# Purpose: Pre-processing daily CMIP5 GCM 500 hPa geopotential height data and classification
# of Central European circulation types with the cost733class software
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# ... |
#!/usr/bin/python3
import wx
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
# %%
_code_git_version="e57a1a0f6fb8b29675f9338afef98a60cd98a0a2"
_code_repository="https://github.com/plops/cl-py-generator/tree/master/example/24_gtk3/source/run_00_show.py"
_code_generation_time="12:24:46 of Friday,... |
# generating captcha
from django.conf import settings
import random
import math
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
class GenCaptcha:
def __init__(self):
CAPTCHA_CONFIG = settings.CAPTCHA
self.height = CAPTCHA_CONFIG['picture_height']
self.width = CAPTCHA_C... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)
for i in range(1,10):
GPIO.output(18,1)
time.sleep(1)
GPIO.output(18,0)
time.sleep(1)
GPIO.cleanup()
|
# -*- coding: utf-8 -*-
import os
import shutil
sourcePath = "C:\\Users\Helga\CloudComputing\Database\Bilder\entpackt"
destinationPath = "C:\\Users\Helga\CloudComputing\Database\Bilder\destination"
personList = os.listdir(sourcePath)
# Get List of emotions from the 1st person without the "mixed"
emotionList = os.list... |
from rest_framework import serializers
from datetime import datetime, timedelta
from movielist.models import Movie
from showtimes.models import Cinema, Screening
class CinemaSerializer(serializers.HyperlinkedModelSerializer):
movies = serializers.SerializerMethodField()
class Meta:
model = Cinema
... |
from flask_login import login_required
from views.base_view import BaseView
class HelloView(BaseView):
@login_required
def get(self, name=None):
return self.render_template('hello.html', name=name)
|
# -*- coding: utf-8 -*-
from scrapy import Spider,Request
from anjuke.items import AnjukeItem
class AnjukehouseSpider(Spider):
name = 'anjukeHouse'
allowed_domains = ['anjuke.com']
start_urls = ['https://guangzhou.anjuke.com/sale/p1-rd1/#filtersort']
def parse(self, response):
# 所有房子URL
... |
# Copyright 2014 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 applicable law or a... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.backend.python.util_rules.package_dists import SetupKwargs, SetupKwargsRequest
from pants.core.util_rules.external_tool import (
Download... |
#!/usr/bin/env python
# coding: utf-8
# <b> Strings, List, Tuples <b>
# In[2]:
#Code prompts written by Cris Doloc
#Code responses written by Erika Lin
# <b> Transform the input string such that you will create another string by removing the characters of odd index values and replace them with the first character... |
import scrapy
import json
from scrapy import Request, FormRequest
import csv
import re
from scrapy.shell import inspect_response
class YelpSpider(scrapy.Spider):
name = "proxy"
allowed_domains = ["https://free-proxy-list.net"]
def start_requests(self):
url = 'https://free-proxy-list.net'... |
#################################
# Split the lineage output
################################
with open("lineages.tsv") as fn:
out = []
lines = fn.readlines()
splitLines = [line.strip('\n').split('\t') for line in lines]
for sp in splitLines:
spL = sp[1].split(";")
out.append(spL)
with open("split_lineages.ts... |
import airflow
from airflow.models import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.bash_operator import BashOperator
from airflow.operators.dummy_operator import DummyOperator
from datetime import datetime
args = {
'owner': 'Miha',
'start_date': datetime(2019,11,17),
... |
/home/ub/cvbridge_build_ws/devel/.private/catkin_tools_prebuild/_setup_util.py |
# coding: utf-8
"""
Telstra SMS Messaging API
The Telstra SMS Messaging API allows your applications to send and receive SMS text messages from Australia's leading network operator. It also allows your application to track the delivery status of both sent and received SMS messages.
OpenAPI spec version:... |
soma = 0
idade_velho = 0
nome_velho = ''
menos_20_anos = 0
for p in range(1, 5, 1):
print(f'----- {p}ª PESSOA -----')
nome = str(input('Nome: ')).strip()
idade = int(input('Idade: '))
sexo = str(input('Sexo [M/F]: ')).upper().strip()
soma += idade
if sexo == 'F' and idade < 20:
menos_20... |
from functools import lru_cache
@lru_cache(maxsize=None)
def number_of_ways_to_climb(stair_height):
if stair_height == 0:
return 1
elif stair_height < 0:
return 0
else:
return number_of_ways_to_climb(stair_height - 1) + number_of_ways_to_climb(
stair_height - 2) + number... |
import os
import sys
import json
cur_dir = os.path.dirname(os.path.realpath(__file__))
def isnum(s):
try:
float(s)
return True
except ValueError:
return False
#implement this method to return data for each time's command line!
def parse_tmp_file(fp):
res = {}
'''
keys = ['... |
import unittest
from hyper2web.http import Stream
from h2.events import DataReceived
class TestStream(unittest.TestCase):
def test_header_not_empty(self):
"""Stream should refuse to construct if the header is Falsy or not a dict"""
with self.assertRaises(Exception):
Stream(stream_id=1, headers={})
def test_... |
import sys
from collections import Counter
## get all types from gweb sancl labeled + unlabeled data
file_path="tokens.txt"
data = set()
with open(file_path, 'rb') as f:
for line in f:
word = line.decode('utf-8','ignore').strip()
data.add(word)
def load_embeddings_file(file_name, sep=" ",lower=Fal... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from time import gmtime, strftime
# Create your views here.
def index(request):
return render(request, "session_words_app/index.html")
def result(request):
return render(request, "sessio... |
# leap.bank_id
OUR_BANK = ''
# leap.username
USERNAME = ''
# leap.password
PASSWORD = '+'
#leap.consumer_key
CONSUMER_KEY = ''
# API server URL
BASE_URL = ''
API_VERSION = "v4.0.0"
# API server will redirect your browser to this URL, should be non-functional
# You will paste the redirect location he... |
import platform, os
print("\tPlatform Infromation \n")
print('\tVersion: ',platform.python_version())
print('\tVersion Tuple: ',platform.python_version_tuple())
print('\tCompiler: ',platform.python_compiler())
print('\tBuild: ',platform.python_build())
print('\n\tSystem Information\n')
print("\tUname: ",platform... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import os
def plot_pic(x_true, fbp, guess, plot_pic_savepath, plot_title):
fig, ax = plt.subplots(nrows=1, ncols=3)
ax[0].imshow(x_true[0].squeeze(-1))
ax[0].set_title('x_true... |
import pyqrcode
import png
from pyqrcode import QRCode
from PIL import Image, ImageFont, ImageDraw
import os
s = "https://patients-db-system.herokuapp.com/lab"
url = pyqrcode.create(s)
url.png('myqr.png', scale=6)
logo_file = "myqr.png"
logoIm = Image.open(logo_file)
im = Image.open("2.jpeg")
logoIm = logoIm.resize(... |
from __future__ import annotations
import re
from collections import namedtuple
from .helpers import prepend_scheme
VERBS = r"(get|options|head|post|put|patch|delete)\("
PREFIX = r"[\w_][\w\d_]*\."
PREFIX_VERBS = PREFIX + VERBS
SESSION_SEND = PREFIX + r"send\("
ASSERTIONS = r"assert \{"
Selection = namedtuple("Sele... |
# -*- coding: utf-8 -*-
# @Author : WangNing
# @Email : 3190193395@qq.com
# @File : db_tool.py
# @Software: PyCharm
import MySQLdb
import threading
from DBUtils.PooledDB import PooledDB
from common_utils.config_parser import DBConfigParser
class DBPool(object):
_lock = threading.Lock()
def __init__(sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.