text
stringlengths
38
1.54M
#!/usr/bin/env python3 import re, sys, os, shutil from subprocess import call def isValidRegion(region): return len(filter(lambda x: len(x) > 0, re.split('[:-]', region))) == 3 def read_frag(frag): chrom, start, end = filter(lambda x: len(x) > 0, re.split('[:-]', frag)) strandiness = '-' if frag[0] =...
import os if "PYCTDEV_ECOSYSTEM" not in os.environ: os.environ["PYCTDEV_ECOSYSTEM"] = "conda" from pyctdev import * # noqa: api def task_pip_on_conda(): """Experimental: provide pip build env via conda""" return {'actions':[ # some ecosystem=pip build tools must be installed with conda when usi...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-11-03 04:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0006_auto_20171103_0219'), ] operations = [ migrations.CreateModel( ...
""" Cruise Analysis Call CruiseAnalysis(V_Cruise,W,S,rh0,CLa,CL0) to obtain Cruise CL,and the required alpha given motocalc and AVL/XFLR5 lift slope info. """ import numpy as np from matplotlib import pyplot as plt from scipy.interpolate import UnivariateSpline from scipy.optimize import fsolve rho = 1.22...
# -*- coding: utf-8 -*- """ Created on Sun Jun 28 09:52:01 2020 @author: Joash """ import numpy as np from os import listdir import knn as K def img2vector(filename): returnVect = np.zeros((1,1024)) fr = open(filename) for i in range(32): lineStr = fr.readline() for j in range(32): ...
from newsfeed_member import models from rest_framework import serializers from member import serializers as member_serializers class NewsfeedType(serializers.ModelSerializer): # pylint: disable=too-few-public-methods class Meta(object): # pylint: disable=too-few-public-methods model = models.N...
from car import Car from controller import Controller def map_from_to(x, a, b, c, d): return (x - a) / (b - a) * (d - c) + c class CarController(Controller): def __init__(self, **kwargs): Controller.__init__(self, **kwargs) self.car = Car(controller_connected=self.is_connected) self...
import wx import os from typing import List, Dict, Callable, Union, Tuple, Any, Type, TYPE_CHECKING import importlib import pkgutil import traceback from amulet.api.errors import LoaderNoneMatched from amulet import world_interface from amulet_map_editor import log from amulet_map_editor.amulet_wx.ui.simple import Si...
import os import sys import time import numpy as np import scipy as sp import h5py as h5 from mpi4py import MPI # module required to use MPI import argparse import skopi as sk from skopi.util import asnumpy, xp # set up MPI environment comm = MPI.COMM_WORLD # communication module size = comm.Get_size() # number of pr...
import sys, random from PyQt4 import QtGui, QtCore # Robot Widget class RobotLink(QtGui.QWidget): def __init__(self, parent, x, y, width, height, fill): super(RobotLink, self).__init__(parent) self._fill = fill self._rotation = 0 self.setGeometry(x, y, width, height) def p...
import bitstring from bitstring import BitArray # to always make sure the address is in the right format def complete_address(value): length = len(value) if length > 32 or length == 0: return 'none' elif length == 32: return value else: limit = 32-length value = str(value) for x in range...
class Solution: def matSearch(self,matrix, N, M, X): row = len(matrix)-1 column = 0 while row >= 0 and column < len(matrix[0]): if matrix[row][column] == X: return 1 elif matrix[row][column] < X: column += 1 elif matrix[row][co...
""" [PPJ Projekt - 1. labos - Generator leksičkog analizatora] @autori: najseksi PPJ ekipa + Dora Franjić """ import sys class LeksickoPravilo: def __init__(self): self.stanje = "" self.regex = "" self.argumenti = [] def dodaj_argument(self, argument): self.argumenti.append(ar...
#!/bin/python3 import os import sys from functools import lru_cache # Complete the stepPerms function below. # A(n) = A(n - 1) + A(n - 2) + A(n - 3) # A(1)=1; A(2)=2; A(3)=4. MODULE = 10000000007 @lru_cache(maxsize=256) def stepPerms(n): if (n == 1): return 1 elif (n == 2): return 2 elif ...
#!/usr/bin/python2.7 # # Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. # import os import time import threading import commands import Ldom import re def execute(cmd): (status, output) = commands.getstatusoutput(cmd) if status != 0: raise Exception("Execution of [%s] failed:\...
# Generated by Django 2.1.5 on 2019-01-12 22:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hackathon', '0002_hackathon_added_by'), ] operations = [ migrations.AddField( model_name='hackathon', name='max_size...
# Third party from utils import generate_resource_name from aws_cdk import core, aws_ssm from aws_cdk.core import Fn, Tag, CfnParameter class InfraSampleStack3(core.Stack): def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) env = "dev" ...
''' Exercise: Write a function, sum_array, that takes an array as an argument and returns the sum of all integers in the array Considerations: Can you write the function such that it terminates gracefully given an unexepected input such as an input that is not an array or an array that contains elements that are not an...
from Tkinter import * class CatchGame: def __init__(self,parent): self.canvas = Canvas(parent, width=200, height=200) self.canvas.grid(column=0, row=0) self.ball = self.canvas.create_oval(90,90,110,110,fill="blue") def move(self): self.canvas.coords(self.ball, 150, 150, 170, 17...
import networkx as nx import matplotlib.pyplot as plt import sys n=int(sys.argv[1]) #50 k=int(sys.argv[2]) #4 p=float(sys.argv[3]) #0.5 seed=int(sys.argv[4]) #1 #G=nx.newman_watts_strogatz_graph(n,k,p,seed) G=nx.watts_strogatz_graph(n,k,p,seed) #G = nx.petersen_graph() #plt.subplot(121) # <matplotlib.axes._s...
import numpy as np numbers = [100, 102, 98, 97, 103] print(np.std(numbers)) print(np.mean(numbers))
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-02-25 17:04 from __future__ import unicode_literals import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_depende...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from schedulers import Scheduler from spaces import Categoric, Numeric class GridSearcher(Scheduler): """Apply grid search for HPO""" def __init__(self, hyperpara...
from threading import Thread class Clock(Thread): def __init__(self, cpu, lock): self._cpu = cpu self._lock = lock def run(self): while True: self._cpu.run_tick() self._lock.acquire()
#coding:utf-8 ''' author : linkin e-mail : yooleak@outlook.com date : 2018-11-15 ''' import time from amipy.core.serverthread import SpiderServer from amipy.core.spiderhub import SpiderHub from amipy.core.loader import SpiderLoader from amipy.core.crawler import WebCrawler from amipy.core.looper import Lo...
class Hero: # We want our hero to have a default "starting_health", # so we can set that in the function header. def __init__(self, name, starting_health=100): # we know the name of our hero, so we assign it here self.name = name # similarly, our starting health is passed in, just like name ...
from os.path import dirname, join from adapt.intent import IntentBuilder from mycroft.skills.core import MycroftSkill from mycroft.util.log import getLogger from os.path import dirname, join from requests import get, post from fuzzywuzzy import fuzz import json __author__ = 'robconnolly, btotharye' LOGGE...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 10 17:08:35 2020 @author: minjie """ %run train_ISIC_gllcmeta.py --datasets ../data/ISIC18/task3/ISIC2018_Task3_Training_Input_coloradj --net resnet50_singleview --out_dir ../checkpoints/resnet50_singleview_fast --num_epochs 50 --lr 0.005 %run ...
#!/usr/bin/env python3 import utils, open_color, arcade # importing the libraries necessary to run the program utils.check_version((3,7)) SCREEN_WIDTH = 800 #sets the width of the screen to 800 pixels SCREEN_HEIGHT = 600 #sets the height of the screen to 600 pixels SCREEN_TITLE = "Smiley Face Example" #sets t...
from matplotlib import pyplot as plt from matplotlib.patches import Ellipse from scipy.stats import chi2 import numpy as np def results(stream, result, config): pass def display_err(err): #print(err) #for it, i in enumerate(err): # err[it]= i/(it+1) plt.plot(err[1:]) #plt.yscale('log') ...
num = list(map(int, input())) zero_cnt = 0 # 전체 0으로 바꿀 때 필요한 횟수 one_cnt = 0 # 전체 1으로 바꿀 때 필요한 횟수 if num[0] == 1: zero_cnt += 1 else: one_cnt += 1 for i in range(len(num) - 1): if num[i] != num[i+1]: if num[i+1] == 1: zero_cnt += 1 else: one_cnt += 1 print(min(zer...
# -*- encoding: utf-8 -*- #from .utils import * from .CallerClasses import * from .InteractionMatrix import * from .DataClasses import * from .ExperimentClass import * from .DataGeneration import * from .logger import * __version__ = "0.0.2" __author__ = 'Aleksandra Galitsyna and Dmitry Mylarcshikov' __email__ = 'agal...
import pandas as pd import base64 import os import pdfkit import boto3 import datetime from configparser import ConfigParser configure = ConfigParser() configure.read("secret.ini") ACCESS_KEY = configure.get("AWS", "ACCESS_KEY") SECRET_KEY = configure.get("AWS", "SECRET_KEY") BUCKET = configure.get("AWS", "BUCKET") ...
#from google.appengine.ext import webapp #[START imports] import webapp2 from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import users from modelHandlers import departmentHandler, studentHandler from modelHandlers import courseHandler, ...
import requests import time from time import sleep higher = 0 letraTemporal = '' password = "p4ssw0r" ip = '192.168.0.29' status_code = 401 while status_code != 200: for letra in range(127): start = time.time() r = requests.get('http://'+ip+'/authentication/example2/', auth=('hacker', str(passw...
#-*- coding:utf-8 -*- from flask import Flask ,request, g, render_template, url_for, redirect, abort from manage import blue_print import config import json from account.lib.user_lib import auth_user from dns.lib.user_domain_lib import get_domain_list_by_user_id from dns.lib.domain_lib import get_all_domain_dict_lib, ...
import parser import json def get_new_in_radius(radius): houses = parser.results_in_radius(radius) with open("cache/checked.json", "r") as json_file: checked = json.load(json_file) new = [] for house in houses: if house["PublicatieId"] in checked: continue ...
''' Selfedu001133PyBegin_v11_list_TASKmy04_20200621.py нарисовать два треугольника, согласно образцу [!] задание давать только после последовательного выведения сходящихся элементов подсказка 1: замените точки числами (количество элементов) ''' n = int(input("Количество элементов списка: ")) list1 = [] for i in range(n...
import os, sys import json import configparser import bpy, bpy_types import bmesh import struct # TODO: # - Apply modifiers before export # - Export list of assets and textures (and code to preload) # e.g. /Applications/Blender/blender.app/Contents/MacOS/blender -b srcart/forest.blend -P script/export_scene.py -- l...
import json with open('know-how.json', 'r') as f: data = json.load(f) #Get the questions import requests # from lxml import html counter = 0 import re regex = '(?<=href=\"\/\/www\.wikihow\.com\/)[A-Za-z\-]*(?=\")' def scrape(data): category = data["name"] print(category) try: page = requests....
import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mysock.connect(('data.pr4e.org', 80)) cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode() #encode > convert from unicode to UTF-8 mysock.send(cmd) while True: data = mysock.recv(512) if (len(data) < 1): bre...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'OpinsysAuthProvider.school' db.add_column('opinsys_opinsysauthprovider', 'school', self.gf...
import unittest from game import Game from players import AIPlayer class TestWinningStateDetection(unittest.TestCase): def test_top_row_is_winning(self): game_board = Game() game_board.board = [ "X", "X", "X", "O", "O", None, None,None,None ] ...
from metric.metric_abstract import AbstractClassifierMetric import numpy as np # class MyEvaluator(AbstractEvaluation): # def evaluate_dataset(self,dataset,plabel,pprob): # pa_events = convertAndMergeToEvent(dataset.set_window,plabel) # a_events = convertAndMergeToEvent(dataset.set_window,dataset.la...
import collections import sys sys.setrecursionlimit(100000) N, M, H = map(int, sys.stdin.readline().split()) queue = collections.deque([]) box = [[]for i in range(H)] check_num = 2 swap = 0 result_day = 0 ss = 0 for j in range(H): for i in range(M): box[j].append(list(map(int, sys.stdin.readline().split()...
import os import cv2 import csv import numpy as np from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from keras.models import Sequential, Model from keras.layers import Lambda, Cropping2D, BatchNormalization, ELU from keras.layers.core import Dense, Dropout, Activation, Flat...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ SYNOPSIS extract_straight [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO...
classmates = ['Michael', 'Bob', 'Tracy'] classmates.insert(1,'Jack') print classmates classmates = ('Michael', 'Bob', 'Tracy') classmates = ('Jack',) print type(classmates) print classmates s = set([1, 2, 3]) s.add(4) print s s.remove(2) print s l = range(100) print l print l[1:10] print l[:10] print l[3:] print l...
# Chapter 02 - Unit 11 - health """ Example: Input: 5 16 17 15 16 17 180 175 172 170 165 67 72 59 62 55 5 15 17 16 15 16 166 156 168 170 162 45 52 56 58 47 Output: 16.2 172.4 63.0 15.8 164.4 51.6 A """ class Student: def __init__(self, age, height, weight): self.age = age self.height = height ...
import click import cv2 import pdf2image import pytesseract as pt import logging from data_utils import * logger = logging.getLogger("test.py") logger.setLevel(logging.DEBUG) class ocr_reader: def __init__(self, input_file, output_file, text=""): self.input_file = input_file self.output_file = o...
from CyberSource import * import os from importlib.machinery import SourceFileLoader config_file = os.path.join(os.getcwd(), "data", "Configuration.py") configuration = SourceFileLoader("module.name", config_file).load_module() def available_reports(): try: start_time = "2018-10-01T00:00:00.0Z" e...
# # @lc app=leetcode id=79 lang=python3 # # [79] Word Search # # https://leetcode.com/problems/word-search/description/ # # algorithms # Medium (32.07%) # Total Accepted: 314K # Total Submissions: 978.9K # Testcase Example: '[["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]]\n"ABCCED"' # # Given a 2D board and...
# -*- coding: utf-8 -*- # @Time : 2019-10-20 19:29 # @Author : icarusyu # @FileName: 2.py # @Software: PyCharm # def f(): # n = int(input()) # zheng = 1 # ni = 0 # while n>0: # zheng, ni = 3*zheng + ni, zheng + 3*ni # # print(zheng,ni) # n-=1 # return zheng % (10**9+7) # def...
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.2.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import cma_gui as cma...
#!/usr/bin/env python import rospy from geometry_msgs.msg import PoseStamped from styx_msgs.msg import Lane, Waypoint, TrafficLightArray, Intersection from geometry_msgs.msg import TwistStamped import math import tf import numpy as np ''' This node will publish waypoints from the car's current position to some `x` d...
import requests import time from bs4 import BeautifulSoup import os import re import urllib.request import json #Goal:Find all the jackets that the prices are above $2000 usd, and download the pictures. #func 1 => find "get_web_page(url)" return resp.text: #func 2 => Go to each page(39 pages in total), and parse all f...
# def max_difference(a): # max_difference = -float("inf") # for i in range(len(a)): # for j in range(i+1, len(a)): # if a[j] - a[i] > max_difference: # max_difference = a[j] - a[i] # return max_difference def max_difference(a): maxDifference = -float("inf") min_n...
from typing import Optional class vigenere_cipher: def __init__(self): self.capitalized = [] # This function helps preserve capitalization def get_num(self, char, idx): num = ord(char) if (num > 64 and num < 91): num = num - 65 self.capitalized.append(True)...
import demistomock as demisto # noqa: F401 from CommonServerPython import * def main() -> None: ORANGE_HTML_STYLE = "color:#FF9000;font-size:275%;>" GREEN_HTML_STYLE = "color:#00CD33;font-size:275%;>" RED_HTML_STYLE = "color:#FF1744;font-size:275%;>" DIV_HTML_STYLE = "display:block;text-align:center...
from datetime import datetime def notnight(func): def wrapper(): if 3 <=datetime.now().hour < 20 : print('You can shout') func() else: print('Maybe its night time.....SSH! donot shout') pass return wrapper @notnight # shouting=notnight(shoutin...
import os import json from log import loggingSetting from ut import pushaction, unlock, getAccounts, runPool, buyram logger = loggingSetting("airdrop") def main(password): pass # for i in x[1:]: # print(pushaction("betdicetoken", "signup", [i, "1000.0000 DICE"], i)) # 1000dice # print( # pu...
import pandas as pd import numpy as np class ID3: """ Public Method """ # Uses the ID3 algorithm to generates the decision tree @staticmethod def generate_tree(df: pd.DataFrame, attribute_dict: {}, use_gain_ratio: bool, use_pruning: bool) -> {}: if len(df) == 0: return ...
# import openpyxl # wb=openpyxl.load_workbook('各班成绩表.xlsx') # ws=wb.active # rngs=list(ws.values) # d={} # for row in rngs[1:]: # if row[0] in d.keys(): # d[row[0]]+=[row] # else: # d[row[0]]=[row] # nwb=openpyxl.Workbook() # for k,v in sorted(d.items()): # nws=nwb.create_sheet(k) # nws....
import pandas as pd import os cwd = os.getcwd() project_wd = os.path.dirname(cwd) download_wd = os.path.join(project_wd, "Download_Data") data_wd = os.path.join(download_wd, "Data") countries_wd = os.path.join(data_wd, "all_Countries.csv") us_states_wd = os.path.join(data_wd, "us_States.csv") fips_states_wd =...
# Django from django.contrib import admin # Models from .models import Onboard class OnboardAdmin(admin.ModelAdmin): model = Onboard list_display = ('account', 'isOnboarded') list_filter = ('account',) search_fields = ('account',) ordering = ('account',) admin.site.register(Onboard, Onboar...
import requests from bs4 import BeautifulSoup import pandas as pd import time #srp-listing clickable-area paid-listing astro-dxc #srp-listing clickable-area gump #srp-listing clickable-area sp #srp-listing clickable-area rd #srp-listing clickable-area mdm main_list = [] def extract(url): page...
import os import logging def logModul(topicName,fileName): """ ##设置日志处理 :param topicName: 日志主题 :param fileName: 日志存储文件 :return: """ logger = logging.getLogger(topicName) logging.basicConfig(level=logging.INFO) ch = logging.StreamHandler() fh = logging.FileHandler(os.path.join(o...
# -*-coding:utf-8-*- # def verify(num): # if num > 0: # print "正数" # if num < 0: # print "负数" # if num == 0: # print "零" # num = float(raw_input("请输入一个数:")) # verify(num) # list = [2,7,6,8,10] # print sum(list) # avg = float(sum(list))/float(len(list)) # print avg # list = [] # tr...
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from django.http.response import JsonResponse from EmployeeApp.models import Departments, Employees from EmployeeApp.serializers import DepartmentSerializer, EmployeeSerializer from dj...
"""Amavis frontend default settings.""" DATABASE_ROUTERS = ["modoboa_amavis.dbrouter.AmavisRouter"] SILENCED_SYSTEM_CHECKS = ["fields.W342", ]
import regex as re from functools import reduce PATTERN = re.compile(r'((\d)\2+)') def read_data(file_name): file_ref = open('../../resources/' + file_name, 'r') result = file_ref.read() file_ref.close() return result def run(): data = read_data('day1.txt') matches = PATTERN.findall(data) ...
# Returns a match for any digit between 0 and 9 import re txt = "8 times before 11:45 AM" #Check if the string has any digits: x = re.findall("[0-9]", txt) print(x) if x: print("Yes, there is at least one match!") else: print("No match")
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import requests from bs4 import BeautifulSoup import pymysql conn = pymysql.connect(host='localhost',user='root',password='123456789',database='lcc',charset='utf8') cursor = conn.cursor() url = 'https://tw.buy.yahoo.com/category/43859...
#Reversing a string in python import sys #take input string from user ip_string = input() op_string = ip_string[::-1] print(op_string)
import urllib import json response = urllib.urlopen( "http://search.twitter.com/search.json?q=microsoft" ) pyresponse = json.load(response, encoding="utf-8") # type(pyresponse) = 'dict' This denotes it as a dictionary where # results can be obtained using something like pyresponse.keys() which # will give a list...
import googleapiclient.discovery import json import youtube_dl from secret import spotify_id, spotify_token, api_key from urllib.parse import urlparse, parse_qs import requests class CreatePlaylist: def __init__(self): self.user_id = spotify_id self.spotify_token = spotify_token self.ap...
#!/usr/bin/env python import rospy from std_msgs.msg import String from sensor_msgs.msg import NavSatFix import math def callback(msg): rospy.loginfo( "Input position: [%f,%f, %f]", msg.latitude, msg.longitude,msg.altitude) #fixed values a = 6378137; b = 6356752.3142; f = (a - b) / a; e_sq ...
"""Module for SIA Alarm Control Panels.""" import logging from homeassistant.core import callback from homeassistant.helpers.entity import generate_entity_id from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.component...
from dataclasses import dataclass import logging import jaydebeapi from tabulate import tabulate HIVE_DRIVER_CLASSPATH = "org.apache.hive.jdbc.HiveDriver" DEFAULT_LOGGING_FORMAT = '%(asctime)s :: %(levelname)s :: %(module)s :: %(message)s' @dataclass class QueryResult: columns: list rows: list def __ta...
# Rename a Directory import os print(os.getcwd()) os.mkdir('new_child') print('Created new_child dir') print(os.listdir()) os.rename('new_child', 'old_child') print('Renamed new_child as old_child') print(os.listdir())
from math import factorial class factor: def factorial(n): if n == 0: return 1 elif n < 0: return "number is in negative can't do factorial" else: return (n * (factorial(n - 1))) print(factorial(5)) if __name__=='__main__': call...
''' Created on Jun 12, 2020 @author: Poshan ''' class Lambda1: def useLambdaFunctions(self): x = lambda givenNo : givenNo + 15 y = lambda a,b : a * b print(x(10)) print(y(10,20)) obj = Lambda1() obj.useLambdaFunctions()
"""WPSClient Class. The :class:`WPSClient` class aims to make working with WPS servers easy, even without any prior knowledge of WPS. Calling the :class:`WPSClient` class creates an instance whose methods call WPS processes. These methods are generated at runtime based on the process description provided by the WPS s...
''' @author :kpkishankrishna Write a piece of Python code that prints out the string 'hello world' if the value of an integer variable, happy, is strictly greater than 2. ''' HAPPY = int(input()) if HAPPY > 2: print("hello world")
######## Picamera Object Detection Using Tensorflow Classifier ######### # # Author: Evan Juras # Date: 4/15/18 # Description: # This program uses a TensorFlow classifier to perform object detection. # It loads the classifier uses it to perform object detection on a Picamera feed. # It draws boxes and scores around th...
"""calculate the diffs for mathdiff.py and tablediff.py""" import py def dodiff(v1, v2, func=None, thelimit=0): """find the diff between v1 and v2. func is the function used to find the diff 1. text diff a. if same, use v1 return (v1, False) b. if diff, use v1 and mark as err ...
from django.contrib import admin from .models import Service class ServicesAdmin(admin.ModelAdmin): list_display = ['order_by','title', 'slug', 'is_published'] list_display_links = ('title', 'slug',) list_editable = ('order_by','is_published',) prepopulated_fields = {'slug': ('title',)} admin.site.r...
from __future__ import division class PixelColor(object): """ Represents a single neopixel color (either RGB or RGBW). The ``red``, ``blue``, ``green``, and ``white`` components can either be between 0 and 1 (normalized), or between 0 and 255. PixelColor will attempt to determine automatically w...
import numpy as np from matplotlib import pyplot as plt import math class ODESolver: def __init__(self,F): self.F = F def set_Inital_Conditions(self,y): self.y = y def solve(self, x, interval_stop, step): self.interval_start = x self.interval_stop =...
from reddit import client from reddit.user import User from reddit.reddits import Subreddit Donzuh = client.login('Donzuh') Donzuh.me() # python = Subreddit("python") # # python.hot()
# coding: utf-8 import sys sys.path.append('..') sys.path.append('../src') import learner import config if __name__ == "__main__": if len(sys.argv) < 2 or sys.argv[1] not in ["train", "play"]: print("[USAGE] python leaner_test.py train|play") exit(1) alpha_zero = learner.Leaner(config.config)...
import string step=int(input("Please enter step for Cesar code: ")) lowercase_leters=list(string.ascii_lowercase) cesar=dict(zip(lowercase_leters,lowercase_leters[step:]+lowercase_leters[:step])) print("Cesar code with step %i is:" % step, cesar)
from typing import TextIO def setup_lights(writer: TextIO): _place_light(writer, 1.3, 2.4, 0.8) _place_light(writer, 1.3, 2.4, 1.5) _place_light(writer, 1.3, 2.4, 2.2) def _place_light(writer: TextIO, x, y, z): writer.write(f""" light_source {{ <{x},{y},{z}> color Gray50 }} // looks_like {{ Lig...
# ------------------------------------------------------------------------------------- # Calls contour data set training script with different gaussian regularization # loss weights. # ------------------------------------------------------------------------------------- import numpy as np import torch from train_cont...
""" @file @brief This file sends anonymous application metrics and errors over HTTP @author Jonathan Thomas <jonathan@openshot.org> @section LICENSE Copyright (c) 2008-2018 OpenShot Studios, LLC (http://www.openshotstudios.com). This file is part of OpenShot Video Editor (http://www.openshot.org), an open-sour...
# Copyright 2008-2018 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) """These are the plugins included with Lino XL. Contacts management =================== .. autosummary:: :toctree: countries contacts addresses phones households humanlinks ...
from cvxopt import blas, lapack, solvers from cvxopt import matrix, spdiag, mul, div, sparse from cvxopt import spmatrix, sqrt, base import numpy as np """ 2x + y + 3z = 1 2x + 6y + 8z = 3 6x + 8y + 18z = 5 Solution: (x, y, z) = ( 3/10, 2/5, 0) CVXOPT cvxopt.lapack.gesv(A, B[, ipiv = None]) S...
import os os.chdir(os.path.dirname(__file__)) dirs = ["data", "data/requirements_xml"] [os.mkdir(n) for n in dirs if not os.path.exists(n)]
from pilco.models import SMGPR import numpy as np import os import oct2py octave = oct2py.Oct2Py() dir_path = os.path.dirname(os.path.realpath("__file__")) + "/tests/Matlab Code" octave.addpath(dir_path) from gpflow import config float_type = config.default_float() def test_sparse_predictions(): np.random.seed(0)...
#!/usr/bin/env python """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" mm |<----84---->| |<---60--->| | |____ | | J3 /o____|=o=o=__+__ _____ / /...