text stringlengths 8 6.05M |
|---|
from scapy.layers.l2 import Ether, ARP, srp
from scapy.all import send
import os
import sys
def get_mac(ip):
"""
Gets the MAC address of the IP address.
:param ip: IP address to get the MAC of.
:return: MAC address of IP OR None
"""
# Send the ARP request packet asking for the owner of the IP ... |
def cockroach_speed(km_h):
return int(km_h / 0.036) # centimeters per second
|
from os.path import join
from typing import Any, Callable, List, Optional, Tuple
from PIL import Image
from .utils import check_integrity, download_and_extract_archive, list_dir, list_files
from .vision import VisionDataset
class Omniglot(VisionDataset):
"""`Omniglot <https://github.com/brendenlake/omniglot>`_ ... |
import collections
import json
import os.path
import pelops.datasets.chip as chip
import pelops.utils as utils
class DGCarsDataset(chip.ChipDataset):
filenames = collections.namedtuple(
"filenames",
[
"all_list",
"train_list",
"test_list",
]
)
f... |
# coding:utf-8
# with语句
# 需求1:文件处理,用户需要获取一个文件句柄,从文件中读取数据,然后关闭数据
with open("text.txt") as f:
data = f.read()
# 使用了with语句,不需要try-finally语句来确保文件对象的关闭。因为无论程序是否出现异常,文件对象都将被系统关闭。
|
class PluginInfo:
def __init__(self) -> None: ...
def __bool__(self) -> bool: ...
@property
def items(self): ...
def __contains__(self, name) -> bool: ...
def __getitem__(self, name): ...
# Names in __all__ with no definition:
# _dispatch
# _mark_tests
|
import keg_storage
class DefaultProfile(object):
# This just gets rid of warnings on the console.
KEG_KEYRING_ENABLE = False
SITE_NAME = 'Keg Storage Demo'
SITE_ABBR = 'KS Demo'
KEG_STORAGE_PROFILES = [
(keg_storage.S3Storage, {
'name': 'storage.s3',
'bucket': 'st... |
#Automatically created by SCRAM
import os
__path__.append(os.path.dirname(os.path.abspath(__file__).rsplit('/TauDataFormat/TauNtuple/',1)[0])+'/cfipython/slc5_amd64_gcc462/TauDataFormat/TauNtuple')
|
import unittest
import numpy.testing as testing
import numpy as np
import hpgeom as hpg
from numpy import random
import tempfile
import shutil
import os
import pytest
import healsparse
try:
import healpy as hp
has_healpy = True
except ImportError:
has_healpy = False
class HealpixIoTestCase(unittest.Test... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import os
def get_args():
parser = argparse.ArgumentParser(description='BERT Baseline')
parser.add_argument("--model_name",
default="BertOrigin",
type=str,
help="the name... |
#encoding: utf8
import string
import math
import scripts
class NaiveBayesClassifier:
def __init__(self, alpha = 1):
self.alpha = alpha
return
def fit(self, X, y):
""" Fit Naive Bayes classifier according to X, y. """
targets = list(set(y)) # список состояний
w... |
import copy
class Language(object):
class Rule(object):
def __init__(self, string=None):
if string is not None:
self.__init_from_string(string)
def __init_from_string(self, string):
parts = string.split(' ')
self._from = parts[0]
... |
from kafka import KafkaConsumer
import json
import io
topic = 'electric'
key_deserializer = 'org.apache.kafka.connect.storage.StringConverter'
value_deserializer = lambda m: json.loads(m.decode('ascii'))
group_id = 'electric-group'
consumer = KafkaConsumer(topic, group_id='consumer-grp', value_deserializer=value_des... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 3 15:28:16 2019
@author: dhk13
"""
from bs4 import BeautifulSoup as soup
import requests
import datetime
def SWedu(today1):
url="http://swedu.khu.ac.kr/board5/bbs/board.php?bo_table=06_01"
html=requests.get(url).text
obj=soup(html, "html.parser")
table... |
import logging
from logging.handlers import (RotatingFileHandler,
QueueHandler,
QueueListener)
from fansettings import LOG_PATH
f = logging.Formatter('%(asctime)s: %(name)s|%(processName)s|%(process)s|%(levelname)s -- %(message)s')
def getFanLogger(name=None... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 15 16:00:47 2017
@author: lcao
"""
import pandas as pd
import numpy as np
import os
import re
# set working directory
os.chdir('D:\Personal\Hackathon\WeiboSum')
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# import statistical data ... |
from django.urls import path
from django.conf.urls import include, url
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('view/', views.handle_view_file, name='view'),
path('upload/', views.handle_file_upload, name='upload'),
path('risk/', views.handle_column_select... |
/home/alex/ScienceWork/SUFEX-Kinetics/Calorimetry/Plot/Integrate-Exp-Data.py |
import tkinter as tk
from tkinter import filedialog as fd
import numpy as np
from fields_analyzer.json_reader import read_json_file
from fields_analyzer.fields_analyzer import select_fields_to_analyze
from algorithm.K_Means import K_Means
from results_and_plotter.clusters_results import cluster_results
from results_a... |
a = input().split()
result = ''
for i in range(len(a)):
if len(a) == 1:
result += a[i]
else:
if i != len(a) - 1:
t = int(a[i - 1]) + int(a[i + 1])
result += str(t) + " "
else:
t = int(a[i - 1]) + int(a[0])
result += str(t)
print(result) |
# Generated by Django 3.0.5 on 2020-08-13 10:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authentication', '0005_auto_20200813_1014'),
]
operations = [
migrations.RenameField(
model_name='attendance',
old_name='log... |
#Respuestas por defecto
# -*- coding: latin-1 -*-
opciones = {
"users": {"Pablo Marinozi","Facundo Bromberg","Diego Sebastián Pérez","Carlos Ariel Díaz","Wenceslao Villegas","Juan Manuel López Correa"},
"inclusion_criteria": ("El estudio utiliza algún proceso de extracción de información automatizado sobre imág... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 17:23:19 2019
@author: HP
"""
def Extended_Euclidean(a,b):
if b==0:
return 1,0,a
else:
m,n,gcd1=Extended_Euclidean(b,a%b)
x=n
y=m-int(a/b)*n
gcd=gcd1
return x,y,gcd
print(Extended_Euclidean(10,7)) |
from sqlalchemy import (
Column,
DateTime,
Integer,
Numeric,
String,
UniqueConstraint,
and_
)
from sqlalchemy.orm import relationship, synonym
from bitcoin_acks.constants import ReviewDecision
from bitcoin_acks.database.base import Base
from bitcoin_acks.models import Comments, Labels
from ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 13:00:48 2019
@author: Ananthan
"""
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
import pandas
#works well for 675 input files, but will give poor labels for many more or less.
def plot_heat_map(matrix,path, title):
# height = plt.rcPar... |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... |
import os
from matplotlib import pyplot as plt
from shapely.geometry import Point
import cv2
import numpy as np
from objects.constants import Constants
from objects.homography import Homography
from objects.images import TestImage, TemplateImage
from objects.plot_discarded import PlotDiscarded
default_backend = None
... |
import numpy as np
import torch
import cv2
import os
import os
import glob
from photometric_augumentation import *
from homography_transform import *
def space_to_depth(inp, grid):
if len(inp.shape) is not 2:
raise ShapeError("input should be 2D-Tensor")
h, w = inp.shape[0], inp.shape[1]
hc = h // g... |
import os
import shutil
import StringIO
import urlparse
import zipfile
import requests
VERSION = '0.8'
GITHUB_URL = 'https://github.com/NLeSC/ShiCo/archive/v{}.zip'.format(VERSION)
STATIC_DIR = 'texcavator/static/js/'
DIST = 'ShiCo-{}/webapp/dist/'.format(VERSION)
DIST_DIR = os.path.join(STATIC_DIR, DIST)
FINAL_DIR ... |
# coding: utf-8
import os.path as osp
import pandas as pd
from ddf_utils.io import open_google_spreadsheet, serve_datapoint, dump_json
from ddf_utils.str import to_concept_id
from ddf_utils.package import get_datapackage
DOCID = '1hhTERVDWDyZh-efUPtMrcdUYWzXBlIbrOIhZwegXSi8'
SHEET = 'data-for-countries-etc-by-year'
... |
"""
This is a web app created with Streamlit to host this project. Feel free to use this file as a guide or visit my
article on the topic (linked below).
"""
import streamlit as st
import pandas as pd
import numpy as np
import pickle
from PIL import Image
from sklearn.linear_model import LogisticRegressionCV
st.heade... |
#!/usr/bin/python3
class Square():
"""Empty class square."""
def __init__(self, size):
"""init square function."""
self.__size = size
|
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'dir2_target',
'type': 'none',
'dependencies': [
'../dir1/dir1.gyp:dir1_target',
],
'act... |
#!/usr/bin/python
def numDivisors(n):
count = 0
j = 1
max = n
while j < max:
if n % j == 0:
count += 2
max = n / j
j += 1
return count
i = 2
num = 1
while numDivisors(num) <= 500:
num += i
i += 1
print(num)
|
from eos import Fit, Ship, ModuleHigh, ModuleMed, ModuleLow, Rig, Implant, Drone, Charge, State, Skill
from ..eve_static_data.consts import CAT_SKILLS
from ..extensions import cache
from ..eve_static_data import eve_static_data_service
class PyfaEosService(object):
def build_high_module(self, type_id, state, c... |
import numpy
import os
import shutil
import random
"""
将图像路径和label写入txt文件
"""
datapath = "D:/project/tensorflow-vgg/test_data"
labels = os.listdir(datapath)
filetxt = open("test_label.txt","w")
idx = -1
for dirpath,dirs,files in os.walk(datapath):
for file in files:
label = labels[idx]
one_hot_lab... |
class Solution(object):
def removeDuplicates(self, nums):
n = len(nums)
if n == 0:
return 0
k = nums[0]
count = 1
i = 1
delete = 0
while i+delete<n:
if nums[i] == k:
count += 1
else:
count = 1... |
#!/usr/bin/env python3
"""
Script for creating the various files required for import of data into
the TextGrid Repository.
The script requires the metadata file produced in the previous step and
the full XML-TEI files to be uploaded.
Usage: The only parameter you should need to adjust is the path
encoded in ... |
#!/usr/bin/env python
aTup = ('I', 'am', 'a', 'test', 'tuple')
res = ()
for i in range( len(aTup) ):
if i%2 == 0:
res += ( aTup[i], )
print res
|
"""treadmill.dirwatch tests"""
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'zq'
import sys
import yaml
import socket
import os
from kafka import KafkaProducer
from datetime import *
"""
kafka-broker-list: kafka100:9092
kafka-topic: demo
filepath : sample.csv
offset : 0
interval : 7
learning : 100
colu... |
A=int(input("A= "))
print((A>99)and(A<1000)and(A%2!=0)) |
import sys
sys.path.insert(0, '/usr/local/blocked')
from BlockedFrontend.server import app as application
|
from django.apps import AppConfig
class CustomstrategyConfig(AppConfig):
name = 'CustomStrategy'
verbose_name='自定义策略' |
def filter_long_words(sentence, n):
return [x for x in sentence.split() if len(x)>n]
'''
Write a function filter_long_words that takes a string sentence and an integer n.
Return a list of all words that are longer than n.
Example:
filter_long_words("The quick brown fox jumps over the lazy dog", 4)
= ['quick', ... |
import cv2
import numpy as np
from PIL import Image
def binarize(img):
'''
functions:
将截取的图片进行二值化
'''
#--将PIL.Image.Image转化为OpenCV的格式
# 并转为灰度化图像
img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
#设定阈值 进行二值化
threshold = 200
param = cv2.THRESH_BINARY
ret,proces... |
import os
import numpy as np
import pandas as pd
import pickle
import msgpack
import copy
import pulp
from fdsim.helpers import create_service_area_dict
import sys; sys.path.append("../../work")
from spyro.utils import obtain_env_information, make_env, progress
STATION_NAME_TO_AREA = {
'ANTON': '13781551',
... |
from time import sleep
from interface.menus import *
pysolvers = ['\033[34mGabriel Correia (gothmate)',
'Pablo Narciso',
'Antonio (Tonny)',
'Eduardo Gonçalves',
'Ricardo Garcêz\033[m',
]
cabecalho('QUIZ PySolvers 2.0')
print('''\033[33mBem vindo ao Quiz... |
"""servos offers an interface for controlling motors that has been attached to an Arduino.
"""
import multiprocessing
import numpy as np
import logging
import time
import pyfirmata
class Servo(object):
# safety delay after changing the servos angle in case no particular number has been
# defined by the use... |
import csv
import random
man = list(range(100,150,1))
woman = list(range(200,250,1))
with open('kekka.csv', 'w') as f:
for M in man:
for F in woman:
f.write(str(M) + "," + str(F) + "," + str(random.randint(1,1000)) + "\n") |
import time
import traceback
import multiprocessing
from functions.plot_manager import setup_backend_for_saving
from functions.process_functions import find_homographies_per_thread
from objects.constants import Constants
from objects.homography import Homography
from objects.images import TemplateImage, TestImage
from... |
t = int(input())
while t > 0:
import math
n,k = map(int,input().split())
arr = []
for i in range(k+1,n+1,+1):
arr.append(i)
x = math.ceil(k/2)
for i in range(x,k,+1):
arr.append(i)
print(len(arr))
print(*arr,sep=" ")
t = t-1 |
def calculate_total_weight(doc,method):
from frappe.util import flt
total_net_weight = 0.0
for x in doc.items:
x.weight = flt(x.weight_per_unit) * flt(x.qty)
total_net_weight = x.weight
doc.total_net_weight = total_net_weight |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#############################################################################
# #
# author: t. isobe (tisobe@cfa.harvard.edu) #
# ... |
#coding: utf-8
#1.import packages
import torch
import torchvision
from torch import nn, optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import datasets
#2.Def Hyperparameters
batch_size = 100
learning_rate = 0.05
num_epoches = 50
#3.import MNIST
data_tf = torchvis... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'DoS.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dos_MainWindow(object):
def setupUi(self, Dos_MainWindow... |
import math
A, B, C = input().split()
A = float(A)
B = float(B)
C = float(C)
Delta = (B*B) - (4*A*C)
if A == 0 or Delta < 0:
print('Impossivel calcular')
else:
x1 = (-B + math.sqrt(Delta))/(2*A)
x2 = (-B - math.sqrt(Delta))/(2*A)
print('R1 = {:.5f}'.format(x1))
print('R2 = {:.5f}'.format(x2)) |
"""
Dieses Programm trainiert das neuronale Netz.
Dafür werden die Daten aus dem "dataset"-Verzeichnis verwendet.
Verwendung: 'python3 train-netzwerk.py'
(am besten zusamen mit 'nice' ausführen, da das Training lange
dauert und sehr rechenintensiv ist)
"""
import sys
import os
import numpy as np
from keras.applicat... |
import random
from card import card
class deck:
"""
model of a deck
"""
def __init__(self):
"""
initialize deck object
"""
self.cardList = []
deck.generate(self)
def generate(self):
"""
generates a deck of 52 cards
:return: none
... |
from estnltk_workflows.postgres_collections.argparse import get_arg_parser
from estnltk_workflows.postgres_collections.argparse import parse_args
from estnltk_workflows.postgres_collections.data_processing.tag_collection import tag_collection |
import FWCore.ParameterSet.Config as cms
#PreselectionCuts = cms.EDFilter('SkimmingCuts',doMuonOnly=cms.bool(False))
#MuonPreselectionCuts = cms.EDFilter('SkimmingCuts',doMuonOnly=cms.bool(True))
NoPreselectionCuts = cms.EDFilter('SkimmingCuts',preselection=cms.untracked.string(""))
MuonPreselectionCuts = cms.EDFilter... |
#!/usr/bin/env python
import argparse
import inception
# Load model and categories at startup
model, synsets = inception.load_inception_model()
# Detect image with MXNet
image = inception.load_image('images/image1.jpg')
prob = inception.predict(image, model)
topN = inception.get_top_categories(prob,... |
with open("day7input.txt", "r") as f:
input_data = f.read()
progdict = {}
for line in input_data.split("\n"):
print(line)
arrow = line.find('>')
if arrow > 0:
children = line[arrow+2:].split(', ')
print(children)
parent = line[:arrow-2].split()[0]
... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def input(request):
return render(request,'base.html')
def add(request):
x=int(request.GET['t1'])
y=int(request.GET['t2'])
z=x+y
resp=HttpResponse("<html><body bgcolor=blue><h1>values submitted succes... |
from behave import *
from fastapi import testclient
import api
from fastapi.testclient import TestClient
@given("que deseo sumar dos numeros")
def step_implementation(context):
context.app = TestClient(api.app)
@when('yo ingrese los numeros {num1} y {num2}')
def step_implementation(context, num1, num2):
... |
import numpy as np
from mnist import MNIST
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from torch.autograd import Variable
import pandas as pd
mndata = MNIST('data')
np.set_... |
# -*- coding: utf-8 -*-
from .basic import index
from .feed import AtomFeed, RssFeed
app_name = 'yyfeed'
|
import random
import json
import torch
from model import NeuralNet
from nltk_utils import bag_of_words, tokenize
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open('intents.json', 'r') as json_data:
intents = json.load(json_data)
FILE = "data.pth"
data = torch.load(FILE)
input... |
#!/bin/env python
#using the wireframe module downloaded from http://www.petercollingridge.co.uk/
import mywireframe as wireframe
import pygame
from pygame import display
from pygame.draw import *
import time
import numpy
key_to_function = {
pygame.K_LEFT: (lambda x: x.translateAll('x', -10)),
pygame.K_RIGHT... |
#!/usr/bin/python3
def multiple_returns(sentence):
return (len(sentence), sentence[0] if (sentence) else None)
|
string = "hello Tom, nice to meet you!"
def reverseString():
splittedArray = string.split(" ")
array = []
newstring = ""
for i in range(len(splittedArray)):
# array.pop()
if splittedArray[i].find(",")>-1:
print(f"before replace ,{splittedArray}")
splittedArray[... |
"""This is the "main script" which will be run and from where the actual work will be done"""
from judge import upload
from judge import judge
from sites import tabroom
from sites import judge_phil
from global_vars import db
import getopt, sys
def remove_dup(arg):
name = arg.split(" ")
all_judges_first = db.chi... |
from django.contrib import admin
from .models import Post
from .models import Post2
class PostAdmin(admin.ModelAdmin):
list_display=('title','author','created_date','published_date')
search_fields =('title',)
# Register your models here.
admin.site.register(Post,PostAdmin)
class PostAdmin2(admin.ModelAdmin):
l... |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.template import loader
from django.core.paginator import Paginator
# Create your views here.
from .models import Messages
import... |
# usage: python USP_server_example.py <host> <port>
import sys
import os
import time
from unix_socket_protocol import USP_SERVER
def callback_func(json_str):
print(json_str)
if __name__ == "__main__":
server = USP_SERVER(sys.argv[1], callback_func, 10)
server.start_server()
print ("server started")
... |
"""
The file_utils module provides methods for accessing or manipulating the
filesystem.
"""
from ephemeral.definitions import ROOT_DIR
def get_relative_package_path():
"""Gets the relative path for the package useful to finding package relative
property files or other resources.
"""
return ROOT_DIR
|
def isPalindrome(s,i,j) :
d = [i for i in s[i:j+1]]
d.reverse()
d = ''.join(d)
if (d == s) :
return True
else :
return False
def PP (i , j) :
global s
if (i >= j) :
return 0
else :
if (isPalindrome(s,i,j)) :
return 0
else :
minimum = float('inf')
for k in range (i,j) :
c = PP(i,k) + PP(k+... |
from django.conf.urls import patterns, include, url
import session_csrf
session_csrf.monkeypatch()
from django.contrib import admin
admin.autodiscover()
from django.views.decorators.cache import cache_page
from blog.views import IndexView
from blog.views import PostView
urlpatterns = patterns('',
... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__)))
del os
del sys
# from system import *
from _statistics import *
from _trig import *
from _basic import *
from _specialf import *
|
import turtle
turtle.pendown()
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
tutle.right(90)
turtle.forward(100)
turle.right(90)
turtle.forward(100)
|
"""
Author: Nemanja Rakicevic
Date : January 2018
Description:
Load a model from the experiment directory and evaluate it on a
user defined test.
"""
import sys
import json
import logging
import argparse
import informed_search.tasks.experiment_manage as expm
def loa... |
# -*- coding: utf-8 -*-
class MergeSort(object):
items = []
def __init__(self,items):
self.items = items
def sort(self,n):
def merge(self):
|
#!/usr/bin/python3
# variables.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
#creates a tuple, immutable
x = (1,2,3)
print(type(x), x)
#can get each of the elements in an objet
for i... |
# Generated by Django 2.2.1 on 2019-07-10 12:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('notice', '0002_auto_20190710_2125'),
]
operations = [
migrations.RemoveField(
model_name='notice',
name='file',
),
... |
import json,operator
from getting_old import imageProcess
from text_sentiment import textProcess
#format ['12312312',{'sad':'0.8'},{'angry':0.4}] ,['12312300',{'happy':'0.7'},{'surprise':0.2}] ,['12312310',{'disgust':'0.9'},{'angry':0.1}]]
from twitter import getTweets
import pickle
net_tweets=[]
def get_json(usern... |
import numpy as np
start = 143
stop = 10000
n = np.arange(start, stop)
triangle = n*(n+1)/2
pentagon = n*(3*n-1)/2
hexagon = n*(2*n-1)
temp = [i for i in triangle if i in pentagon and i in hexagon]
print(temp) |
from lol_sift.features_utils import find_champion_in_picture
from lol_sift.lol_window_utils import (
select_lol_window,
get_champion_select_image,
click_champion_select,
)
|
import enum
import time
from datetime import timedelta
from uuid import uuid4
import boto3
from celery.decorators import periodic_task
from celery.schedules import crontab
from django.conf import settings
from django.core.files.storage import default_storage
from django.core.mail import EmailMessage
from django.templa... |
from PIL import Image
from six import BytesIO
def image_from_bytes(bytes_):
return Image.open(BytesIO(bytes_))
def png_format(image):
bytes_ = BytesIO()
image.save(bytes_, 'PNG')
return bytes_.getvalue()
class ScreenshotFromPngBytes(object):
def __init__(self, png_bytes):
self._png_by... |
'''
@Author: Fallen
@Date: 2020-04-03 13:51:25
@LastEditTime: 2020-04-03 14:06:49
@LastEditors: Please set LastEditors
@Description: 字符串判断文件格式
@FilePath: \day02\字符串判断文件类型练习.py
'''
'''
练习:
给定一个路径,上传文件(记事本txt或者是图片jpg,png)
如果不是对应格式的,允许重新指定上传文件,
如果符合上传的规定则提示上传成功
'''
#允许重复,就是个循环,一般是死循环然后设置个跳出机制,可以写成一个函数
def upfilePic(... |
a =(ord("0"))
print(a)
print(ord("c"))
print(ord("&"))
|
# missed solution completely. needed help.
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
contains_one = False
num_len = len(nums)
for i in range(num_len):
if nums[i] == 1:
c... |
#-*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
so = 0
trig = 12
echo = 26
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(echo, GPIO.IN)
def sendsonic(dis):
so = 0
if dis < 8:
so = 1
elif 8 <= dis < 16:
so = 2
elif 16 <= dis < 24:
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 28 21:33:25 2017
@author: Akhil
"""
#!/usr/bin/python
#===============================================
# image_manip.py
#
# some helpful hints for those of you
# who'll do the final project in Py
#
# bugs to vladimir dot kulyukin at usu dot edu
#======... |
# Numericos
entero = 7
decimal = 7.5
otroDecimal = 7.0
otroDecimal = float(7.02)
# Cadenas
cadenaS = 'Holi'
cadenaC = "Boli"
cadenaS2 = "I'm Pato de Turing"
pruebaUno = cadenaS+" "+ cadenaC+""+str(decimal)
pruebaDos = entero + decimal
print(pruebaDos) |
#Ce module rassemble les fonctions destinées à l'affichage graphique des résultats
import matplotlib.pyplot as py
def print_instance(inst):
dep = inst[0]
cust = inst[1:]
py.plot(dep[0], dep[1], color='blue', marker='o')
for i in cust:
py.plot(i[0], i[1], color='red', marker='o')
def print_rou... |
"""
TECHX API GATEWAY
GENRIC WORKER CLASS TO API CALLS TO EXTERNAL SERVICES
CREATED BY: FRBELLO AT CISCO DOT COM
DATE : JUL 2020
VERSION: 1.0
STATE: RC2
"""
__author__ = "Freddy Bello"
__author_email__ = "frbello@cisco.com"
__copyright__ = "Copyright (c) 2016-2020 Cisco and/or its affiliates."
__license__ = "MIT"
# ==... |
from functools import reduce
from operator import iconcat
from collections import Counter
from babybertsrl import configs
MODEL_NAME = 'childes-20191206'
# load model-based annotations
srl_path = configs.Dirs.data / 'training' / f'{MODEL_NAME}_no-dev_srl.txt'
text = srl_path.read_text()
lines = text.split('\n')[:-1]... |
# Generated by Django 2.1.4 on 2018-12-19 11:27
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Contacts',
fields=[
('id', models.AutoField... |
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
# Credits######################################################
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.