text
stringlengths
8
6.05M
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import re from powerline.lib.vcs import get_branch_name, get_file_status from powerline.lib.shell import readlines from powerline.lib.path import join from powerline.lib.encoding import (get_pr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # Created By : Krikor Herlopian # Created Date: Wed May 12 2021 # Email Address: kherl1@unh.newhaven.edu # ============================================================================= from ...
''' """ Created on Feb 24, 2020 @author1: leyu_lin(Jack) @author2: Parth_Thummar ''' def polyval(fpoly, x): # reverse use slicing rev_fpoly = fpoly[::-1] value = 0 for b, a in enumerate(rev_fpoly): value += a * x ** b return value def derivative(fpoly): rev_fpoly = fpoly[::-1] pol...
#!/usr/bin/env python3 # # Determine the duration of a specified test. # import datetime import sys import pscheduler spec = pscheduler.json_load(exit_on_error=True); # TODO: Make sure the type is one we like # TODO: Validate the spec total = datetime.timedelta() # # Traceroute time # try: hops = spec['hops'...
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait def getLocation(): options = Options() options.add_argument("--use-fake-ui-for-media-stream") timeout = 20 driver = webdriver.Chrome(exe...
# -*- coding: utf-8 -*- """ Created on Tue Jul 03 12:22:24 2018 @author: UG-DProyectos """
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() current_font_size = 16 default_text = "ABCDEFGHIJKLMnopqrstuvwxyz" text_color = (246/255.0, 255/255.0, 11/255.0) bg_color = (56/255.0, 56/255.0, 154/255.0) renWin = vtk.vtkRenderWindow() renWin.SetSize(386, ...
"""Utils related to lstm models and dataset vocab.""" import pandas as pd import numpy as np import copy from sklearn.metrics import roc_auc_score import matplotlib.pyplot as plt import seaborn as sns from collections import Counter import torch from torch.utils.data import Dataset class ToyDataset(Dataset): ""...
pin = "881120-106824" print(pin[7])
from rest_framework import routers from .views import AuthViewSet router = routers.DefaultRouter(trailing_slash=False) router.register('auth', AuthViewSet, basename='auth') urlpatterns = router.urls
from django.http import HttpResponseBadRequest, HttpResponse from django.views.decorators.csrf import csrf_exempt from main.models import User from main.app.modules import user, sync, profile, recognition def api(request): if request.method == 'GET': try: User.objects.get(token=request.sessio...
from rest_framework.permissions import BasePermission class IsStaffOrUser(BasePermission): # message="ssssssssss" def has_object_permission(self,request,view,obj): if request.user.is_staff or (obj.added_by == request.user): return True return False
import os import shlex, subprocess import sys def execute(): wd=os.getcwd() os.environ['UE4_DIR']=wd os.environ['SIMUL_BUILD']='1' # Insert below the location of your own Qt5 64-bit install: os.environ['QTDIR']=os.environ['DROPBOX']+'/Qt/qt5_msvc2012_64_opengl' os.environ['VSDIR']=os.environ['ProgramFiles(x86)']...
import json from django.http import JsonResponse, HttpResponseBadRequest, QueryDict from main.models import User, Plate, Synchronization from client.settings import BASE_DIR from pip._vendor import requests import ast from main.app import app def put(request): user = User.objects.get(token=request.session['toke...
from app_def import app from choroplethmapbox import get_choroplethmap_fig from pre_process import * from utils import add_annotations_to_fig, options_map, stat_zones_names_dict, options import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import plotly.expr...
from flask.views import View class IssuerView(View): def __init__(self, view): self.view = view def dispatch_request(self, *args, **kwargs): """ Returns identifying information for a Blockchain Certificate issuer. --- tags: - issuer parameters: ...
# -*- coding: utf-8 -*- """ Created on Sun Apr 11 01:16:20 2021 @author: hoang """ import hashlib from Crypto.Cipher import AES def derive_key(key): # SHA-1 hash algorithm key_sha1 = hashlib.sha1(key).digest() b0 = "" for x in key_sha1: b0 += chr( ord(x)^ 0x36) b1 = "" for x in key_s...
# 10 matrix example from numpy import * list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] list2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] arr = matrix(list1) secarr = matrix(list2) # 1 print(arr) arr2 = arr.flatten() print(arr2) # 2 arr3 = arr2.reshape(3, 3) print(arr3) # 3 arr4 = arr + secarr print(arr4) # 4 arr5 = arr * secarr...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Part3. Standard Library (Python标准库) =============================================================================== 该部分主要介绍了Python标准库中的那些常用的库。 """
# coding: utf-8 import io from flask import Flask, request, send_file from object_detection.utils import ops as utils_ops import os import numpy as np import cv2 from gevent import monkey import tensorflow as tf import datetime # In[ ]: os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' os.environ["CUDA_DEVICE_ORDER"] = "PCI_...
import math from Tkinter import * from UITools import BoardTools, BoardTestTools from TKUnit import * import ui_cfg class TKBattlefield: def __init__(self, canvas, top_left_pixel, width, height): self.canvas = canvas self.major = width self.minor = height self.xoffset = top_left_...
from django.contrib import admin from first_app.models import Feed, UserProfile # Register your models here. admin.site.register(Feed) admin.site.register(UserProfile)
#!/usr/bin/python3 """fetches https://intranet.hbtn.io/status """ import urllib.request with urllib.request.urlopen('https://intranet.hbtn.io/status') as response: html_con = response.read() print('Body response:') print('\t- type: {}'.format(type(html_con))) print('\t- content: {}'.format(html_con)...
def print_reverse(org: list): new_list = org[0:len(org):-1] print(new_list) if __name__ == '__main__': reverse(list(range(10)))
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
import matplotlib.pyplot as plt import csv """ Classes: Company() ---> Creates a company class Functions: predict_next_average() ---> Takes in a company class and predicts the average price in the next period using hard-coded linear regression classify_trend() ---> Takes in a com...
from decimal import Decimal from functools import total_ordering from onegov.core.orm import Base from typing import NamedTuple, TYPE_CHECKING if TYPE_CHECKING: from onegov.pay.types import PriceDict from sqlalchemy import Table from typing_extensions import Self class _PriceBase(NamedTuple): amount...
from config import JLNet_config import torch from torch.utils.tensorboard import SummaryWriter import argparse from datetime import datetime,date from torch.utils.data import DataLoader import torch.optim as optim from utils.base_train import base_train class JLNet_train(base_train): """ basic training class ...
import math import random abs(-2) 2 ** 3 pow(3,4) math.sqrt(100) random.randint(1,300)
from abc import ABCMeta, abstractmethod import paramiko from scp import SCPClient import os class ModuleBaseClass(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self, app, name, pepper_ip, folder_name): # Storing relevant variables self.IP = pepper_ip self.name = na...
print( 2 + 2 ); print (8 / 5); print ((50 - 5*6) / 4);
"""Simple MicroPython script which demonstrates uPyBot controlled using the Micro Python Board (pyboard)""" # 25-Dec-2019 Initial version of the script created # 16-Jan-2020 Simple update robot class renamed to uPyBot import pyb from pyb import Pin, Timer from pyb import ExtInt, LED import micropython from micropython...
# if,else statement mark = 20 if mark >= 33: print("You pass in the exam") if mark < 33: print("You fail in the exam") print("Program end") value = 60 if value < 30: print("Pass") else: print("Fail") ''' statement1 -> if statement statement2 -> if statement, else statement statement3 or more -> if st...
# Guess the number #This program generates a random number between 1 and 64 and #the player has to guess it. #The computer tells the player each time if their guess is too low or too high #or if they have guessed it correctly import random print("This is a simple guessing game.") print("I am going to think o...
# A list of numbers is given. Print all list # items that are larger than the previous item. s = list(map(int, input().split())) maxN = s[0] ans = list() for i in range(1, len(s)): if int(s[i]) > int(s[(i - 1)]): ans.append(s[i]) print(*ans)
from django.db import models from datetime import date from django.contrib.auth.models import User #Blog author or commenter from django.urls import reverse STATUS = ( (0,"임시저장"), (1,"글 게시") ) # Create your models here. class Post(models.Model): title = models.CharField(max_length = 255 , verbose_name="제목") ...
from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path('search/', views.search), path('search/<str:topic>', views.search, name="search"), path('wiki/<str:subject>', views.wiki, name = "wiki"), path('createNewPage/', views.createNewPage, name= "ne...
import pathlib import boto3 from botocore.exceptions import ClientError from chalicelib.configuration import get_config from chalicelib.utils.custom_logging import log s3_client = boto3.client('s3', region_name=get_config("region")) def create_presigned_url(bucket_name, object_name, expiration=3600,region="us-west-...
# -*- coding: utf-8 -*- """ Universidade Federal do Rio de Janeiro Porgrama de Pos-Graduação em Engenharia de Sistemas e Computação CPS841 - Redes Neurais Sem Peso Teste da WiSARD para predição de tendências de ações com a estratégia "diamante, conforme o artigo "Análise de Séries Temporais Financeiras Utilizando Wi...
{ PDBConst.Name: "notetype", PDBConst.Columns: [ { PDBConst.Name: "ID", PDBConst.Attributes: ["tinyint", "not null", "primary key"] }, { PDBConst.Name: "Type", PDBConst.Attributes: ["varchar(128)", "not null"] }, { PDBConst.Name: "SID", PDBCons...
import inspect from typing import Tuple from .stock_exchange_v1 import StockExchangeV1OrderBook, StockExchangeV1Action, StockExchangeV1OrderTypes, StockAgentV1InternalState, StockExchangeV1FillTicket class OrderBookTests: def buildTest(): ob = StockExchangeV1OrderBook(1) def testBasicFunctionality():...
import numpy as np import matplotlib.pyplot as plt x = np.arange(-5, 15, 0.1) # y_2 = x^2 - 10x + 10 y_2 = x**2 - 10*x + 10 # y_3 = x^3 - 10x^2 - 10x + ff y_3 = x**3 - 10*x**2 - 10 * x + 10 #plt.plot(x, y_2) #plt.plot(x, y_3) plt.show()
lista = [2,5,7,6,9,3,1] lista[2] = 3 lista.append(7) # ADICIONA itenm no final da lista lista.sort() # Organiza a lista em ordem crescente lista.sort(reverse=True) #Organiza a lista em ordem descrecente lista.insert(3, 4) # adiciona item na lista (posição, elemento) if 10 in lista: lista.remove(7) #remove o primeir...
import novaclient.v1_1.client as nvclient from environ import getenviromentvars import logging import json import uuid from nvclient_model import model_nvsession, model_nvnetwork, model_instance, model_nvclient class view_nvsession(object): def __init__(self, model): self.log = logging.getLogger("view.n...
"""Generate an HTML report summarizing CladeCompare output.""" import logging from math import log10 html_page_tpl = """\ <html> <head> <title>%(title)s</title> <style> * { font-family: Verdana, sans; } body { margin: 0; } h1 { font: 1.6em bold Verdana, sans; background-color: #eee; ...
''' Baseline solution for the ACM Recsys Challenge 2017 using XGBoost by Daniel Kohlsdorf ''' from model import * from parser import * from test import * import os mingw_path = 'C:\\Program Files\\mingw-w64\\x86_64-5.3.0-posix-seh-rt_v4-rev0\\mingw64\\bin' os.environ['PATH'] = mingw_path + ';' + os.environ['PATH'] ...
from functools import reduce from typing import AbstractSet import bottle import json from bottle import route, run, template, request, response, redirect, static_file, error, post, view from numpy import percentile from numpy.core.numeric import indices import pandas from pandas.io.parsers import read_csv from attrs i...
from xml.etree.ElementTree import Element,dump,SubElement note = Element('note', date="20120104") #attrib를 써서 속성을 추가하는 것과 같은 결과가 나온다 to = Element('to') #자식 노드 to.text = "Tove" note.append(to) SubElement(note,"from_tag").text="Jani" dump(note)
import logging from collections import defaultdict import numpy as np import pandas as pd from sklearn import clone, metrics from sklearn.model_selection import cross_validate from util.estimator.tests.base import EstimatorTestMixin class RegressorTestMixin(EstimatorTestMixin): PRECISION = 2 def test_cover...
default_app_config = 'django_nginx_access.apps.DjangoNginxAccessConfig'
import os if 'QUERY_STRING' in os.environ: if os.environ["QUERY_STRING"] != "": print("<code>", os.environ['QUERY_STRING'], "</code>")
from unittest import TestCase import sys sys.path.append('../') from leetCodeUtil import LinkedList from leetCodeUtil import ListNode import unittest from linked_list_cycle import Solution class TestSolution(TestCase): def test_linkedListCycleCase1(self): sol = Solution() l1 = LinkedList() ...
import moduleCreate moduleCreate.pythonModule1() moduleCreate.pythonModule2() print(moduleCreate.variableName) try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished")
## Tax Calculator - V 1.0.0 ## Author: Dena, Rene ## Last Modified: #________________________________________________________Misc.__________________________________________________________ ## Requirements: # input costs # country/state # output tax and total cost stateList = {'Alabama': 4.00, 'Alaska': None, 'Arizon...
import numpy as np def nudft1(sig, fourier_pts): """ Non-uniform discrete Fourier transform (1D) :param sig: An array of size n containing the signal :param fourier_pts: An array of size K represents the frequencies in Fourier space at which the Fourier transform is to be calculated. :retur...
#!/usr/bin/env python """ Takes a file with detection bounding boxes. Crops the boxes and saves all resulting crops in a .hdf5 file. This can then be used to do pre-training tasks. """ from __future__ import print_function import os, sys, time, os.path as path from argparse import ArgumentParser from progressbar impo...
from selenium import webdriver # 导入提供鼠标操作的ActionChains类 from selenium.webdriver.common.action_chains import ActionChains from time import sleep driver = webdriver.Chrome() driver.get("https://yunpan.360.cn") right_click = driver.find_element_by_name("password") # context_click(right_click)模拟鼠标右键,perform执行操作 ActionCha...
class SegmentTree(): # SegmentTree(n, 0, lambda a,b : a+b) # 0-indexed def __init__(self,size,unit,f): self.size=size self.data=[unit for _ in range(2*size)] self.unit=unit self.f=f def update(self,i,x): c=self.data f=self.f i+=self.size c[...
# Generated by Django 2.1.2 on 2019-05-18 10:16 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('tag', '0001_initial'), ('genre', '0001_initial'), migrations.swappable_dependency(settin...
import sublime from ._compat.typing import Optional from .view_utils import _temporarily_scratch_unsaved_views __all__ = ['new_window', 'close_window'] def new_window( *, menu_visible: Optional[bool] = None, sidebar_visible: Optional[bool] = None, tabs_visible: Optional[bool] = None, minimap_vi...
# if you change this file, consider also changing image_loader_dummy.py import io # see pyproject.toml try: import lxml.etree import PIL.Image import reportlab.graphics.renderPM from svglib import svglib except ImportError as e: raise ImportError(str(e) + ". Maybe try 'pip install teek[image_loade...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'C4205 ._SN', MapName = 'Grancel', Location = 'C4205.x', MapIndex = 1, MapDefaultBGM = "ed60031", Flags = 0, ...
import re from typing import List, Union from itertools import chain from summertime.model.base_model import SummModel class DialogueSummModel(SummModel): is_dialogue_based = True def __init__( self, trained_domain: str = None, max_input_length: int = None, max_output_length...
from . import * from .mistags import Mistags from .catalog import Catalog from .requestlist import RequestList from sqlalchemy.orm import column_property class Song(Base): __tablename__ = 'song' id = Column(Integer, primary_key=True) file = Column(String(512)) catalog_id = Column("catalog", Integer, F...
from flask import Flask, render_template, request, redirect app = Flask(__name__) @app.route("/") def root(): return "Hello, World!" @app.route("/index.html") @app.route("/index.php") def home(): return redirect("/") @app.route("/user/<username>") def user_template(username): return render_template("user.h...
import os def join_collection(directory: str): items = set() for filename in os.listdir(directory): if not filename.endswith('.processed'): continue with open(os.path.join(directory, filename), 'r') as f: items |= set(f) if len(items) == 0: return with o...
import json from boto.s3.connection import S3Connection from boto.s3.key import Key # create connection to bucket c = S3Connection('AKIAIQQ36BOSTXH3YEBA','cXNBbLttQnB9NB3wiEzOWLF13Xw8jKujvoFxmv3L') # create connection to bucket b = c.get_bucket('public.tenthtee') contest_structure = {} conte...
import csv with open('/mnt/users/code/test/volumes.csv', 'r') as f: reader = csv.reader(f) counts = [] i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10 = 0,0,0,0,0,0,0,0,0,0,0 for row in reader: if int(row[1]) <= 10: i0 += 1 if int(row[1]) <= 20 and int(row[1]) > 10: i1 += 1 ...
def max_index(a_list): old_list = a_list[:] a_list.sort(reverse=True) if a_list[0] >= 2 * a_list[1]: return old_list.index(a_list[0]) return -1 a_list = [3,6,2,1] b_list = [4,6,2,1] c_list = [3,4,10,2,5] print(max_index(a_list)) print(max_index(b_list)) print(max_index(c_list))
#!/usr/bin/env python import sys import signal import binascii import struct import time from killerbee import * def usage(): print >>sys.stderr, """ zbkey: Attempts to retrieve a key by sending the associate request followed by the data request after association response Example usage: ./zbkey -f 14 -s 0...
"""Advent of Code 2019 Day 12 - The N-Body Problem.""" def moon_steps(moon_positions, moon_velocities): """Take a time step simulating the movement of the moons.""" for moon, position in moon_positions.items(): for other_moon, other_position in moon_positions.items(): if moon == other_moon...
def complex_mult(a,b): a_real, a_imz = map(parse_str_number, a.split('+')) b_real, b_imz = map(parse_str_number, b.split('+')) result_read, result_imz = map(parse_int_number, multiply([a_real, a_imz], [b_real, b_imz])) return result_read + 'i' + result_imz def parse_str_number(str_number): ...
import request import bottle from hashlib import sha256 comment_list=[] def create_hash(password): pw_bytestring = password.encode() return sha256(pw_bytestring).hexdigest() pw2 ="123456" hsh1 = create_hash(pw2) while (True): comment=input("Enter your comment : ") comment_number = 0 pw...
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-06-17 14:36 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('takwimu', '0001_initial'), ] operations = [ migrations.RemoveField( mod...
#!/usr/bin/env python import sys def main(argv): output_file_name = argv[2] import xml.etree.ElementTree as ET tree = ET.parse('spontal.xml') root = tree.getroot() for point in root.findall('POINT'): b_hz = float(point.find('BOTTOM_HZ').text) t_hz = float(point.find('TOP_HZ').text) f0_st = float(point.find...
num=[7,8, 120, 25, 44, 20, 27] i=0 while i<len(num): if num[i]%2!=0: print(num[i]) i=i+1
# Generated by Django 3.2 on 2021-04-21 18:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pie', '0003_auto_20210421_1844'), ] operations = [ migrations.AlterField( model_name='showchart', name='customer_id', ...
#!/usr/bin/env python # ENCODE frac mito # Author: Jin Lee (leepc12@gmail.com) import sys import os import argparse from encode_lib_common import ( log, ls_l, mkdir_p, strip_ext) from encode_lib_log_parser import parse_flagstat_qc def parse_arguments(): parser = argparse.ArgumentParser( prog='ENCODE...
from scrapy import Item, Field class QuoteItem(Item): text = Field() author = Field() tag = Field() #class BookItem(Item):
# 23. Merge k Sorted Lists ''' Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. ''' Solution 0: Brute Force Time O(nlogn) where n is the total number of nodes Solution 1: Use merge two sorted lists which takes O(n) merge every two for each layer Time O(nlogk) Soluti...
# -*- coding:utf-8 -*- import os import sys class PlayBack(object): def __init__(self, state, action, next_state, reward): self.state = state self.action = action self.next_state = next_state self.reward = reward class PlayBacks(object): def __init__(self): self.__data...
import aiohttp import xmltodict import json import asyncio import PIL import PIL.Image import io import typing italify = '*{}*'.format boldify = '**{}**'.format codify = '`{}`'.format # ASSUMPTION_EMOJI = '🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿' ASSUMPTION_EMOJI = '🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷...
import matplotlib.pyplot as plt import numpy as np from numpy import pi import pyqg # the model object year = 1. m = pyqg.BTModel(L=2.*pi,nx=256, tmax = 50*year, beta = 21., H = 1., rek = 0., rd = None, dt = 0.001, taveint=year, ntd=4) fk = m.wv != 0 ckappa = np.zeros_like(m.wv2) ckappa[f...
class Node(object): def __init__(self, data, next=None): self.data = data self.next = next class Context(object): def __init__(self, source, dest): self.source = source self.dest = dest def move_node(source, dest): if not source: raise "SourceError" dest...
from flask import Blueprint, jsonify, request from flask_login import login_required from app.models import Module, db from app.forms import ModuleForm module_routes = Blueprint('modules', __name__) @module_routes.route('/') @login_required def modules(): """ Queries for and returns all modules """ mo...
from django.contrib import admin from .models import BillsAgreement, BillsHistory, PaymentHistory admin.site.register(BillsAgreement) admin.site.register(BillsHistory) admin.site.register(PaymentHistory)
from Gaudi.Configuration import * from Configurables import DaVinci #from Configurables import AlgTool from Configurables import GaudiSequencer MySequencer = GaudiSequencer('Sequence') #For 2012 MC DaVinci.DDDBtag='dddb-20130929-1' DaVinci.CondDBtag='sim-20130522-1-vc-mu100' #for 2011 MC #DaVinci.DDDBtag='dddb-201309...
class Book: count = 0 # 카운트 순번... books = [] @classmethod def print(cls): for book in cls.books: print(Book.str(book)) print(Book.getBookInfo(book)) print('-'*40) def __init__(self, title, author, price): self.title = title self.author = ...
# Copyright 2017 QuantRocket LLC - All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
import os import sys import random import collections from nn_config import SELECTED_CATEGORIES LIST_CATEGORY_CLOTH_FILE = os.path.join('DATA', 'Anno', 'list_category_cloth.txt') LIST_CATEGORY_IMG_FILE = os.path.join('DATA', 'Anno', 'list_category_img.txt') TRAIN_OUTPUT_FILE = "sample_equal_numbers_train.txt" VALIDAT...
from django.shortcuts import render,render_to_response,get_object_or_404 from django.template import RequestContext from books.models import Book def ui_index(request): context = RequestContext(request) count = Book.objects.count() return render_to_response( 'ui/ui_books.html', {'coun...
import numpy as np def my_imfilter(image, filter): """ Apply a filter to an image. Return the filtered image. Args - image: numpy nd-array of dim (m, n, c) - filter: numpy nd-array of dim (k, k) Returns - filtered_image: numpy nd-array of dim (m, n, c) HINTS: - You may not use any libraries that do...
from __future__ import absolute_import, division, print_function from builtins import bytes import glob import os import sys import multiprocessing import pytest # todo this is a dup from setup.py.... def get_my_compiler(): my_compiler = os.getenv('CXX', '').replace('/', '') if not my_compiler: my_...
# Generated by Django 2.1 on 2019-01-25 03:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('order', '0006_auto_20190125_1048'), ] operations = [ migrations.AlterField( model_name='orderinfo', name='transit_pric...
from django.shortcuts import render, redirect from django.views.generic.list import ListView from django.views.generic.edit import ModelFormMixin from django.contrib.auth.models import User from django.db.models import Q from django.http import HttpResponse from . import create from main.models import * def register(...
from database import conn cursor = conn.cursor() sql = """ CREATE TABLE IF NOT EXISTS `qqmessage`( `id` INT UNSIGNED AUTO_INCREMENT, `user_id` VARCHAR(50), `group_id` VARCHAR(50), `sender` VARCHAR(500), `type` VARCHAR(50), `cq` VARCHAR(200), `content` VARCHAR(3000), `time` VARCHAR(25), PRIMA...
# Time :- O(N) as we will iterate through the array once # Space :- O(1) Constant space as it does not save the elements in set or hashtable def duplicate(arr,n): # Iterate through the array for i in range(n): # arr[i] will give the element at and take its absolute value # arr[value of arr[i] -1 ] -1 i...
from subprocess import call import os import sys import staus_handling status_message = staus_handling.StatusHandling() filenames= os.listdir(os.path.dirname(os.path.abspath(__file__))) folders = [] for filename in filenames: # loop through all the files and folders if os.path.isdir(os.path.join(os.path...
# Generated by Django 2.0.7 on 2019-01-08 10:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basedata', '0042_auto_20190107_1107'), ] operations = [ migrations.AlterField( model_name='feedback_form', name='bon...
import pandas as pd def countries_dropdown_data(main_table): print("------------------") info_mongodbpairs = main_table info_mongodbpairs = info_mongodbpairs.iloc[:,1:].fillna('0') info_mongodbpairs = info_mongodbpairs.drop(columns=['lat', 'long']) info_mongodbpairs =info_mongodbpairs.rena...