text stringlengths 38 1.54M |
|---|
__author__ = "Quy Doan"
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(input_file,"r") as reader:
with open(output_file,"w") as writer:
num_of_test = int(reader.readline())
for test in range(num_of_test):
k,c,s = map(int,reader.readline().split())
... |
# Generated by Django 2.0.6 on 2018-06-28 12:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ntakibariapp', '0004_auto_20180627_2118'),
]
operations = [
migrations.AddField(
model_name='member',
name='sex',
... |
for循环语句
\1、for语句的结构:
Python语言中的for语句与其他高级程序设计语言有很大的不同,其他高级语言for语句要用循环控制变量来控制循环。Python中for语句是通过循环遍历某一序列对象(字符串、列表、元组等)来构建循环,循环结束的条件就是对象被遍历完成。
for语句的形式如下:
for <循环变量> in <循环对象>:
<语句1>
else:
<语句2>
else语句中的语句2只有循环正常退出(遍历完所有遍历对象中的值)时执行。
# 迭代式循环:for,语法如下
# for i in range(10):
# ... |
from django.conf.urls import url, include
from .views import all_features, create_feature, feature_detail, feature_upvote
urlpatterns = [
url(r'^$', all_features, name='features'),
url(r'^new/$', create_feature, name='new_feature'),
url(r'^(?P<pk>\d+)/$', feature_detail, name='feature_detail'),
url(r'up... |
# Generated by Django 3.0.7 on 2021-04-05 14:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
'''
Created on February 9th, 2018
author: Michael Rodriguez
sources: http://docs.fetchrobotics.com/
description: Module to monitor keyboard activity for ROS
'''
# External Imports
import rospy
# Local Imports
from std_msgs.msg import Int32
from geometry_msgs.msg import PointStamped
from visualization_msgs.msg import Ma... |
from typing import Callable, Dict, Any, Iterable, Tuple, List
import numpy
import pandas
from pandas import DataFrame, SparseDataFrame, Categorical
from modeling import categorical_util
class GridSearchCVResults:
def __init__(self,
params: Dict):
self.params = params
self.attrs:... |
#!/usr/bin/env python
import sys
sys.path.append("/home2/data/Projects/CWAS/share/lib/surfwrap")
import os
from os import path
from os import path as op
from surfwrap import SurfWrap, io
import numpy as np
import nibabel as nib
###
# Setup
strategy = "compcor"
scans = ["short", "medium"]
hemis = ["lh", "rh"]... |
"""
This module contains a function to download every one-minute time window
where there is an LFE recorded, stack the signal over all the LFEs, cross
correlate each window with the stack, sort the LFEs and keep only the best
We also save the value of the maximum cross correlation for each LFE
"""
import obspy
from ob... |
from flask import Blueprint, current_app, jsonify
from flask_restful import Api
from marshmallow import ValidationError
from myapi.extensions import apispec
from myapi.api.resources import TaskResource, TaskList, UserResource, UserList
from myapi.api.schemas import TaskSchema, UserSchema
blueprint = Blueprint("api", ... |
def func(a_list):
res = []
for i in range(2 ** len(a_list)):
combo = []
for j in range(len(a_list)):
if (i >> j) % 2 == 1:
combo.append(a_list[j])
res.append(combo)
return res
def main(range_len, length):
import random
lists = random.sample(range... |
from __future__ import print_function
from imutils.video.pivideostream import PiVideoStream
from picamera.array import PiRGBArray
from picamera import PiCamera
import argparse
import imutils
import time
import cv2
# initialize the camera and stream
camera = PiCamera()
camera.resolution = (640, 480)
rawCapture = PiRG... |
"""
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have
to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs,
return the ordering of courses you shou... |
from collections import Counter
# ransom note
class Pleb:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
magazine_ctr = Counter(magazine)
for char in ransomNote:
if magazine_ctr[char] > 0:
magazine_ctr[char] -= 1
else:
ret... |
import os
import time
from collections import defaultdict
import tensorflow as tf
import tensorflow.keras.layers as layers
import tensorflow_probability as tfp
import numpy as np
GRIDS = {16: (4, 4), 32: (8, 4), 64: (8, 8), 128: (16, 8), 256: (16, 16),
512: (32, 16), 1024: (32, 32), 2048: (64, 32)}
class W... |
import os
import re
import glob
import pickle
import pandas as pd
from utils.transform_utils import *
# Get all posts within the data directory
posts = glob.glob('data/posts/*.p')
# Iterate over all posts within a class
for fp in posts:
# Load each post into a DataFrame and store its networkid
df = pd.DataFr... |
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.ticker as mtick
df = pd.read_csv(r'Medical\\DataCleaning\\DataTransformation\\KivaLoanProject\\kiva_data.csv')
print(df.head(25))
# Creates the figure
f, ax = plt.subplots(figsize=(15, 10))
# Plot the data
sn... |
import sys
from explain.tf2.deletion_scorer import summarize_deletion_score_batch8, show
def main():
dir_path = sys.argv[1]
deletion_per_job = 20
deletion_offset_list = list(range(20, 301, deletion_per_job))
summarized_result = summarize_deletion_score_batch8(dir_path, deletion_per_job, deletion_offs... |
import os
import ezexif
import shutil
os.chdir("/Users/chilly/Desktop/python/yequ/崩溃的阿文/lesson06")
downloadPath = "照片"
photoList = os.listdir(downloadPath)
for photo in photoList:
photoPath = os.path.join(downloadPath, photo)
exifInfo = ezexif.process_file(photoPath)
# 获取拍摄时间
takeTime = exifInfo["EXIF... |
import re
class ValidateEmail():
def __init__(self, email, users):
self._email = email
self._users = users
def validate(self):
if self._email in self._users:
print("student was already registered, please use a different email\n")
return False
else:
... |
import logging
import os
import shutil
from collections import OrderedDict, namedtuple
from pathlib import Path
from uuid import uuid4
from sqlalchemy.exc import IntegrityError
from tqdm import tqdm
import pandas as pd
from common import DAL
from common.DAL import ModelPartialScore
from common.utils import VerboseTim... |
from setuptools import setup
setup(
name='odc_apps_cloud',
version='1',
author='Open Data Cube',
author_email='',
maintainer='Open Data Cube',
maintainer_email='',
description='CLI utils for working with objects/files the cloud',
long_description='',
license='Apache License 2.0',... |
"""
Simple calculator without using `eval`
"""
import operator
from textwrap import dedent
MATH_OPS = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
def eval_equation(equation):
"""
Evaluate the equation
"""
number1, opr, number2 = equation.... |
# this file and implementation of static HTML based off of Amos Omondi's tutorial on scotch.io: https://scotch.io/tutorials/working-with-django-templates-static-files
#used to render pages and pass necessary python parameters to them.
from django.shortcuts import render
from django.views.generic import TemplateView ... |
#!/usr/bin/env python
import roslib; roslib.load_manifest('localization')
from localization import *
from localization.bag import get_dict
from assignment_3.geometry import *
from assignment_4.laser import *
from math import pi
import tf
from tf.transformations import euler_from_quaternion
import argparse
import rosp... |
import sys
levens = 6
woord = "pythonp"
te_raden = list(woord)
geraden = list("_"*len(woord))
def antwoord():
result = ""
while result == "_" or len(result) != 1 or result.isdecimal():
result = input("Geef mij een letter: ")
return result
while levens > 0:
print("Geraden woord: ", "".join(g... |
import numpy as np
def Mutate(chromosome, mutationProbability):
"Mutates the chromosome"
nGenes = chromosome.size
mutatedChromosome = chromosome.copy()
for i in range(nGenes):
r = np.random.rand()
if r < mutationProbability:
mutatedChromosome[i] = 1 - chromosome[i]
re... |
# -*- coding: utf-8 -*-
import os
import logging
import time
import thread
from woof.transactions import TransactionLogger
logging.basicConfig(
format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s',
filename='/tmp/kafkalog',
level=logging.INFO
)
logger = logg... |
from random import randint
import random
class Tree:
def __init__(self, parent=None, name=''):
self.name = name
self.parent = parent
self.value = 0
self.children =[]
self.probability = round(random.random(), 2)
self.probabilityGivenOne = round(random.random(), 2) # based on the parent value
self.probabi... |
import csvReader
def testIsJustNumbersOnNumbers():
listOfStrings = ['22.4', '23.9']
assert csvReader.isJustNumbers(listOfStrings)
def testIsJustNumbersOnBadNumbers():
listOfStrings = ['abc', '23.9']
assert csvReader.isJustNumbers(listOfStrings) == False
def testGetNumbers():
listOfStrings... |
# coding: utf-8
import sys
import os
import re
import random
import time
import urllib
from sklearn.cluster import AffinityPropagation, MeanShift, KMeans, Birch
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import numpy as np
from collections import Counter
class Sekitei:
... |
class Solution:
def findMin(self, nums: List[int]) -> int:
res=nums[0]
for i in nums:
if i < res:
return i
return res |
from flask import Flask, redirect, url_for, request,render_template
app = Flask(__name__)
n=''
def print(*args):
global n
for i in range(len(args)):
if i>0:
n+=','
n+=str(args[i])
n+='\n'
#@app.route('/success/<name>')
def success(name):
global n
n=''
... |
from django.shortcuts import render
from blogs.models import Blog
def index(request):
blogs = Blog.objects.order_by('-post_date')[:8]
context = {
'blogs': blogs
}
return render(request, 'pages/index.html', context)
def about(request):
return render(request, 'pages/about.html')
|
#!/usr/bin/env python
PACKAGE = "openpose_ros_node_cfg"
from dynamic_reconfigure.parameter_generator_catkin import *
gen = ParameterGenerator()
gen.add("show_skeleton", bool_t, 0, "Boolean wether to show the openpose skeleton", True)
gen.add("show_bbox", bool_t, 0, "True to visualize bounding box around... |
import requests
import json
class yandexTranslateApi:
def __init__(self,token):
self.__token=token
self.__get_directions_url="https://translate.yandex.net/api/v1.5/tr.json/getLangs?key="
self.__direct_translate_url="https://translate.yandex.net/api/v1.5/tr.json/translate?key="
se... |
# DoDirectory.py
#
#CheckIfExists 160306
#Create 160306 */ |
import pygame, sys, time, random
from pygame.locals import *
from Class_Button import button
# key description
kdc = '''
Key description:
press key A to move the red car to racetrack 1
press key D to move the red car to racetrack 2
press key < to move the yellow car to racetrack 3
press key > to move t... |
from datetime import datetime, timezone
import pytest
from website_monitor.status import Status
class TestStatus:
"""
Test the Status dataclass.
"""
def test_parsed_timestamp(self):
status = Status('http://www.ya.ru', '2021-02-10T18:04:28.023922+00:00', 200, 0.358636, True)
assert st... |
import json
rapper_dict = {'first': 'Marshall', 'last': 'Mathers'}
rapper_dict['City'] = 'Detroit'
rap_dict = {}
rap_dict['Best Rapper Ever'] = rapper_dict
rap_json = json.dumps(rap_dict)
print()
print(rap_json)
songs = ['Lose Yourself', 'Without Me', 'I Will']
rapper_dict['songs'] = songs
rapper_json = json.dump... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-01 12:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... |
#!/usr/bin/env python
import rospy
import roslib
from geometry_msgs.msg import Point
import tf
from aruco_msgs.msg import MarkerArray
from std_msgs.msg import Float64
class get_pose():
def __init__(self):
rospy.init_node('get_pose',anonymous=False)
self.aruco_marker = {}
self.cam_pose = Point()
self.posepub ... |
"""
Permutations
============
A simple implementation of permutations on `n` elements.
Authors
-------
* Chris Swierczewski (Feb 2014)
"""
class Permutation(object):
"""A permutation on `n` elements.
Methods
-------
is_identity()
Returns `True` if the Permutation is the identity.
index(... |
# Generated by Django 3.1.2 on 2021-03-25 06:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0041_remove_product_updated_at'),
]
operations = [
migrations.AlterField(
model_name='category',
name='or... |
from gpiozero import *
from picamera import *
from time import *
from guizero import *
def take_picture():
global output
#name of file
output = strftime("/home/pi/mypibooth/image-%d-%m %H:%M:%S.png", gmtime())
#take 3 pics
for i in range(3):
sleep(3)
camera.capture(output)
#GPIO button asignment
take... |
# Generated by Django 2.1.8 on 2019-08-09 17:36
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('locally', '0004_auto_20190810_0103'),
]
operations = [
migrations.RemoveField(
model_name='comm... |
import os
exec(open("_main2.py").read())
db = 1 #REPORTING DATABASE
database = ''
delete_staging = True
print_internal = True
print_details = False
run_warehousing = True
time_type = 'days'
time_unit = 30
#CAN ONLY SEND DATES TO RINGCENTRAL, SO THE TIME COMPONENT NEEDS STRIPPING OUT
start_date = now.replace(hour... |
# Copyright 2019 Yelp 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 or agreed to in writing, so... |
## This file alters the game described in simpy_rollout_fire_smdp.py
# Here, agents receive a local observation (location,strength,status,interest) for 5 closest fires
# Also, each fire gets random number of UAV-minutes needed to extinguish it, where the mean is a
# function of fire level
# Rewards are equal to the fi... |
# set is an unordered and sorted collection of items with no duplicate
sets = {1,2,3}
sets = {1,"two",3.00,(2,3)}
list1 = [1,4,5,1,4,5]
sets = set(list1)
print(list1,sets)
# create a empty set
sets = {}#its a dictionary
sets = set() # we use set function to create a empty set
# Add and update in set (index has not ... |
#!/usr/bin/env python
import sys
import Sex
import GenieDB
import Date
# Configuration Control ###############################################
if 1: # for folding
# These settings affect how the program operates. Some are for
# debugging. Others are optional, but produce important results.
# Disambiguate suc... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Blueprint
cart_bp = Blueprint("cart", __name__, url_prefix="/cart")
from cart.views import *
|
import uuid
from django.db import models
# Create your models here.
class Quiz(models.Model):
title = models.CharField(blank=False, max_length=40)
uuid = models.CharField(max_length=40, null=True, blank=True, unique=True)
def __init__(self, *args, **kwargs):
super(Quiz, self).__init__(*args, **k... |
def setup():
size(300,300)
background(255)
smooth()
#noLoop()
def draw():
background(255)
strokeWeight(30)
stroke(100)
line(mouseX,mouseY, 200, 200)
|
# iterative solution
def sumOfNumbersIterative(number):
sum = 0
for item in range(number + 1):
sum += item
return sum
print(sumOfNumbersIterative(5))
# non-iterative solution
def sumOfNumbersNonIterative(number):
return number * (number + 1) / 2
print(sumOfNumbersNonIterative(5))
|
import sys
import math
import numpy as np
import matplotlib
#matplotlib.rcParams['mathtext.fontset'] = 'stix'
#matplotlib.use('PDF')
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import rc
#from matplotlib.collections import LineCollection
#rc('text',usetex = False)
def dot_product(a1,a2):
... |
from sys import stdin,stdout
t=int(stdin.readline())
l=[0]
c=0
x=1
while x<20002:
l.insert(x,0)
x+=1
line=stdin.readline()
for a in line:
if a== " ":
continue
if(t<=0):
break
t-=1
a=int(a)
l[a]=1
if int(l[a-1])==int(l[a+1]):
if int(l[a-1])>0:
... |
d = int(input('Quantos dias pretende alugar? '))
diaria = d*100.00
km = float(input('Quantos kms rodados? '))
kms = (km*1.50)+diaria
print('O total do aluguel do carro custará \033[0;31mR${:.2f}\033[m!'.format(kms))
|
tableau_game_character_sheet = 0
tableau_game_inventory_window = 1
tableau_game_party_window = 2
tableau_troop_note_alpha_mask = 3
tableau_troop_note_color = 4
tableau_troop_character_alpha_mask = 5
tableau_troop_character_color = 6
tableau_troop_inventory_alpha_mask = 7
tableau_troop_inventory_color = 8
tableau_troop_... |
# DP 简单题
class Solution:
"""
@param m: positive integer (1 <= m <= 100)
@param n: positive integer (1 <= n <= 100)
@return: An integer
"""
def uniquePaths(self, m, n):
# write your code here
dp = {} # using a hashtable
for i in range(m):
for j in range(n):
... |
m = int(input("ingrese el primer numero: "))
n = int(input("ingrese el segundo numero: "))
p = 0
while m > 0:
m = m - 1
p = p + n
print ('El producto de m y n es', p)
|
# -*- coding: utf-8 -*-
import logging
from Pyside2 import QtWidgets, QtCore
class EdlTable(QtWidgets.QTableView):
itemSelectionChanged = QtCore.Signal()
def __init__(self, rows, model):
super(EdlTable, self).__init__()
self.model = model
self.setModel(self.model)
self.model.... |
import wx
import wx.lib.ogl as ogl
class AppFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__( self,
None, -1, "Demo",
size=(300,200),
style=wx.DEFAULT_FRAME_STYLE )
sizer = wx.BoxSizer( wx.VERTICAL )
... |
from random import randint
from orator.seeds import Seeder
from models.project import Project
class ProjectTableSeeder(Seeder):
def projects_factory(self, faker):
"""
Defines the template of user test records
"""
return {
'name' : faker.company(),
'descripti... |
# Generated by Django 3.1.5 on 2021-01-21 17:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('FPT', '0012_auto_20210120_0303'),
]
operations = [
migrations.RemoveField(
model_name='trainee',
name='department',
... |
__all__ = ['UtilClasses']
from UtilClasses import Location
from UtilClasses import ModemResult
from UtilClasses import SMS
from UtilClasses import RWLock
|
from main.views import main_response
from django.urls import path
urlpatterns = [
path('', main_response, name='main_response'),
]
|
from rest_framework import permissions, viewsets
from similarities.utils import get_similar
from .models import Artist
from similarities.models import UserSimilarity, KnownArtist
from .serializers import ArtistSerializer, SimilaritySerializer, KnownArtistSerializer
from bandcamp import tasks as bandcamp_tasks
MIN_TRA... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Copyright Bernardo Heynemann <heynemann@gmail.com>
# Licensed under the Open Software License ("OSL") v. 3.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.opensource.org/lic... |
from functools import wraps
def method_decorator_adaptor(adapt_to, *decorator_args, **decorator_kwargs):
def decorator_outer(func):
@wraps(func)
def decorator(self, *args, **kwargs):
@adapt_to(*decorator_args, **decorator_kwargs)
def adaptor(*args, **kwargs):
... |
def gcdIter(a, b):
c = a + b
while c > 0:
if a % c == 0 and b % c == 0:
return c
c -= 1
return 1
|
class Student:
def set_student(self,rollno,name,total):
self.rollno=rollno
self.name=name
self.total=total
def print_student(self):
print(self.rollno)
print(self.name)
print(self.total)
obj=Student()
obj.set_student(10,"Sarath",100)
obj.print_student() |
#!/usr/bin/env python
#coding:utf-8
# Weather forecast
# libdoor weather API, 2016/12
import urllib2, sys
import json
import aitalk
import audioplayer
from pprint import pprint
citycode = '270000' #Osakaの都市コード
resp = urllib2.urlopen('http://weather.livedoor.com/forecast/webservice/json/v1?city=%s'%citycode).r... |
import tensorflow as tf
def H0(normals):
B, C, L = normals.shape.as_list()
# return tf.ones([B, 1, L], dtype=tf.float32)
return tf.ones_like(normals, dtype=tf.float32)[:, 0:1, :]
def H1(normals):
return normals[:, 1:2, :]
def H2(normals):
return normals[:, 2:3, :]
def H3(normals):
return... |
#Basic Calculator
#HackerRank Pythonista Contest
#Created by Brandon Morris 11/1/2014
x = float(input())
y = float(input())
print("%.2f" % (x + y))
print("%.2f" % (x - y))
print("%.2f" % (x * y))
print("%.2f" % (x / y))
print("%.2f" % (x // y)) |
T = int(input())
for i in range(1, T+1):
N = int(input())
A = list(map(int, input().split()))
diff = A[1] - A[0]
count = 2
maxcount = 2
for j in range(2, N):
if A[j] - A[j-1] == diff:
count += 1
maxcount = max(maxcount, count)
else:
diff = A[j]... |
HTML_TABLE = """
<table class='center' height="50%" width="100%" align=center cellpadding ="25">
<tr>
<th><h2>Question</h2></th>
<th><h2>Answer</h2></th>
</tr>
{table_rows}
</table>
"""
TABLE_CSS = """.center {
margin-left: auto;
margin-right: auto;
}
"""
BUTTON_CSS = """
.mybutton {
lef... |
"""
This script allows you to verify if the imagenet ILSVRC images you downloaded
are correct (i.e., images are not corrupted). You can run them in parallel if
you have multiple machines.
We found that there is one image (an image that contains a monkey) that is
actually a valid JPEG image, but cannot be read in pytho... |
#coding=utf-8
import time,sys,os,win32gui, win32ui, win32con,traceback
from sensetimebi_productstests.Sharedscript.SharedGetYamlConfigData import DataGetConfig
from PIL import Image
import pytesseract
class images_dispose(object):
def __init__(self):
'''
'''
getConfig = DataGetConfig()
... |
#!/usr/bin/python
import os, glob, subprocess, sys
def clamp(v, mn, mx):
return min(mx, max(mn, v))
def mix(a, b, m):
return a * (1.0-m) + b * m
def smoothstep(edge0in, edge1in, xin):
edge1 = float(edge1in)
edge0 = float(edge0in)
x = float(xin)
# Scale, bias and saturate x to 0..1 range
ret = edge1
if edge1 ... |
# This file is part of the calculator_oop.py Task
# import Calculator class so we can inherit from it
from calculator_oop import Calculator
import math
# Create class that inherits from Calculator
class FuncCalculator(Calculator):
# Calculate area of circle (pi*radius^2) and round to 2 decimal points
def ar... |
#Măriuca ţine evidenţa iepurilor din crescătorie. Ea îşi notează câţi iepuri sunt la
#începutul fiecărei luni, câţi au murit şi câţi s-au născut în cursul fiecăei luni. Puteţi să
#realizaţi un program care, primind aceste date, să afişeze la sfârşitul fiecărei luni câţi
#iepuri sunt în crescătorie? Exemplu : Date de... |
#George West
#14-10-14
#stars
number = int(input("How many stars do you want per row? "))
rows = int(input("How many rows do you want? "))
list1=''
for count in range(number):
list1= list1 + '*'
for count in range(rows):
print(list1)
|
from django.test import TestCase
from django.urls import reverse
from project_core.tests import database_population
class ChangelogTest(TestCase):
def setUp(self):
self._client_management = database_population.create_management_logged_client()
def test_get(self):
response = self._client_mana... |
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need
# fine tuning.
buildOptions = dict(packages = [], excludes = [])
msiOptions = dict(
add_to_path = True,
all_users = True
)
base = 'Console'
executables = [
Executable('nitropy.py', base=base)
]
setup(na... |
# coding=utf-8
from typing import Text, List, Any, Optional
from abc import ABCMeta
from modelscript.base.issues import (
Issue,
LocalizedSourceIssue,
Level,
WithIssueList,
IssueBox)
import re
from modelscript.base.annotations import (
Annotations
)
DEBUG = 0
#TODO:4 The type ModelElement sho... |
#!/usr/bin/env python
"""Run doctests"""
import doctest
import re
import sys
import unittest
from . import engine, fetchers
# From https://dirkjan.ochtman.nl/writing/2014/07/06/single-source-python-23-doctests.html
class Py23DocChecker(doctest.OutputChecker):
"""Python 2&3 compatible docstring checker"""
#py... |
import sys, os
import time
import urllib2
import simplejson
sys.path.append('/home/mednet/build')
os.environ['DJANGO_SETTINGS_MODULE'] ='quicksms.settings'
from quicksms.sms.models import Incoming,Outgoing,Pull
import pygsm
from datetime import datetime
modem = pygsm.GsmModem(port="/dev/ttyUSB0", baudrate=115200... |
from tools import shell_cmd
import json
from log import logger
import os
from config import config
import ConfigParser
def getremote_cpu_model(ip):
put_scrit_args = "scp %s/bin/get_cpu_mode.py %s:/tmp/" % (os.getcwd(), ip)
create_cpu_json_args = "python /tmp/get_cpu_mode.py %s " % ip
shell_cmd.shell_run(p... |
{
'verbose': True,
'from_pickle': True,
'pickle_data': 'images-50000-(20, 20)-2016-11-28 10-05-07.471249.p',
'folder': '\Train',
'img_size': (20, 20),
}
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-11-21 11:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('company', '0073_auto_20180709_1001'),
]
operations = [
migrations.AlterFie... |
import click
# import pandas as pd
# from datetime import datetime
# from faker import Faker
from snakeeyes.app import create_app
from snakeeyes.extensions import db
from snakeeyes.blueprints.contact2.models import Projects
from snakeeyes.blueprints.user2.models import User2
# Create an app context for the database... |
while True :
byk = int(input())
if byk==0:
break
hls = []
hls1 = []
for i in range (byk):
kl = input()
hls1.append(kl)
data = kl.split(" ")
for j in range(len(data)):
if j ==0 :
continue
if data[j] not in hls :
... |
'''
на экран по одному выводятся 20 вопросов типа:
Чему равно произведение чисел 4 и 9?
Множители (числа 2, 3, …, 9) задаются случайным образом с использованием
функции randint().
Пользователь должен ввести ответ. Этот ответ оценивается как правильный или нет
(проводится подсчет количества правильных ответов, окончател... |
import os
import re
import requests
import threading
import time
# url = 'https://www.77nt.com/50750/'
# url = 'https://www.77nt.com/50750/12068063.html'
# url = 'https://www.77nt.com/107094/34439391.html'
text_index_list = []
lock = threading.Lock()
def get_date(url):
html = requests.get(url)
html_bytes = ... |
# _*_ coding: utf-8 _*_
__author__ = 'onewei'
__date__ = '2018/1/31 6:41'
import hashlib
def get_md5(url):
if isinstance(url, str):
url = url.encode("utf-8")
m = hashlib.md5()
m.update(url)
return m.hexdigest()
if __name__ == '__main__':
print(get_md5("http://jobbole.com"))
|
"""
!sudo ./darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg
!sudo ./darknet detect cfg/yolov3-tiny.cfg yolov3-tiny_final.weights data/1.jpg
from google.colab import drive
drive.mount('/content/drive')
!cd /content/drive/My Drive
!sudo ./darknet detect cfg/yolov3-tiny.cfg yolov3-tiny_final.weights data/2... |
# -*- coding: utf-8 -*-
import os
import shutil
from xml.sax import make_parser
from xml.sax.handler import feature_namespaces
from xml.sax import saxutils
from xml.sax import ContentHandler
from xml.sax.saxutils import XMLGenerator
from xml.sax.saxutils import escape
from dicht_trefw import add_jaar, trefwoor... |
detected_called_method = "cloned.put(buffer.duplicate().append('a'));"
n1 = detected_called_method.find('.')+1
print('n1: ' + str(n1))
m1 = detected_called_method[n1:]
k1 = m1.find('(')+1
print('m1: ' + str(m1))
print('k1: ' + str(m1[:k1-1]))
n2 = m1.find('.')+1
print('n2: ' + str(n2))
m2 = m1[n2:]
print('m2: ' + str... |
from .models import City
from .serializers import CitySerializer
from rest_framework import generics
class CityListIndex(generics.ListCreateAPIView):
queryset = City.objects.all()
serializer_class = CitySerializer
class CityElementShow(generics.RetrieveAPIView):
serializer_class = CitySerializer
look... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.