text
stringlengths
38
1.54M
def SelectionSort(A): n = len(A) for j in range(0, n - 1): imin = j for i in range(j + 1, n): if (A[i] < A[imin]): imin = i A[imin], A[j] = A[j], A[imin]
# coding:utf-8 import os import time import tempfile import aircv as ac import pytesseract from PIL import Image PATH = lambda p: os.path.abspath(p) TEMP_FILE = PATH(tempfile.gettempdir() + "/temp_screen.png") class Appium_Extend(object): def __init__(self, driver): self.driver = driver def get_time...
import numpy as np import os years = np.arange(501,525) v = 'SST' output = 'ice_month' for y in years: os.system('ncra -v ' + v + ' /short/e14/erd561/mom/archive/gfdl_nyf_1080_hist_5069/output' + str(y) + '/' + output + '.nc /g/data/e14/erd561/mom/gfdl_nyf_1080_hist_5069/' + output + str(y) + '_' + v + '.nc') ...
# -*- coding: utf-8 -*- import glob import os import importlib import sys modules = {} # 출력 결과 비교 모듈을 발견해 봅시다 diff_dir = os.path.dirname(__file__) sys.path.append(diff_dir) files = glob.glob(os.path.join(diff_dir, "*.py")) for file in files: try: differ = os.path.basename(file).split(".")[0] if d...
from __future__ import division import numpy as np import tensorflow.contrib.learn.python.learn as learn from sklearn import metrics batch_size = 32 def get_classification_score(train_encodings, train_labels, test_encodings, test_labels, steps): feature_columns = learn.infer_real_valued_columns_from_input(train_...
# Copyright 2015 ARM Ltd # # 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, soft...
# coding=utf-8 from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django_resized import ResizedImageField from .choices import * from star_ratings.models import Rating class AbsPerm(models.Model): ...
"""Deck.""" from typing import Optional, List import requests import random class Card: """Simple dataclass for holding card information.""" def __init__(self, value: str, suit: str, code: str): """Constructor.""" self.value = value self.suit = suit self.code = code se...
''' 闭包(python可以嵌套定义函数) -内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包 -Python内函数也是对象 -闭包不能修改外部作用域的局部变量 ''' def addx(x):# x是引用环境 def adder(y): return x + y return adder # adder为闭包 c = addx(8)# c现在是一个函数 type(c)# function c(10)# 相当于addx(8)(10)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None import copy class Solution: def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]: if root is None: return [] result = [] def dfs(nod...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hf:t:",["ifile=","text="]) except getopt.GetoptError: print 'Error: SVGtoPDFfromText.py -f <inputfile> -t <text>' sys.exit(2) for opt, arg i...
import os import re from os import walk, getcwd import csv """-------------------------------------------------------------------""" """ Configure Paths""" valid_txt_path = 'img_handshake_oznaczone/' detected_txt_path = 'img_handshake_wyliczone/' outpath = "CSV_dic/" """ Get input text file list """ txt_name_list ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 21 14:59:55 2020 @author: ganesh """ import pandas as pd mail = pd.read_csv('/home/ganesh/Desktop/SpamClassifier-master/smsspamcollection/SMSSpamCollection', sep='\t', names=["label", "message"]) # the above note pad is ...
''' if a image (e.g., segmentation maps) is composed of several components, but there are some noise, which are in form of isolated components we can then remove the extra noise with following codes Dong Nie 12/17/2016 ''' import numpy as np import SimpleITK as sitk from multiprocessing import Pool import os...
import random, string def rndText(letters=15, lines=3, spaces=5): return "\n".join("".join((random.choice(string.letters + ' ' * spaces) for _ in xrange(letters))) for _ in xrange(lines)) RESET = '\x1b[0m' BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = ['\x1b[1;{}m'.format(30+i) for i in range(8)] i...
import numpy as np # unique class values def y_Encoder(classList): num_class = len(classList) classDict = {} for i,classElem in enumerate(classList): code = np.zeros((num_class,)) code[i] = 1.0 classDict[classElem] = code return classDict # from nltk.corpus import wordnet as ...
x = int(input('Quanti voti ha ricevuto il 1° candidato? ')) y = int(input('Quanti voti ha ricevuto il 2° candidato? ')) z = x+y d = (x/z)*100 u = (y/z)*100 print('Percentuale 1° candidato: ', d, '%') print('percentuale 2° candidato: ', u, '%') if d>u : print('Il primo candidato ha vinto!') if d<u : pr...
import orderbook as ob o = ob.Orderbook('new_orderbook.h5') o.read_data('SPY','order_book') o.rollup_orderbook() o.plot_bid_ask_prices() o.plot_bid_ask_spread() o.plot_interpacket_gap() o.plot_order_traffic(40)
from os import path d = path.dirname(__file__) d = '/'.join(d.split('/')[:-2]) audio_num_mel_bins = 80 audio_sample_rate = 16000 num_freq = 513 symbol_size = 256 n_fft = 1024 rescale = True rescaling_max = 0.999 hop_size = 256 win_size = 1024 frame_shift_ms = None preemphasize = True preemphasis = 0.97 min_level_db = ...
from django.test import TestCase from django.contrib.auth.models import User from django.test import Client import json from assets.constants import SUPERVISOR, ADMIN from authentication.models import UserRole from authentication.tests.helper_functions import create_new_user, log_in class AuthenticationViewTestCase(...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data class preprocess: def __init__(self, FLAGS): self.dataset_path = FLAGS.dataset_path def Mnist2data(self): self.mnist = input_data.read_data_sets(self.dataset_path+"/MNIST_data/", one_hot=True) ...
real = float(input('\nDigite um valor em Reais: R$')) peso = real * 13.63 iene = real * 19.80 dolar = real / 5.33 euro = real / 6.33 libra = real / 7.00 print('\nCONVERSOR DE MOEDAS') print('-'*25) print('Peso Argentino: $ {:.2f}' .format(peso)) print('Iene: ¥ {:.2f}' .format(iene)) print('Dolar: U$ {:.2f}' .format(dol...
import os from contextlib import contextmanager try: import psycopg2cffi as psycopg2 except ImportError: import psycopg2 import queries DB_CONNECT = os.getenv('NHLDB_CONNECT') @contextmanager def session(connect=None, pool_size=10, is_tornado=False): if connect is None: connect = DB_CONNECT ...
import config.config as config # Decoder class for use with a rotary encoder. class decoder: """Class to decode mechanical rotary encoder pulses.""" def __init__(self, pi, rot_gpioA, rot_gpioB, switch_gpio, rotation_callback, switch_callback): """ Instantiate the class with the p...
#!/usr/bin/env python #============================================================================== # gtf2juncs.py # # Shawn Driscoll # 20160819 # # Gene Expression Laboratory, Pfaff # Salk Institute for Biological Studies # # Print out a file of junctions from a GTF annotation. this will include # gene name, id, st...
""" Script to easily read in and plot the results of BestTrack output Example Usage: python plotBestTrack.py 20150408_20150409 -i tracks """ import argparse import datetime from datetime import timedelta import time import numpy as np from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import s...
import flask_bootstrap from flask_wtf import form from flask import request import forms import time from forms import * from flask import abort from werkzeug.exceptions import Unauthorized from flask import Flask, render_template, session, Response, request from flask import render_template, flash, redirect, url_for f...
from __future__ import print_function, division import os, json, random from PIL import Image import numpy as np import torch import torchvision from torch.utils.data import Dataset from envs.config import Config from torchvision import transforms import cv2 import utils.video_transforms as video_transforms #import vid...
#!/usr/bin/env python # -*- coding: utf-8 -*- # camera.py # Copyright (c) 2017-2021, Richard Gerum # # This file is part of the cameratransform package. # # cameratransform is free software: you can redistribute it and/or modify # it under the terms of the MIT licence. # # cameratransform is distributed in the hope th...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' this module is to inspect keys, expecially keys with colon. ''' import audit import re import json import codecs OSM_PATH = "sample.osm" OUTPUT = "inspect_keys.json" get_element = audit.get_element LOWER_COLON = audit.LOWER_COLON ''' The functi...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): GENDER = ( ('M', 'Male'), ('F', 'Female') ) user = models.OneToOneField(User) age = models.IntegerField(default=0) gender = models.CharField(max_length=1,...
# -*- coding: utf-8 -*- """ Created on 2018/11/7 10:34 @author: royce.mao # 构造第2阶段,小图片数字的识别检测网络 """ from __future__ import print_function from __future__ import absolute_import from keras.models import Model from keras.layers import Conv2D, Reshape, Input, Activation, Convolution2D, MaxPooling2D, ZeroPadding2D, Add, B...
# -*- coding: utf-8 -*- import cv2 import sys import face_recognition import os import MySQLdb import numpy as np from datetime import datetime import databaseScript path = "ImagesAttendance" images = [] classNames = [] myList = os.listdir(path) # print(myList) for cl in myList: curImage = cv2.imread(f'{path}/{cl}'...
"""Add first/last name fields to user table. Revision ID: 81162fe5d987 Revises: 4e8beae024e9 Create Date: 2018-11-28 22:14:00.933976 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '81162fe5d987' down_revision = '4e8beae024e9' branch_labels = None depends_on = ...
#remove dublets List=[1,2,4,7,22,3,5,6,3,1,22,1,4,5,2,3,4,5,6,7,5] NewList=[] for number in List: if number not in NewList: NewList.append(number) #append means- put into print(NewList) #sort list NewList.sort() print(NewList)
import pygame import time import random import numpy as np from PIL import Image import env from game.Board import BoardSingleton from game.Snake import Snake from game.Food import Food from game.EventListener import EventListener class SnakeGameEnv(): def __init__(self): self.board = BoardSingleton.getI...
import math # import matplotlib.pyplot as plt import numpy as np from ... environment.simulator.models import Simulation from ... import db # To differentiate first and last from movement display MARKER_FIRST = { 'marker': "o", 'markerfacecolor': "green", 'markersize': "14", ...
# coding: utf-8 # # Introducing Pandas # # Pandas is a Python library that makes handling tabular data easier. Since we're doing data science - this is something we'll use from time to time! # # It's one of three libraries you'll encounter repeatedly in the field of data science: # # ## Pandas # Introduces "Data F...
""" Captcha.Visual.Backgrounds Background layers for visual CAPTCHAs SimpleCaptcha Package Forked from PyCAPTCHA Copyright (C) 2004 Micah Dowty <micah@navi.cx> """ from simplecaptcha.visual import Layer, pictures import random from PIL import Image, ImageDraw class SolidColor(Layer): """A solid color background...
import imapclient import pyzmail imapObj = imapclient.IMAPClient('imap.gmail.com', ssl=True) imapObj.login(' chokkadibhat@gmail.com ', ' abhI$hek15 ') imapObj.select_folder('INBOX', readonly=True) UIDs = imapObj.search(['SINCE 05-Jul-2014']) #UIDs have list of message ID rawMessages = imapObj.fetch([40041], ['BO...
from django.urls import path from . import views app_name = 'logtest' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('today_access', views.TodayAccessView.as_view(), name='today_access'), path('recent_log_table', views.RecentLogView.as_view(), name='recent_log_table'), path('e...
from os import environ ''' smtplib is a less secure method than google auth. To use google auth, see https://github.com/shankarj67/python-gmail-api ''' import smtplib def send_email(ads_msgs): #ads_msgs: a list of strings. gmail_bot = environ['gmail_bot'] gmail_bot_pwd = environ['gmail_bot_pwd'] sent...
import pytest import numpy as np from astropy import units as u from ..flux import compute_flux def strip_parentheses(string): return string.replace('(', '').replace(')', '') COMBINATIONS = \ [ (np.array([1, 2, 3]) * u.Jy, u.Jy, {}, 6 * u.Jy), (np.array([1, 2, 3]) * u.mJy, u.Jy, {}, 0.006 * u.Jy), ...
from rest_framework.serializers import ModelSerializer, ReadOnlyField from .models import Investment as InvestmentModel class InvestmentSerializer(ModelSerializer): investmentId = ReadOnlyField(source='id') class Meta: model = InvestmentModel fields = ['investmentId', 'username', 'amount', '...
#!/usr/bin/env python # get_all_kmers.py seq = 'GCCGGCCCTCAGACAGGAGTGGTCCTGGATG' kmer_length = 7 stop = len(seq) - kmer_length + 1 for start in range(0, stop): kmer = seq[start:start + kmer_length] print(kmer)
#!/usr/bin/env python3 import os import sys import gzip from Bio import SeqIO #functions for trimming and merging fastq files, and characterizing fastq files def cut_primers(file, primer, raw_dir, trimmed_dir): #Cut primer sequences off from beginning of a read and send to new "trimmed" file #Input: zipped fa...
# Copyright 2020 Huawei Technologies Co., Ltd # # 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 a...
bp = list(input()) ab = "abcdefghijklmnopqrstuvwxyz" AB = "abcdefghijklmnopqrstuvwxyz".upper() for a in ab: p = list(filter(lambda x: x != a and x != a.upper(), bp)) Done = False while not Done: Done = True i = 1 while i < len(p): if (p[i] in ab and p[i-1] == p[i].upper...
import sys import os import argparse import json import csv import numpy as np import matplotlib.pyplot as plt from sklearn import model_selection from sklearn.cross_decomposition import PLSRegression from sklearn.metrics import mean_squared_error, r2_score import model_io import pls_analysis fontSize = 8 totalItems...
from django.shortcuts import render from .models import Price, Site # Create your views here. def home (request): return render(request, 'home.html') def prices(request): prices = Price.objects.order_by('price_base') return render(request, 'prices.html', {'prices': prices}) def sites(request): sites ...
# -*- coding: utf-8 -*- # from subprocess import * # import threading import time import subprocess import tornado.process gProjectName = "PD_103023_ELK" gVersion="6.6.6.6" gCmdLine = "start -branch %s -setVersion %s -uploadFtp -signature\n" # gProcess = subprocess.Popen('ffmpeg.exe', bufsize=10240, s...
#!/usr/bin/python import random def lessthan(test, pivot): return test < pivot def greaterthan(test, pivot): return pivot < test def partition(a, left, right, predicate): pivot = a[right] il = left ir = right while il < ir: while il < right and predicate(a[il], pivot): ...
# -*- coding: utf-8 -*- """ Created on Wed Jan 17 11:05:50 2018 @author: dell """ from tkinter import * from PIL import Image, ImageTk from tkinter.messagebox import * import main3x1 import main3x2 import main3x3 import main3x4 import main3x5 import main3x6 import qjbl qjbl.bl() def info(): '...
import os from setuptools import setup, find_packages import distutils.cmd import distutils.log from version import get_git_version VERSION, SOURCE_LABEL = get_git_version() PROJECT = 'dossier.models' AUTHOR = 'Diffeo, Inc.' AUTHOR_EMAIL = 'support@diffeo.com' URL = 'http://github.com/dossier/dossier.models' DESC = ...
#coding:utf-8 from django.shortcuts import render, render_to_response from django.contrib import auth # Create your views here. def login(request, **kwargs): print "into login" ''' response = render_to_response('login/login.html') # 在客户端Cookie中添加Post表单token,避免用户重复提交表单 response.set_cookie("postToken...
# Generated by Django 3.1.3 on 2020-11-25 12:02 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Initial_Contact', fields=[...
""" Using for loop to calculate the summary from 1 to 100 """ sum = 0 for x in range(1,101): sum += x print("The summary from 1 to 100 is %f" % sum) ############################################################ """ Using for-in loop to calculate the even summary from 1 to 100 """ sum = 0 for y in range(0, 101, ...
import os import SocketServer from ComputerVision.FaceDetector import FaceDetector from ComputerVision.CV2Wrapper import CV2Wrapper from Database.DBWrapper import DBWrapper class WebInterfaceTCPHandler(SocketServer.BaseRequestHandler): """ The request handler class for our server. It is instantiated onc...
import os, sys sys.path.append('/var/scalak/scalakweb') os.environ['PYTHON_EGG_CACHE'] = '/var/scalak/python_egg_cache' from paste.deploy import loadapp application = loadapp('config:/var/scalak/scalakweb/production.ini')
#!/usr/bin/python import sys flag=0 for input_line in sys.stdin: line = input_line.strip().split(",") if (flag ==0): columns=line flag=1 else: disno = float(line[11]) print "{0}\t{1}".format(disno,str(input_line.strip()))
from bs4 import BeautifulSoup data = open('/home/fenris/work/Internshit/Kamtech/out/Bike Rental System.html','r') soup = BeautifulSoup(data, 'lxml') inner_ul = soup.find_all('ul') lists = {} for ultag in soup.find_all('ul'): temp = [] for litag in ultag.find_all('li'): temp.append(litag.text.split) ...
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt random_array = np.linspace(0,2*np.pi,100) #generamos el array con 100 elementos aleatorios entre 0 y 2*PI array_sin = np.sin(random_array) #generamos el seno de todos los elementos anteriores array_cos = np.cos(random_array) #generamos el cos...
# -*- coding: utf-8 -*- def booleNett(phrase): ''' phrase : chaîne de caractères. Apairage des parenthèses nécessaires, espaces tolérés, tous les autres caractères hors opérateurs sont considérés comme variables ''' # 1-On enlève les espaces phrase=phrase.decode(encoding='UTF-8') phrase=phr...
import random from django.core.management.base import BaseCommand from django.contrib.admin.utils import flatten from django_seed import Seed from playlists import models as playlist_models from users import models as user_models from songs import models as song_models class Command(BaseCommand): """ class: ...
""" Example explaining the peculiriaties of evaluation """ from ml_recsys_tools.datasets.prep_movielense_data import get_and_prep_data import pandas as pd from ml_recsys_tools.data_handlers.interaction_handlers_base import ObservationsDF from ml_recsys_tools.recommenders.lightfm_recommender import LightFMRecommender ...
import psycopg2 connect_str = "dbname='empleado' user='cursoPython'host='localhost' password='1234567890'" conexion = psycopg2.connect(connect_str) cur = conexion.cursor() # rows= cur.execute("SELECT * FROM empleado") rows= cur.fetchall() for row in rows: print("ID: ",row[0],"\nNombre: ",row[1],row[2],"\nSueldo: "...
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from fbprophet import Prophet # setting the Seaborn aesthetics. sns.set(font_scale=1.3) df = pd.read_csv('ts_df.csv') m = Prophet() m.fit(df) forecast = m.predict(df) fig = m.plot_components(forecast) plt.show()
#-*- coding: utf-8 -*- from ElasticSearchManager import esManager class EVElasticSearch: """Base Class for EV Data Objects""" _internalCount = 0 _es = esManager() def __init__(self): self._internalCount = self._internalCount + 1 def showCount(self): return self._internalCount ...
from transformers import GPT2LMHeadModel, BertTokenizer, GPT2Config, TrainingArguments, Trainer import torch import os import argparse import random import numpy as np import sys sys.path.append('/home/user/project/text_generation/') from src.util import read_data, split_data from src.text_keywords_generation.datase...
import atm.database as db from utilities import * eval = db.Database('sqlite', '../../atm.db') ################## database and datarun # print_hp_summary(eval, 1) # print_summary(eval, 1) print_method_summary(eval, 1)
from typing import Union, List import requests from Summary import Summary from Provinces import Provinces from SummaryAll import SummaryAll from SummaryByProvince import SummaryByProvince from SummaryByRegion import SummaryByRegion class CovidSdk: __split_data = None @staticmethod def summary(province:...
#!/usr/bin/python3 import os from formula import formula insightType = os.environ.get("INSIGHT_TYPE") contribution = os.environ.get("CONTRIBUTION") formula.Run(insightType, contribution)
from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save,pre_save from django.dispatch import receiver from django.contrib.auth.models import UserManager # Create your models here. USER_CHOICES=( ("PATIENT", "PATIENT"), ("DOCTOR", "DOCTOR"...
from ply import lex literals = ['[', ']'] tokens = ['PLUS', 'MINUS', 'LSHIFT', 'RSHIFT', 'OUTPUT', 'INPUT'] t_PLUS = '\+' t_MINUS = '-' t_LSHIFT = '<' t_RSHIFT = '>' t_OUTPUT = '\.' t_INPUT = ',' t_ignore = ' \t' def t_NEWLINE(t): r'\n' pass def t_error(t): print("Illegal Character...
SIGN_MASK = 1 << 32 def max_old(a, b): if (a - b) & SIGN_MASK: return b return a def max_with_overflow(a, b): # overflow would be caused by different signed params # e.g. a = INT_MAX (2^31 - 1) and b = -15 if (a & SIGN_MASK and not b & SIGN_MASK) or (not a & SIGN_MASK and not b & SI...
from sqlalchemy import DateTime, Float, create_engine, Column, String, Integer, ForeignKey from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.exc import IntegrityError from sqlalchemy.sql import func from flask import Flask, request, jsonify ...
import boto3 import sys sys.path.append("./packages") import mysql.connector as mysql_connector import tornado.escape as tornado if __name__ == '__main__': response = boto3.client('health', region_name='us-east-1').describe_event_details_for_organization( organizationEventDetailFilters=[ { ...
from __future__ import print_function import platform import sys import struct import socket import threading import types import time from .config import DEBUG, HOST, PORT, MSG_TIMEOUT, SOCK_TIMEOUT, GET_PORT_ATTEMPT_COUNT from ._datatypes import * from .utils import show_error_message EVENTS_NAMES = ( 'evitem...
# Adapted from Graham Neubig's Paired Bootstrap script # https://github.com/neubig/util-scripts/blob/master/paired-bootstrap.py import numpy as np from sklearn.metrics import f1_score, precision_score, recall_score from tqdm import tqdm EVAL_TYPE_ACC = "acc" EVAL_TYPE_BLEU = "bleu" EVAL_TYPE_BLEU_DETOK = "bleu_detok"...
#encoding=utf-8 import torch import torch.nn as nn import torch.nn.functional as F class Swish(nn.Module): def __init__(self): super(Act_op, self).__init__() def forward(self, x): x = x * F.sigmoid(x) return x ''' ## 由于 Function 可能需要暂存 input tensor。 ## 因此,建议不复用 Function 对象,以避免遇到内存提前释...
#YOur Script is was update by Hirokaazo Nagata #fb : Hirokazo Nagata #gmail : ziadabouelfarah2@gmail.com import os,time print(''' XX MMMMMMMMMMMMMMMMss''' '''ssMMMMMMMMMMMMMMMM XX XX MMMMMMMMMMMMyy'' ''yyMMMMMMMMMMMM XX XX MMMMMMMMyy'' ...
import docx import os ''' Function: read_file(file_name, item_type) Parameters: file_name - the name of the file to be read. item_type - user-inputted search term to specify what is parsed for in the document. os.path.dirname(os.path.abspath(__file__))+"\\" is the current working director...
""" This is a setup.py script generated by py2applet Usage: python setup.py py2app """ from setuptools import setup with open("README.md", 'r') as f: long_description = f.read() APP = ['BuildTool\\main.py'] DATA_FILES = [] OPTIONS = {} setup( app=APP, data_files=DATA_FILES, options={'py2app': O...
from github import Github #Hesabımıza Giriş Yapıyoruz. try: git_hesap = Github("K_Adı", "Sifre") #print("Hesabınıza başarı ile giriş yapıldı.") except: print("Hesabınıza giriş başarısız!") #Githubda arama yapmak ve çıktı almak. try: repos = git_hesap.search_repositories(query="language:py...
from Core.Globals import * from Mapping import Mapping, E class VehicleMapping(Mapping): def __init__(self,target): self.target = target class Keyboard1Mapping(VehicleMapping): IMAGE = 'Keyboard1Mapping.png' def __init__(self,target): VehicleMapping.__init__(self,target) ...
import psycopg2 import pandas import numpy import objects import config db = objects.Database(config.server, config.database, config.user, config.password) # Read population data. dfPopulation = pandas.read_excel(r"C:\Users\hoged\OneDrive\Skrivebord\Speciale\Data\Population (2019).xlsx", skiprows=2, nrows=106, usec...
import unittest from src.core import formi # [] TODO: add test to combine more than 1 operations class FormiCoreTestCase(unittest.TestCase): """ Test formi.py core functions """ def test_join_string_function(self): result = formi.join_string('the\nquick') expected = 'the, quick' sel...
from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtMultimedia import * from random import randint from doudizhu import poker_distribute, pattern_spot, cards_validate, strategy, compare, ai_jiaofen, rearrange, print_cards import json, socket, threading, struct, sys, os, doudi...
from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static import django.contrib.staticfiles urlpatterns = [ url(r'^amadon$', views.index), url(r'^amadon/checkout$', views.checkout), url(r'^amadon/buy$', views.buy), ]
""" leetcode 108 """ def convert_sorted_array_to_bst(nums): if not len(nums): return None half = len(nums) // 2 root = TreeNode(nums[half]) root.left = convert_sorted_array_to_bst(nums[:half]) root.right = convert_sorted_array_to_bst(nums[half+1:]) return root
import numpy as np from core.soft import bezier from numpy import sin, cos from core.anim import Animation from core.obj import Vector, Line, Curve sHandSpeed = 12 mHandSpeed = sHandSpeed/60 hHandSpeed = mHandSpeed/12 b = bezier([0, 0, 0, 1, 1, 1, 1, 1]) def update_s(s, t, tmax): t *= -sHandSpeed * 2*np.pi t...
import tensorflow as tf from BNN import readData import numpy as np tf.reset_default_graph() def conv2d(x, W): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): """max_pool_2x2 down samples a feature map by ...
#!/usr/bin/env python from logging import basicConfig, getLogger, DEBUG logger = getLogger(__name__) OBJECT = 'Logical Port' MODULE = 'Logical Switching' def get_list(client, logical_switch_id=None): """ This function returns all T0 logical routers in NSX :param client: bravado client for NSX :retu...
import numpy as np import pandas as pd import faiss from sentence_transformers import SentenceTransformer from tqdm import tqdm class Clusterer: def __init__(self, data: pd.DataFrame, model=None): self.model = model self.data = data @staticmethod def chunks(lst, n): for i in rang...
from operator import itemgetter import psycopg2 import networkx as nx import matplotlib.pyplot as plt from networkx.drawing.nx_agraph import graphviz_layout from subprocess import call import pandas as pd def select(query): con = None result = None try: con = psycopg2.connect(database='MovieLens'...
import skimage from skimage import io import os import glob IMAGE_PATH = 'data/raw/images_train_rev1/' IMAGE_BW_PATH = 'data/bw/images_train_rev1/' if not os.path.isdir('data/bw/'): os.mkdir('data/bw/') if not os.path.isdir(IMAGE_BW_PATH): os.mkdir(IMAGE_BW_PATH) images = glob.glob( os.path.join(IMAGE_PA...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np # 1. variable definition x1 = 1.0 x1_node = {"requires_grad": True, "grad": 0, "backward_branches": []} x2 = np.pi / 4 x2_node = {"requires_grad": True, "grad": 0, "backward_branches": []} # 2. forward propagation y1 = 2 * x1 y1_node = { "requir...
# coding: utf-8 import MySQLdb import datetime, time import csv host = 'localhost' db = MySQLdb.connect(host, 'root', 'vis_2014', 'FinanceVis') cursor = db.cursor() headers = ["Date", "Open", "High", "Low", "Close", "Volume", "Adj Close", "predict_news_word", "predict_twitter_word", "bias_news_word", "bias...
with open('../result/csi.bin', 'U') as inf: for line in inf: feats = line.strip().split(' ') print len(feats) break
from ximea import xiapi import cv2 import time from camera_setting import white_balance_adjustment def adjust_camera(cam): img =xiapi.Image() while cv2.waitKey(33) != 27: cam.get_image(img) data = img.get_image_data_numpy() cv2.imshow("img", data) cam = xiapi.Camera() # start communic...