text stringlengths 8 6.05M |
|---|
import csv
import collections
class Tree(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
class LRU:
def __init__(self, func, maxsize=128):
self.cache = collections.OrderedDict()
self.func = func
self.maxsize = maxsize
def __call_... |
/Users/matthewpeterson/anaconda3/lib/python3.7/tokenize.py |
"""
I am source code in boring.py
I have an optional block right here:
{%- filter stencil('qux') %}
This should only be included if the 'qux' pattern is applied
{%- endfilter %}
"""
|
from django.db import models
from django.contrib.auth.models import User
STATE_CHOICES = [('AL', 'AL'), ('AK', 'AK'), ('AZ', 'AZ'), ('AR', 'AR'), ('CA', 'CA'), ('CO', 'CO'), ('CT', 'CT'),
('DE', 'DE'), ('FL', 'FL'), ('GA', 'GA'), ('HI', 'HI'), ('ID', 'ID'), ('IL', 'IL'), ('IN', 'IN'),
... |
#import sys
#input = sys.stdin.readline
def add(A,a,w,N):#リストに値を追加する関数
x = a
while x <= N:
A[x-1] += w
x += x&(-x)
def sums(A,a):#k番目までの和
x = a
S = 0
while x != 0:
S += A[x-1]
x -= x&(-x)
return S
def main():
H, W, M = map( int, input().split())
G = [[] ... |
# -*- coding: utf-8 -*-
import discord
import requests
import random
from sys import exit, argv
from os import path, makedirs
from datetime import datetime, timedelta
from io import BytesIO
from urlparse import urlparse
from dateutil.parser import parse
from PIL import Image
import threading
import pycountry
import ... |
#!/usr/bin/python
"""
This file takes a csv file and writes a new one that has the MX added.
"""
import concurrent.futures, optparse, csv, dns.resolver, os
parser = optparse.OptionParser('-i [input_file] -o [output_file]')
parser.add_option('-i', '--input', dest='input_file')
parser.add_option('-o', '--output', des... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'mainwindow.ui'
##
## Created by: Qt User Interface Compiler version 5.14.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
###############... |
__title__ = "apprisetransactions"
__version__ = "1.0.2"
__license__ = "MIT"
__status__ = "Production"
from .transactions import MoneroTransaction
from .factories import MoneroFactory
from .configuration import ServerConfig
# Set default logging handler to avoid "No handler found" warnings.
import logging
from logging... |
import os
from peewee import *
arq = "pessoa.db"
db = SqliteDatabase(arq)
class BaseModel(Model):
class Meta:
database = db
class Pessoa(BaseModel):
nome = CharField()
dd = CharField()
mm = CharField()
aaaa = CharField()
rg = CharField()
cpf = CharField()
rua = CharField()
... |
from AU_rcnn.links.model.faster_rcnn.faster_rcnn_vgg16 import FasterRCNNVGG16 # NOQA
from AU_rcnn.links.model.faster_rcnn.faster_rcnn_vgg19 import FasterRCNNVGG19 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
if __name__ == '__main__':
iris = pd.read_csv('./data/Iris.csv')
# print(iris.describe())
y = np.array(iris[['Species']])
x = np.array(iris.drop(['Id', 'Species'], axis=1))
p... |
from turtle import Turtle, Screen
jabba = Turtle()
jabba.color('DeepPink')
jabba.shape('turtle')
jabba.forward(150)
print(jabba)
my_screen = Screen()
my_screen.exitonclick()
|
from django.urls import path, include, re_path
from AppTwo import views
urlpatterns = [
re_path(r'^$', views.user_form_view, name='user_form'),
]
|
import torch
import torch.optim as optim
import torch.nn.functional as F
from utils import *
import numpy as np
import gym
class PolicyGradient(nn.Module):
def __init__(self,featExtractor,nb_features,action_space,gamma=0.99,device='cpu'):
super(PolicyGradient,self).__init__()
self.featExt... |
import argparse
from sudoku.solver.sat import solve_all
def main():
ap = argparse.ArgumentParser()
ap.add_argument("-S","--strategy", type=int, choices=range(1,4), help="The strategy to use: S1, S2 or S3")
ap.add_argument("puzzles_filename", type=argparse.FileType('r'), help="the filename containing the SU... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fabric.api import local
from cli.decode import test_decode
from cli.encode import test_encode
from cli.help import test_help
from cli.init import test_init
from cli.version import test_version
from client.getpassword import test_getpassword
def main():
"""Main f... |
from MC2 import Name_Entity
import random, re
###MAAAAAAAAAAAAAAAAAAAIIIIIIIIIIIIIIIIIIIIIINNNNNNNNNNNNNN
#-----------------------------------------------------------------------------------------------------#
def MarkovChain(startWord):
#rep means reply / curr = current
#Reading Reference file and genera... |
#!/usr/bin/env python
import cv2, math
import numpy as np
from matplotlib import pyplot as plt
MEDIAN_FILTER_DIM = 5 # dimension of the median filter
RECENT_FRAMES = 10 # number of frames to look back by
def distance(p0, p1):
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)
def main():
video = ... |
'''
Write program to find the biggest and Smallest of N numbers.
PS: Use the functions to find biggest and smallest numbers.
'''
lst = [1,2,3,4,5,6,7,8,9]
print max(lst)
print min(lst)
|
def detect_anagrams(string, array):
lisret = []
list1 = list(array)
str2="".join(set(string.lower()))
for ent in list1:
if len(string) == len(ent) and string.lower() != ent.lower():
flag=0
for ch in str2.lower():
c2=(string.lower().count(ch))
c... |
import time
import logging
LOG = logging.getLogger(__name__)
def timeit(description='action'):
def timeit_inner(func):
def wrapped(*args, **kwargs):
now = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - now
LOG.debug('%s took %.3f seconds'... |
import sentiwordnet_analysis as swn
import pickle
##print(swn.sentiment("This movie was awesome! The acting was great, plot was wonderful, and there were pythons...so yea!"))
##print(swn.sentiment("This movie was utter junk. There were absolutely 0 pythons. I don't see what the point was at all. Horrible movie, 0/... |
import discord
import sqlite3
import requests
import json
import os, sys
class Db_Utilities():
def __init__(self, db_path: str, osukey: str):
self.db_path=db_path
self.osukey = osukey
self.displayupdate = None
self.usercountry = None
def add(self, member, osuID = None):
... |
# !/usr/bin/python
"""
-----------------------------------------------
Asset Wrangler
Written By: Colton Fetters
Version: 1.3
First release: 1/2018
-----------------------------------------------
DEVELOPER NOTES: Tool is an interface to aid in the version control of assets
Version History:
v1... |
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'C3502 ._SN',
MapName = 'Zeiss',
Location = 'C3502.x',
MapIndex = 1,
MapDefaultBGM = "ed60033",
Flags = 0,
En... |
# Generated by Django 2.0 on 2019-11-06 11:49
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('chats', '0009_auto_20191106_1119'),
]
operations = [
migrations.AlterModelOptions(
... |
import model_Le
from Data_loader import *
import torch.nn as nn
import torch
a,b = load_traffic_sign_data('E:\ex_python\sign_detection\\backup\\test.p')
testloader = DataLoader(
dataset=MyDataset(images=a,labels=b),
batch_size=1,
shuffle=True
)
# train_weights = 'E:\ex_python\sign_detect... |
import os
import kubeflow.kubeflow.crud_backend as base
from kubeflow.kubeflow.crud_backend import config, logging
from .routes import bp as routes_bp
log = logging.getLogger(__name__)
def create_app(name=__name__, cfg: config.Config = None):
cfg = config.Config() if cfg is None else cfg
# Properly set th... |
def main():
n = int(input("Insira n: "))
k = int(input("Insira k: "))
exp = 1
while k > 0:
exp *= n
k = k - 1
print("valor de n^k: ", exp)
if __name__ == '__main__':
main() # chamada que inicia o programa
|
#!/usr/bin/env python3
"""utility program that allows user to preview calendar's events"""
import sys
import pathlib
import argparse
from datetime import datetime
from icalendar import Calendar, __version__
def _format_name(address):
"""Retrieve the e-mail and the name from an address.
:arg an address object... |
from yahoo_historical import Fetcher
import csv
import datetime
import os.path
fetch_list = ["^GSPC","^RUA","^RUT","IJR"]
store_file_list = ["SP500","RUSSELL3000","RUSSELL2000","SP-SMALL-CAP"]
f = open("/Users/ahsentob/stock_predictions/own_prediction/data_collect/complete_stock_data.txt",'r')
message = [line.rstrip(... |
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from .models import Business
from .serializers import BusinessSerializer
from .easy_web_scraper import get_first_business_info
# Create your views here.
class BusinessView(APIView):
def __init_... |
def validarExtensionDeArchivo(ruta,extensiones):
key0 = True
key1 = True
if( len(ruta) > 0 and ruta[0] == "/" and ruta[1] != "/" ):
for x in range(0,len(ruta)):
if( ruta[x] == "/" ):
a = ruta[x-1]
b = ruta[x+1]
if( a == "/" or b == ... |
"""Mini Issue Tracker program. Originally taken from Paul Bissex's blog post:
http://news.e-scribe.com/230 and snippet: http://djangosnippets.org/snippets/28/
"""
from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation imp... |
import sys, ldap
from ceo import members, uwldap, terms, ldapi
def max_term(term1, term2):
if terms.compare(term1, term2) > 0:
return term1
else:
return term2
class ExpiredAccounts:
help = '''
expiredaccounts [--email]
Displays a list of expired accounts. If --email is specified, expired ac... |
import http.client
conn = http.client.HTTPSConnection("sandbox.handelsbanken.com")
payload = "client_id=b340f766-a89e-4887-a7c2-a553bccf6100&grant_type=client_credentials&scope=AIS"
headers = {
'Accept': "application\/json",
'content-type': "application/x-www-form-urlencoded",
'accept': "application/json... |
"""Visualization of disjoint set using forest structure"""
from numbers import Number
from random import randint
import time
class TreeNode:
def __init__(self, key: Number) -> None:
self.key = key
self.parent = None
self.height = 0
def __eq__(self, other) -> bool:
return sel... |
from utils.load_results import load_data
from pynfb.inlets.montage import Montage
import pylab as plt
import mne
import numpy as np
from helpers import get_XY, get_ideal_H, band_hilbert, ridge
from mne.viz import plot_topomap
df, fs, channels, p_names = load_data('/home/kolai/_Work/predict_eeg/results/alpha-delay-sub... |
test_input = input()
print(max(test_input, key=test_input.count))
|
import json
from kubeflow.kubeflow.crud_backend import logging
from werkzeug.exceptions import BadRequest
from . import utils
log = logging.getLogger(__name__)
SERVER_TYPE_ANNOTATION = "notebooks.kubeflow.org/server-type"
HEADERS_ANNOTATION = "notebooks.kubeflow.org/http-headers-request-set"
URI_REWRITE_ANNOTATION ... |
import cv2
import numpy as np
import math
"""
This code snippet does prediction on input mask using kalman filter.
The predicted parameters include mid point values and angle in which the lane is directed.
Two functions are used for kalman filter. One for midpoint prediction and other for angle prediction
for better r... |
import logging
import re
from furl import furl
from bs4 import BeautifulSoup
from share.harvest import BaseHarvester
logger = logging.getLogger(__name__)
class BiorxivHarvester(BaseHarvester):
VERSION = 1
def do_harvest(self, start_date, end_date):
end_date = end_date.date()
start_date = ... |
from Recorder import RECORDER
d = RECORDER()
d.Run_Forever()
|
from binance.client import Client
import configparser
import datetime
class Bot(object):
HIGH = 2
LOW = 3
API_KEY = ''
API_SECRET = ''
SYMBOL = 'BTCUSDT'
FEE = 0.01
intervalType = str()
interval = str()
priceMax = float()
priceMin = float()
fibLevels = [1, 0.786, 0.618, 0.... |
rule salmon_index:
input:
'reference/Homo_sapiens.GRCh38.transcriptome.fasta'
output:
directory('reference/Homo_sapiens.GRCh38.transcriptome.salmon_idx')
params:
# Optional parameters. Omit if unneeded.
extra = '',
threads: 1
log: 'logs/salmon/index/Homo_sapi... |
#Program to count number of each character in string
chars = "abcdefghijklmnopqrstuvwxyz"
new_str = input("Enter a string")
for char in new_str:
count = new_str.count(char)
if count > 1:
print(char + ":" + str(count)) |
#!/usr/bin/python
try:
import irc.client as client
except:
print('Unable to import irc.clients/irc.events')
client = None
events = None
from time import sleep
class IRC(object):
def __init__(self, server=None, port=6667, channel=None, nick=None, no_irc=False):
self.server = server
... |
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from os.path import basename
from email.mime.application import MIMEApplication
import CFGFileHelper
from email.utils import COMMASPACE, formatdate
import os
# def send_mail2(message, subject, files=None, path='.'):
# ... |
../../task7/part 2/graph.py |
### Udacity FSWD Project 3
### Track your goods, a way to calculate value of your
### household good for renter's insurance.
### Import the libraries used for Closet Item Project
from flask import Flask, render_template, request, redirect, jsonify, url_for, flash
from sqlalchemy import create_engine, asc
from sqlalch... |
#import sys
#input = sys.stdin.readline
def main():
# N = 13
# print(N)
# a = ord("a")
# ANS = []
# for i in range(N-1):
# ans = ["a"]*(N-1)+[chr(a+i)]
# ANS.append(ans)
# ANS.append([chr(a+i) for i in range(N-1,N+12)])
# print("\n".join(["".join(ans) for ans in ANS]))
# ... |
X, Y = map (int, input ().split ())
if X * 2 < Y or Y * 2 < X:
print ('NO SOLUTION')
else:
x = X
y = Y
if x > y:
while x > y:
print ('BGB', end = '')
x -= 2
y -= 1
print ('GB' * x)
else:
while y > x:
print ('GBG', end = '')
... |
import tensorflow as tf
from tensorflow import convert_to_tensor as to_T
from .config import cfg
from . import controller, nmn, input_unit, output_unit, vis
class Model:
def __init__(self, input_seq_batch, seq_length_batch, image_feat_batch,
num_vocab, num_choices, module_names, dropout_keep_pro... |
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
ban = []
for n in range(len(nums)):
if nums[n] == val:
ban.append(n)
for n in ban[::-1]:
nums.p... |
import json
import pyotp
from decimal import Decimal
from django.shortcuts import render, HttpResponse, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import TemplateView
from django.core.exceptions import... |
import torch
from gmf import GMF
from mlp import MLP
from engine import Engine
from utils import use_cuda, resume_checkpoint
class NeuMF(torch.nn.Module):
def __init__(self, config):
super(NeuMF, self).__init__()
self.config = config
self.num_users = config['num_users']
self.num_it... |
import unittest
import json
import hmac
import hashlib
import httplib
import decimal
import requests
from bitmm.psp import client
def sign(data, fields, apikey):
values = []
for field in fields:
values.append(str(data[field]))
return hmac.new(''.join(values), apikey, hashlib.sha256).hexdigest()
... |
import os, sys
import multiprocessing
import subprocess
# Crawler function
def crawler(topic):
# This crawler will generate csv file in /topic
cmd = "python WeiboTopicScrapy.py %s" % topic
print(cmd)
os.system(cmd)
print("Getting top topics")
print("Start writing top topics to topic/top_topics.txt")... |
import unittest
from tree_utils import Node
def is_bst_compare(root):
"""Check if tree is bst by definition."""
return _is_bst_compare(root, float('-inf'), float('inf'))
def _is_bst_compare(root, mini, maxi):
"""Recursively check if a node is in given range.
Any node in a bst must be less than a... |
import struct
from Crypto.Cipher import AES
from io import BytesIO
def decrypt(key, data, size_of_chunk=24*1024):
origin_size = struct.unpack('<Q', data.read(struct.calcsize('Q')))[0]
iv = data.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
origin_data = b''
while True:
chunk = data... |
import numpy as np
Radcliffe_A = 2800 #collecting area (cm^2)
Radcliffe_T = 0.35 #combined transmission efficiency
Radcliffe_eta = 0.55 #CCD quantum efficiency
Radcliffe_deltalambda = 1000 #bandwidth of filter/spectograph per pixel (Å)
Radcliffe_s_sky = 10 #sq. arcsec
Radcliffe_n_pix = 20 #pixels
Allen_A = 2800 #coll... |
# Masks code file for Vocal learning papers
# Author: Beren Millidge
# Date: Summer 2018
import numpy as np
def diagonal_mask(x,y, diff=15):
if x + diff > y and x -diff < y:
return (1,1,1)
else:
return (0,0,0)
def half_diagonal_mask(x,y,diff=5):
if x+diff > y:
return (1,1,1)
else:
return (0,0,0)
def... |
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import datetime
def union_set(a, b):
for j in range(len(b)):
if b[j] not in set(a):
a.append(b[j])
return a
def return_k_nn(source,G,k):
read_index = 0
my_set = []
my_set = union_set(my_set,[source])
... |
#!/usr/bin/python
# coding: utf-8
import os
import glob
import numpy
from scipy.misc import imread,imsave
from PIL import Image
#name of the directory with the processed images
dst = "color3"
#position of the discontinuity in the image
disc=1776
#arrays to convert images back & forth from RGB to YUV space.
RGB2YUV ... |
import pickle
def storeData():
davide = {'key': 'davide','name':'mezbah davide',
'age' : '25', 'pay' : '100000$'}
mezbah = {'key' : 'mezbah', 'name' : 'davide mezbah',
'age' : '26', 'pay' : '100000$'}
db = {}
db['davide'] = mezbah
db['mezbah'] = davide
... |
# -*- coding: utf-8 -*-
from irc3.testing import BotTestCase
from irc3.compat import asyncio
import irc3
@irc3.event(irc3.rfc.PRIVMSG)
def msg1(bot, **kwargs):
bot.privmsg('#irc3', 'msg1')
@irc3.event(irc3.rfc.PRIVMSG)
def msg2(bot, **kwargs):
bot.privmsg('#irc3', 'msg2')
@irc3.event(irc3.rfc.PRIVMSG, iot... |
# Generated by Django 3.2.5 on 2021-07-29 07:32
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('management', '0002_auto_20210729_1258'),
]
operations = [
migrations.AlterField(
model_name='appoin... |
import logging
from ...config import Configuration
def action_tabulate(cp, outfilename):
logger = logging.getLogger(__name__).getChild('_action_tabulate')
config = Configuration()
tabulation = config.read_from_parser(cp)
with tabulation.open_fp(outfilename) as outfile:
logger.info("Writing output to: {}".... |
from bs4 import BeautifulSoup
import requests
# takes in a url and returns a dict of [word, occurrences]
def scraper(url):
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
text = ''
for par in soup.find_all('p'):
text = text + ''.join(par.findAll(text=True))
words = text... |
#!/usr/bin/env python
"""Python script for the COCO experimentation module `cocoex`.
Usage from a system shell::
python ES_with_Search_Path.py bbob
runs a full but short experiment on the bbob suite. The optimization
algorithm used is determined by the `SOLVER` attribute in this file.
python ES_with_Search_... |
"""
Student ID: 2594 4800
Name: JiaHui (Jeffrey) Lu
Aug-2017
"""
import numpy as np
# import matplotlib.pyplot as plt
def taylor_sine(x, d):
"""
Element-wise function for sine.
:param x: sine argument
:param d: specifies when to stop the taylor series expansion
:return: the taylor expansion of ... |
import datetime
import time
def main():
timebool = True
starttime = datetime.datetime.now()
while(timebool == True):
currenttime = datetime.datetime.now()
passedtime = currenttime - starttime
time.sleep(1)
print(passedtime)
if __name__ =='__main__':
main()
|
"""
Copyright 2019 INESC TEC
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 agreed to in writing, software
distr... |
/Users/Di/anaconda/lib/python2.7/types.py |
#!/usr/bin/python
import sys
import csv
import re
reader = csv.reader(sys.stdin, delimiter='\t', quoting = csv.QUOTE_MINIMAL)
for line in reader:
# YOUR CODE HERE
#print len(line)
if len(line) < 5:
continue
data = line[4].strip()
nodeId = line[0].strip()
nodeId = nodeId.replace('"','')
if nodeId.isdigit() =... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
input_1 = pd.read_csv("efficientnet-b1.csv") # 1.4
input_2 = pd.read_csv("resnet152.csv") # 1.1
input_3 = pd.read_csv("resnet152_2.csv") # 1.2
input_4 = pd.read_csv("densenet169.csv") # 1.1
input_5 = pd.read_csv... |
import re
import logging
import jieba
from torchtext import data
from torchtext import vocab
jieba.setLogLevel(logging.INFO)
def tokenizer(text):
"""
定义TEXT的tokenize规则
"""
#去掉不在(所有中文、大小写字母、数字)中的非法字符
regex = re.compile(r'[^\u4e00-\u9fa5A-Za-z0-9]')
text = regex.sub(' ', text)
#使用jieba分词... |
#import sys
#input = sys.stdin.readline
def main():
N, M = map( int, input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
dp = [[0]*(M+1) for _ in range(N+1)]
for i in range(1,N+1):
dp[i][0] = i
for j in range(1,M+1):
dp[0][j] = j
for i in ra... |
#!/usr/bin/env python3
"""
Author: David Hein
This script can be used to do the initial commits of a new IntelliJ project.
The following files will be commited:
- Git Ignore
- IntelliJ project folder
- Gradle files
Requirements:
- A Git repo must exist in the directory of the Grav source code
- Git must be usable v... |
#!/usr/bin/env python3
# File: arp4pi.py
"""
Usage:
sudo ./arp4pi.py
Tries to find the IP address of any device
with any of the known MAC addresses listed
in MAC_W_ID.
This script must be run with root privileges!
Development was inspired by the Raspberry Pi
related projects. Because of this, an added feature... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
L = list(filter(lambda n:n%2==0, range(1, 20)))
print(L) |
#!/usr/bin/python
"""
Given a station ID, yield all availble data using mapreduce
take USC00515000 as an example
"""
import sys
sys.path.append('/usr/lib/python2.6/dist-packages')
from mrjob.job import MRJob
from sys import stderr
import pandas as pd
import re,pickle,base64,zlib
def decode(eVal):
""" Decode a str... |
from django.http import HttpResponse
# Helper functions and classes
class HttpResponseBadRequest(HttpResponse):
"""
HTTP 400 response
Used when the server cannot or will not process the request
due to an apparent client error
"""
def __init__(self, reason=None):
if reason is None:
... |
from django.test import TestCase
from products.forms import ProductForm
from products.models import Product
from django.urls import reverse
from django.contrib.auth.models import User
from django.test.client import Client
# form tests
class TestProductForm(TestCase):
def test_fields_are_explicit_in_form_metaclas... |
from libs.config import alias, color
from libs.myapp import send
def get_php(type, ip, ports, timeout):
return """
# gettime_
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function Scan($type,$ip,$ports,$timeout){
try{
... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
'''
Created on 2017/12/18
@author: ChaoZhong
@email: 16796679@qq.com
'''
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql://root:123456@127.0.0.1:3306/ops'
SQLALCHEMY_TRACK_MODIFICATIONS = True
CSRF_ENABLED = True
SECRET_KEY = 'GU36b8TE55aeq2gLLZ0P3DquSk8wJ3pP'
|
x = 1,2,3
print x
y = 1,
print y
c = (1,2,3)
print c
d = 3*(40+2,)
print d
e = 3*(40+2)
print e
f = tuple([1,2,3])
print f
h = tuple('abc')
print h
print f[2]
print f[:2] |
# Method 1
# import hashlib
# def md5(fname):
# hash_md5 = hashlib.md5()
# with open(fname, "rb") as f:
# for chunk in iter(lambda: f.read(4096), b""):
# hash_md5.update(chunk)
# return hash_md5.hexdigest()
# Method 2
# import hashlib
# with open("your_filename.png", "rb") as f:
# ... |
# created by Raymond Chung
# file engine.py
# imports
import sys, pygame, math, agent, item, os, random
import titlescreen, room
import levels.grasslands as grasslands
import levels.bosslands as bosslands
class engine:
def __init__ (self, state, screen, clock, width, height):
self.state = state
self.width = wi... |
from flask.json import JSONEncoder
from utils.redis import get_redis_cli
__author__ = 'liangzili'
redis_cli = get_redis_cli()
GET_LIST_PROPS = ["brief", "cover", "title", "type", "url"]
# 文章的model,使用Redis保存,保存到db的字段要设置为公开的, 其他字段全都保存成私有字段
# 还需要指定用于存储的主键是哪个属性, __pk作为HashTable的主键,而__index作为该文章在list中的索引
class BaseArtic... |
A = []
protokol = []
enter = input ()
while enter != 'exit':
p = enter [1]
if p == 'u':
x = enter [5:]
A += x
protokol.append ('ok')
elif p == 'o':
if len (A) > 0:
x = A.pop (0)
protokol.append (x)
else: protokol.append ('error')
elif p == ... |
class Human:
def __init__(self, firstname, age, surename, IIN):
self.firstname = firstname
self.age = age
self.surename = surename
# self.__IIN = IIN
def eat(self):
print("Human eating")
def walk(self):
print("Human walking")
# print(self.__IIN)
cla... |
#!/usr/bin/python
#\file sync_server_2.py
#\brief Synchronous Modbus TCP server test 2.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Jun.22, 2023
from pymodbus.server.sync import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSeq... |
import os
clear = lambda: os.system('clear')
import art
from art import *
import time
from time import sleep
import requests
from bs4 import BeautifulSoup
import geopy
from geopy.geocoders import Nominatim
###################################################
Art = text2art("ES Weather")
print(Art, "\n")
def getWe... |
#!/usr/bin/env python
"""
Instantiates a project on a particular cluster.
Run this from a project directory. The cluster identity will be inferred
automatically. If the required configurations are not available for this
cluster, an error will be emitted.
"""
from __future__ import print_function
import os
import ... |
import sys
import os
import getpass
import requests
import json
import time
from boj import Boj
from option import Option
from git import Git
sess = requests.Session()
if __name__ == "__main__":
#python main.py 1000.cpp 1000 | python main.py filename problem_number
if len(sys.argv) != 3:
... |
import math
import operator
from collections import Counter
def get_lexicon_distribution(lexicon):
"""Get counts of polarity values in a lexicon."""
distro_dict = Counter()
for polarity in lexicon.values():
distro_dict[polarity] += 1
return distro_dict
def get_lexicon_classes(lexicon):
"... |
'''
Created on Dec 20, 2016
@author: bogdan
'''
from domain.entities import *
from repo.FileRepository import *
from ui.ui import *
from controller.Controller import *
Dr=FileDriverRepository()
Or=FileOrderRepository()
cont=Controller(Dr,Or)
UI=ui(cont)
UI.runApp() |
"""
MUSEpy is a python based package for the analysis of MUSE data.
Please report requests/bugs/issues to amcleod@eso.org.
Please aknowledge MUSEpy if you use it for your publications!
"""
class MUSEpy:
def __init__(self):
self
from astropy.io import fits
from spectral_cube import SpectralCube
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.