text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 4 20:17:16 2020
@author: han
"""
import tensorflow as tf
import numpy as np
import os
import skimage
import keras
from sklearn.utils import shuffle
import matplotlib.pyplot as plt
def load_small_data(dir_path,m,flag):
images_m=[] ##新建一个空列表用于存放图片数集... |
import pygame
import sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption("Drawing stuff")
#Palette of colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
PURPLE= (... |
# TODO: complete in free time
def binary(_list, _element):
found = False
start_index = 1
end_index = len(_list) - 1
while 1:
center_index = (end_index - start_index)/2
element_from_center = int(_list[center_index])
if _element == element_from_center: # has center
... |
""" Add directory to path, tests should import from this file. """
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from the_exif_mutalator import cli, logging_config, tem # pylint: disable=wrong-import-position,unused-import
|
#!/usr/bin/env python
from collections import namedtuple
# Application data model
LineItem = namedtuple('LineItem', ['product_id', 'quantity'])
Order = namedtuple('Order', ['line_items', 'discount_code'])
Discount = namedtuple('Discount', ['code', 'percentage', 'type', 'product_ids'])
Product = namedtuple('Product', ... |
# -*- coding: utf8 -*-
# from app import bcrypt, db
from app import db
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import *
from sqlalchemy.dialects import mysql
class NewsBasic(db.Model):
__tablename__ = 'news_basic'
__table_args__ = {'schema': 'study'}
id = db.Column('id', mysql.... |
def binarySearch(A,B,n):
low,high = 0,n
while(low < high):
mid = low + (high-low+1)//2
flag = 1
for index in range(mid):
if(A[index] > B[n+index-mid]):
flag = 0
if(flag == 0):
high = mid - 1
else:
low = mid
return ... |
# -*- coding: utf-8 -*-
# Resolves move url from most of hosting websites
import re, sys
class Streamango():
def decode(self, encoded, code):
#from https://github.com/jsergio123/script.module.urlresolver - kodi vstream
_0x59b81a = ""
k = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" Contains all partitioner errors
"""
__all__ = [
'BadKeyType',
'OutsideInstanceNumber'
]
class BadKeyType(TypeError):
"""BadKeyType
This error was raised in KeyPartitioner when key was not bytes
"""
class OutsideInstanceNumb... |
def a():
return 1
def b():
x=a()
print(x)
b() |
from common.run_method import RunMethod
import allure
@allure.step("极运营/营销中心/商品中心/新建编辑商品")
def goods_course_saveGoods_post(params=None, body=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:... |
import pytest
from pageObjects.LoginPage import LoginPage
from utilities.readProperties import ReadConfig
from utilities.customLogger import CustomLogger
class TestLogin001:
baseURL = ReadConfig.getURL()
username = ReadConfig.getUname()
password = ReadConfig.getPass()
logger = CustomLogger.customerl... |
# coding: utf-8
import os, io, sys, tarfile, zipfile
import numpy as np
from PIL import Image
"""
Compression file should be the following architecture.
Compression file
|-- Label A
| |-- image file
| |-- image file
|-- Label B
| |-- image file
| |-- image file
"""
extentions = ["jpg", "J... |
# Generated by Django 2.2.3 on 2019-07-04 10:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('skolr', '0003_auto_20190704_0710'),
]
operations = [
migrations.AddField(
model_name='teacher',
name='typ',
... |
# FUNCTIONS TO CHECK COLLECTED BEHAVIORAL DATA FOR ATTENTION AND MEMORY EXPERIMENT
import os
import pickle
import pandas as pd
from matplotlib import pyplot as plt
# Functions to Aggregate Subject Data and Verify Correct Stimuli were Presented
def sum_pd(subdir):
'''
input: subject directory (string)
out... |
# -*- coding: utf-8 -*-
from collections import Counter
class Solution:
def hasGroupsSizeX(self, deck):
counts = Counter(deck).values()
min_count = min(counts)
if min_count == 1:
return False
partition_size = min_count
for count in counts:
remaind... |
# Linear Queue
import array
class LinearQueue:
def __init__(self, capacity):
self.capacity = capacity
self.front = 0
self.rear = 0
self.array = array.array('l', [0]*capacity)
def put(self, value):
if self.rear == self.capacity:
return False
self.arr... |
# -*- coding: utf-8 -*-
"""
Avaliacao.test_models
~~~~~~~~~~~~~~
Testa coisas relacionada ao modelo.
:copyright: (c) 2011 by Felipe Arruda Pontes.
"""
import datetime
from django.test import TestCase
from model_mommy import mommy
from Avaliacao.models import Avaliacao, TemplateAvaliacao
from Materia.T... |
from __future__ import print_function
import copy
from collections import OrderedDict
from functools import partial
from operator import itemgetter as _itemgetter
import six
# TypedNamedTuple is largely structured the way the code generated by
# NamedTuple is structured. However, by itself it is empty. When a
# ch... |
f = open("edinput.txt")
lines = f.readlines()
def update_position(min_v, max_v):
return min_v + (max_v - min_v) // 2
higher = -1
ids = []
for line in lines:
min_row = 0
max_row = 127
min_col = 0
max_col = 7
for c in line:
if c == 'F':
max_row = update_position(min_row, max_row)
elif c == 'B':
min_row ... |
from dependency_injector import containers, providers
from core.env import Environment
from core.event_hub import EventHub
class Container(containers.DeclarativeContainer):
# database_client = providers.Singleton(
# init_db,
# db_name='database.db',
# migrations_dir='repository/migrations... |
# -*- coding: utf-8 -*-
"""
This package contains object classes and functions to access the Ionic Liquids Database - ILThermo (v2.0)
from NIST (Standard Reference Database #147) within Python.
Concept
-------
The :func:`pyilt2.query` function uses the *requests* module to carry out the query on the NIST server.
The ... |
'''David Naccache based Identity-Based Encryption
| From: "David Naccache Secure and Practical Identity-Based Encryption Section 4"
| Available from: http://eprint.iacr.org/2005/369.pdf
* type: encryption (identity-based)
* setting: bilinear groups (asymmetric)
:Authors: Gary Belvin
:Date: 06/2011
'''
from c... |
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import Keys
from pages.base_page import BasePage
from utils.locators import ChatPageLocator
# Processing Functions
def message_sent_or_pending(label):
if label == 'Sent':
return 'Yes'
elif label == 'Deliv... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from urllib.request import urlopen
from urllib.parse import quote
from bs4 import BeautifulSoup
import sys, os, glob
from reportlab.platypus import SimpleDocTemplate
from reportlab.lib.pagesizes import A4, landscape
from utils import str2bool, make_url, parse_inputs, get_re... |
import pytest
from tests.mocks import MockChannel
from tests.output_betterproto.import_service_input_message import (
RequestResponse,
TestStub,
)
@pytest.mark.asyncio
async def test_service_correctly_imports_reference_message():
mock_response = RequestResponse(value=10)
service = TestStub(MockChanne... |
class hand:
"""
models a poker hand
"""
def __init__(self):
self.hand = []
def deal_poker_hand(self, deck):
"""
this function adds 5 cards from the deck to the hand
:param deck: deck that cards are being drawn from
:return:
"""
for i in ran... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 12:05:17 2015
@author: HSH
"""
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Inte... |
import math,string
import numpy as np
import time
import __builtin__
#
# MATLAB-like tic/toc for convenience
#
_tics = {None: 0.0}
def tic(id=None):
global _tics
now = time.time()
_tics[id] = now
return now
def toc(id=None):
global _tics
now = time.time()
return now - _tics[id]
#########... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import sys
class FunctionalTest(StaticLiveServerTe... |
#Create Pandas dataframe from the DarkSage output G['']
import pandas as pd
import numpy as np
# This is a way to converte multi dimensional data into pd.Series and then load these into the pandas dataframe
Pos = []
for p in G['Pos']:
Pos.append(p)
Pos_df = pd.Series(Pos, dtype=np.dtype("object"))
Vel = []
for ... |
# -*- coding: utf-8 -*-
num=int(input())
sum=1
for i in range(1,num+1):
sum=sum*i
print(sum) |
# File: hw3_part4.py
# Author: Joel Okpara
# Date: 2/21/2016
# Section: 04
# E-mail: joelo1@umbc.edu
# Description: This program takes a tempurature from the user
# and calculates the state of water at that temperature
def main():
# The Freezing point in celsius is 0 degrees
# The Boiling point in celcius is 100 degr... |
from django.contrib import admin
from .models import Dog, Breed
# Register your models here.
@admin.register(Dog)
class DogAdmin(admin.ModelAdmin):
list_display = ('name', 'age', 'breed', 'gender', 'color')
search_fields = ('name',)
@admin.register(Breed)
class Breed(admin.ModelAdmin):
list_display = ('na... |
from django.contrib.sites.models import Site
from django.db import models
from django.utils.translation import ugettext_lazy as _
class SiteSettings(models.Model):
site = models.OneToOneField(Site, related_name='settings')
class Meta:
verbose_name = _(u'site settings')
verbose_name_plural = ... |
# Generated by Django 2.2.13 on 2020-07-08 16:22
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='category',
old_name='title',
ne... |
from elasticsearch import Elasticsearch
import json
if __name__ == "__main__":
app_name_set = set()
es_client = Elasticsearch(['localhost:9200'])
index='topic'
response = es_client.search(
index='topic',
body={
"size": 2900,
"query": {
"match_all"... |
import matplotlib.pyplot as plt
from numpy import *
from random import random
class kalman(object):
def __init__(self, x0, p0, a, b, c, vv, vw):
self.x_ = 0 # A priori estimate state
self.x = x0 # A posteriori estimate state
self.p_ = 0 # A priori error covariance mat... |
from django.shortcuts import render
from .models import Informaciones
from django.views import generic
# Create your views here.
class InformacioneListView(generic.ListView):
model = Informaciones
template_name='Naruto.html'
context_object_name='Informaciones_list'
|
#!/usr/bin/python3
import pytest
import os
import urllib
# from .app import app as myapp
from .helpers import Vocabulary, FileManager, EpithetGenerator
from flask import Flask
from flask_testing import LiveServerTestCase
from unittest.mock import patch
dir_path = os.path.abspath("../../resources")
path_json = os.p... |
from __future__ import division
#encoding:utf-8
import pandas as pd
import numpy as np
'''
功能:计算回归分析模型中常用的四大评价指标
'''
from sklearn.metrics import explained_variance_score, mean_absolute_error, median_absolute_error, r2_score
def calPerformance(y_true,y_pred):
'''
模型效果指标评估
y_true:真实的数据值
y_pred:回归模型预测的数据... |
#!/usr/bin/python
from os import getenv
from datetime import datetime, timedelta
from time import mktime
from email.Utils import formatdate
steps = ('Start', 'Weiter', 'Noch weiter', 'Ende')
path_info = getenv('PATH_INFO', '')
if len(path_info) >= 2 and path_info[0] == '/':
step = int(path_info[1:])
else:
st... |
from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msrest.authentication import CognitiveServicesCredentials
subscription_key = "cced4caa372c41deac94a069a20212f2"
endpoint = "https://kardel2.cognitiveservices.azure.com/"
credentials = CognitiveServicesCredentials(subscription_key)
tex... |
"""
Crie um programa que receba uma lista de inteiros e depois receba mais um inteiro f
após isso, mova todos os valores f da lista original para o final da lista.
Exemplo
Entrada Saída
[1, 2, 1, 4, 5, 1, 9], 1 [2, 4, 5, 9, 1, 1, 1]
"""
lista = []
index = 5
ocorrencias=0
cont = 0
for i in ra... |
# Generated by Django 2.2.3 on 2019-07-18 10:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("robbit", "0005_image_faves")]
operations = [
migrations.AlterField(
model_name="image",
name="faves",
field=models.Po... |
#Given envelopes = [[5,4],[6,4],[6,7],[2,3]],
#the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). |
#coding=utf-8
import zipfile
from . import main
from flask import render_template, redirect, url_for,request,jsonify,Response
from ..models.Photo import Photo
from ..models.Album import Album
# from config import ALLOWED_FILE
# allowed_files = ['jpg','png','zip','rar']
def filetype(filename):
return '.' in filenam... |
from typing import Dict, ClassVar
from qcodes.instrument_drivers.Lakeshore.lakeshore_base import (
LakeshoreBase, BaseOutput, BaseSensorChannel)
from qcodes.instrument.group_parameter import GroupParameter, Group
import qcodes.utils.validators as vals
# There are 16 sensors channels (a.k.a. measurement inputs) i... |
def quicksort(a, l, r):
if l >= r: return
mid = partition(a, l, r)
quicksort(a, l, mid - 1)
quicksort(a, m + 1, r)
def partition(a, l, r):
x = a[l]
j = i
if __name__ == '__main__':
numbers = map(int, input().split())
quicksort(numbers, 0, len(numbers))
print(numbers)
|
x=float(input("x= "))
if ((x%2==0)and(x/0==0)):
x=1
print("f(x): ",x)
elif(x<0):
x=0
print("f(x): ",x)
else:
x=(-1)
print("f(x): ",x) |
# -*- coding: utf-8 -*-
# $ pip install opencv-python
# $ pip install pillow
# Python3
# Usage: $ Python yolo-img-rotate-del_exif_windows.py image_folder
#
import sys
import cv2
import glob
import numpy as np
from PIL import Image
from PIL.ExifTags import TAGS
import shutil
import os
from os import listdir, getcwd
fro... |
import io
import os
import tarfile
import errno
import json
import zipfile
import os.path as osp
import numpy as np
import pandas as pd
from tensorflow.keras.utils import get_file
__all__ = [
'download_file', 'files_exist', 'makedirs', 'makedirs_from_filepath',
'extractall', 'remove', 'load_np... |
from graph_txt_files.txt_functions.graph_calculator import calc
from graph_txt_files.txt_functions.graph_property_names import property_names
import grinpy as gp
import os
import pickle
exceptions = ['randic_index',
'augmented_randic_index',
'harmonic_index',
'atom_bond... |
import os
import numpy
from typing import Optional
from phi import math
from phi.field import Scene
from phiml.math import shape, wrap, channel, spatial, batch
from phiml.backend import ML_LOGGER
@math.broadcast
def load_scalars(scene: Scene or str,
name: str,
prefix='log_',
... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
memo = {}
def act(i, buy):
if i >= len(prices):
return 0
if (i, buy) in memo:
return memo[(i, buy)]
if buy:
memo[(i, buy)] = max(act(i+1, False)-prices[... |
import numpy as np
import torch
import scipy.io as sio
from generate_environment import environment
import argparse
#### Samples for training propagation with changing source pixels
# Note: There are two version
def generateSamples(N, numTraining, steps):
# Parameters for environment generation
N2 = N**2
p = 0.... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @return the head node in the linked list
def swapPairs(self, A):
if not A or not A.next:
return ... |
#Author: James Nicholson
#Date: 5/30/2018
#Ask the user for a number.
# Depending on whether the number is even or odd,
# print out an appropriate message to the user.
num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
print("Number is odd.")
else:
print("Number is even")
#End Script
|
import unittest
import testutil
import shutil
import os
import hdbfs.ark
import hdbfs.imgdb
PRI_THUMB = 1000
PRI_DATA = 2000
class ImgDbCases( testutil.TestCase ):
def setUp( self ):
self.init_env()
data_config = hdbfs.imgdb.ImageDbDataConfig( self.db_path )
self.idb = hdbfs.ark.Stream... |
from django import forms
from lib.bootstrap_modal_forms.mixins import PopRequestMixin, CreateUpdateAjaxMixin
class BSModalForm(PopRequestMixin, forms.Form):
pass
class BSModalModelForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm):
pass
|
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
from . import lr_scheduler
from . import optim
def build_optimizer(cfg, model):
params = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
lr = cfg.SOLVER.BASE_LR
... |
# movement can cause death
# Dungeon V 1
import time
import random
import YesNo
import upDownLeftRight
import loading
import runDirection
def Enter():
if YesNo.yesNo('Would you like to enter the dungeon?'):
for i in range(101):
print('Loading dungeonV01...', i, '%', sep='', end='\r', flus... |
from django.db import models
# Create your models here.
class UserProfile(models.Model):
username = models.CharField(max_length=11, verbose_name='用户名', unique=True)
password = models.CharField(max_length=32, verbose_name='密码')
email = models.EmailField()
phone = models.CharField(max_length=11, verbose... |
from selenium import webdriver
import ctypes
class OpenFile:
def __init__(self, file_name: str, mode: str):
__tmp_file = open(file_name, 'r')
self.__tmp_file_content = __tmp_file.read()
__tmp_file.close()
self.__tmp_filename = file_name
try:
self.file_obj = open... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from flask_bcrypt import Bcrypt
from flask_migrate import Migrate
import stripe
import os
app = Flask(__name__)
stripe_keys = {
"secret_key": os.environ['STRIPE_SECRET_KEY'],
"publishable_key": os.envi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from werkzeug.wrappers import Response
from jinja2 import Environment, FileSystemLoader
template_path = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = Environment(loader=FileSystemLoader(template_path), autoescape=True)
def render_template(te... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 21:30:41 2020
@author: shaun
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import plotly.express as px
import plotly.graph_objects as go
def round_sig(x, sig):
return round(x, sig-int(floor(log10(abs(x))))-1)
#a function to calculate the... |
# part - 1 [Take variables with values of different types]
Name = "sara"
Age = 20
College = "Bhavans women college"
Height = 5.5
Obesity = False
# part - 2 [Print these in different lines and with appropriate messages (use .format()]
print("My name is {}.".format(Name))
print("I am {} years old.".format(Age))... |
import pymysql.cursors
connection = pymysql.connect(host=#'hostname',
user=#'username',
password=#'password',
db=#'dbname',
charset=#'utf8',
cursorclass=pymysql.cursors.DictCursor)... |
# Copyright 2018 Intel Corporation
#
# 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 wri... |
import os
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import random
from models import setup_db, Question, Category
QUESTIONS_PER_PAGE = 10
def paginate_questions(request, selection):
page = request.args.get('page', 1, type=int)
start ... |
"""Custom renderers for DRF."""
import csv
from io import StringIO
from rest_framework import renderers
class CSVRenderer(renderers.BaseRenderer):
"""Custom CSV renderer."""
media_type = "text/csv"
format = "csv"
def render(self, data, media_type=None, renderer_context=None):
with StringIO... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 10:07:23 2019
@author: nico
"""
import numpy as np
from scipy import signal as sig
import matplotlib.pyplot as plt
import control
import os
os.system ("clear") # limpia la terminal de python
plt.close("all") #cierra todos los graficos
num ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/11 下午8:33
# @Author : Lucas Ma
# @File : defunc
# 自定义函数
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
print(my_abs(-9))
# 如果想定义一个什么... |
def add_books():
title = input("Title: ").strip().title()
author = input("Author: ").strip().title()
year = input("Publishing year: ").strip()
book = f"{title},{author},{year},Not read\n"
with open('books.csv' , 'a') as reading_list:
reading_list.write(book)
def get_all_books():
boo... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from pants.backend.go.subsystems.golang import GolangSubsystem
from pants.backend.go.util_r... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:Segment.py
# @Author: Michael.liu
# @Date:2019/2/12
# @Desc: NLP Segmentation ToolKit - Hanlp Python Version
import os
import json
import random
import math
class FirstRec:
"""
初始化函数
seed:产生随机的种子
k: 选取的近邻用户个数
nitems 推荐电影
"""
de... |
from typing import List
from fastapi import FastAPI, Depends, Body
from sqlalchemy.orm import Session
from app.database import get_database
from app import crud
from app import types
#API main object
app = FastAPI()
#root endpoint
@app.get('/')
def root():
return {
'message':'Welcome on JM mobile ap... |
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import matplotlib.collections
def get_similar_producers(budget_revenue_dict, producer_name):
producers_list = budget_revenue_dict["producer_list"];
producer_index_value = producers_list.index(produce... |
from setuptools import setup, find_packages
import vds
setup(
name='vds',
version=vds.__version__,
url='https://github.com/maet3608/vft-data-sanitizer',
author='Stefan Maetschke',
author_email='stefan.maetschke@gmail.com',
description='Remove sensitive information from visual field test data',... |
#!/usr/bin/env python3
import netfilterqueue
import scapy.all as scapy
from scapy.layers import http
import argparse
from threading import *
from time import *
import re
connected_clients = []
blocked_websites = []
file_name = re.sub("\s\d\d:\d\d:\d\d", "", asctime())
log_file = open(os.path.abspath(os.getcwd())+"/L... |
import sys
import re
def process(line):
nums = sorted([int(i) for i in re.findall(r',(\d*);',line)])
l = 0
out = ""
for i in nums:
out += str(i-l)+","
l = i
print out[:-1]
with open(sys.argv[1],'r') as f:
for line in f:
process(line)
|
import os
from qtpy import QtWidgets
from pdsview import pdsview, channels_dialog, band_widget
FILE_1 = os.path.join(
'tests', 'mission_data', '2m132591087cfd1800p2977m2f1.img')
FILE_2 = os.path.join(
'tests', 'mission_data', '2p129641989eth0361p2600r8m1.img')
FILE_3 = os.path.join(
'tests', 'mission_dat... |
class SWBFConfig:
def __init__(self, filename):
self._filename = filename
self._properties = {}
def __getitem__(self, item):
if item in self._properties:
return self._properties
return None
def __setitem__(self, key, value):
self._properties[key] = value... |
#!usr/bin/env python
# -*- coding:utf-8 -*-
# 稳定版,添加中间数据的持久化,网络高负载情况,增加记录拒绝服务的请求数
import math
import sys
import time
import numpy as np
import random
import simu.greedy as greedy
import simu.greedy_computing as greedy_computing
import simu.greedy_down_bandwidth as greedy_down_bandwidth
import simu.greedy_up_bandwidth ... |
from .logo import logoplot
from .utils import AMINO_ACIDS, DNA |
__author__ = 'schneg'
from astroid import builder
from astroid.utils import ASTWalker
from astroid.exceptions import InferenceError
from astroid.inference import InferenceContext, CallContext
abuilder = builder.AstroidBuilder()
from collections import defaultdict
def infer(node):
try:
return list(node.in... |
#
# @lc app=leetcode.cn id=198 lang=python3
#
# [198] 打家劫舍
#
# @lc code=start
class Solution:
def rob(self, nums: List[int]) -> int:
"""
DP 自底向上
"""
n = len(nums)
dp_i_0, dp_i_1, dp_i_2 = 0, 0, 0
for i in range(n-1, -1, -1):
dp_i_0 = max(dp_i_1, dp_i_2 + ... |
#!/usr/bin/env python3
"""gem2log"""
from argparse import ArgumentParser
from ctypes import CDLL
from signal import SIGHUP, SIGINT, SIGQUIT, SIGTERM, signal
from sys import exit
from time import sleep
def log(msg):
"""
"""
print(msg)
if separate_log:
logging.info(msg)
def mlockall():
"""... |
class solution:
def maxSubArray(self,nums):
s = [nums[0]]*len(nums)
for i in range(1,len(nums)):
s[i] = max(nums[i],s[i-1]+nums[i])
max_s = s[0]
for is_s in s:
if is_s > max_s:
max_s = is_s
return max_s
if __name__ == '__main__':
sol = solution()
nums = [-1]
print(sol.maxSubArray(nums)) |
import os
from unittest import TestCase
from lxml import html
from basketball_reference_web_scraper.html import DailyBoxScoresPage
january_01_2017_html = os.path.join(os.path.dirname(__file__), './01_01_2017_box_scores.html')
class TestDailyBoxScoresPage(TestCase):
def setUp(self):
self.january_01_2017... |
import torch
import torch.nn as nn
import math
from torch.autograd import Variable
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Parameter
def nl():
return nn.LeakyReLU(0.2, inplace=True)
def conv(ic, oc, k, s, p, bn=True):
model = []
model.append(nn.Conv2d(ic, oc, k, s, ... |
import enum
import os
from pathlib import Path
import random
import re
from typing import (
Any,
Callable,
Iterable,
List,
Mapping,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
import appdirs
from yarl import URL
__all__ = [
'parse_api_version',
'get_config',
... |
#!/usr/bin/env python
# encoding: utf-8
#LTB:import tim_pageSetup;reload(tim_pageSetup);tim_pageSetup.main()
"""
tim_pageSetup.py
Created by Tim Reischmann on 2011-10-26.
Copyright (c) 2011 Tim Reischmann. All rights reserved.
usage:
import tim_pageSetup;reload(tim_pageSetup);tim_pageSetup.main()
set:
jointLength =... |
# Generated by Django 3.0.4 on 2020-04-04 22:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('boards', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='content',
... |
import cv2
import numpy as np
from math import pi
img = cv2.imread('test.jpeg', 0)
img = cv2.medianBlur(img, 5)
# hough --> only in grayscale
gray_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 100, param1=100, param2=30, minRadius=0, maxRadius=0)
#If the ... |
"""
Esta clase contiene una coleccion de threads los cuales se van a dedicar a cumplir
tasks conforme se estas sean agregadas al task(Queue). Gracias a esta implementacion
el servidor va a poder servir varias conexiones al mismo tiempo.
"""
from Queue import Queue
from trabajador import Trabajador
class ThreadPool:
... |
from django.db import models
from django.contrib.auth.models import User
import datetime
from django.utils import timezone
# Create your models here.
class class1(models.Model):
name = models.CharField(max_length=30, blank=True)
class Meta:
db_table = '_App1_class1'
class class2(models.Model)... |
#!/usr/bin/python
arr = [line.rstrip('\n') for line in open('problem_67.in')]
for i in range(0, len(arr)):
arr[i] = list(arr[i].split(" "))
for j in range(0, len(arr[i])):
arr[i][j] = int(arr[i][j])
holdSums = arr[len(arr) - 1]
for i in range(len(arr) - 2, -1, -1):
sums = arr[i]
for j in ran... |
import uuid
import enum
from django.db import models
from django.utils import timezone, translation
from django.conf import settings
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from djan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.