content
stringlengths
5
1.05M
from datetime import datetime import os import subprocess from pathlib import Path FILE_SUFFIX = datetime.today().strftime('%Y%m%d') home = str(Path.home()) root = os.path.join(home, "Desktop") for subdir in [x[0] for x in os.walk(root)]: # master = os.path.join(subdir, "macro-output", "master.mp3") master = os.path.join(subdir, "master.mp3") source = os.path.join(subdir, "source.jpg") if os.path.exists(master) and os.path.exists(source): subprocess.check_output([ 'ffmpeg', '-loop', '1', '-i', source, '-i', master, '-c:a', 'aac', '-c:v', 'libx264', '-shortest', f'{os.path.basename(subdir)}{FILE_SUFFIX}.mp4' ], cwd=subdir)
import Quandl import pandas as pd import pickle import matplotlib.pyplot as plt from matplotlib import style style.use('fivethirtyeight') # Not necessary, I just do this so I do not show my API key. api_key = open('quandlapikey.txt','r').read() def state_list(): fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states') return fiddy_states[0][0][1:] def grab_initial_state_data(): states = state_list() main_df = pd.DataFrame() for abbv in states: query = "FMAC/HPI_" + str(abbv) df = Quandl.get(query, authtoken=api_key) # NOTE: This is a fix that is not addressed in the tutorial df.columns = [str(abbv)] df[abbv] = (df[abbv] - df[abbv][0]) / df[abbv][0] * 100.0 if main_df.empty: main_df = df else: main_df = main_df.join(df) print(main_df.head()) pickle_out = open('fiddy_states3.pickle', 'wb') pickle.dump(main_df, pickle_out) pickle_out.close() def HPI_Benchmark(): df = Quandl.get('FMAC/HPI_USA', authtoken=api_key) print(df.head()) abbv = 'United States' # NOTE: This is a fix that is not addressed in the tutorial df.columns = [str(abbv)] df[abbv] = (df[abbv] - df[abbv][0]) / df[abbv][0] * 100.0 return df # grab_initial_state_data() # fig = plt.figure() # ax1 = plt.subplot2grid((1, 1), (0, 0)) HPI_data = pd.read_pickle('fiddy_states3.pickle') # benchmark = HPI_Benchmark() # # HPI_data.plot(ax=ax1) # benchmark.plot(ax=ax1, color='k', linewidth=10) # # plt.legend().remove() # plt.show() HPI_State_Correlation = HPI_data.corr() print(HPI_State_Correlation) print(HPI_State_Correlation.describe())
# For installation: "python setup.py install" from distutils.core import setup, Extension # Nombre del módulo y archivos que contienen el código fuente. module1 = Extension("optimcore", define_macros=[('MAJOR_VERSION', '0'), ('MINOR_VERSION', '1')], include_dirs = ['OptimCore/include'], sources=["optimcoremodule.cpp", "OptimCore/source/dynamicModel.cpp"]) # Nombre del paquete, versión, descripción y una lista con las extensiones. setup(name="optimcore", version="0.1", description="Evolutionary optimization library for parameter estimation.", author="Fidel Echevarria Corrales", url="https://fidelechevarria.github.io/", ext_modules=[module1], long_description=''' Evolutionary optimization library for parameter estimation. Bla bla bla. ''')
# Time: O(n) # Space: O(1) class Solution(object): def twoSum(self, nums, target): start, end = 0, len(nums) - 1 while start != end: sum = nums[start] + nums[end] if sum > target: end -= 1 elif sum < target: start += 1 else: return [start + 1, end + 1]
import os import sys import re from time import sleep import time import random from microMolder import LambdaMolder from microFront import CloudFrontMolder from microGateway import ApiGatewayMolder from microDynamo import DynamoMolder from microUtils import loadConfig, roleCleaner, serviceID from MMAnsibleDeployAll import deployStart # TESTERS... from microGateway_test import ApiGatewayTester import awsconnect from awsconnect import awsConnect # sudo ansible-playbook -i windows-servers API_Name.yaml -vvvv dir_path = os.path.dirname(__file__) real_dir_path = os.path.dirname(os.path.realpath(__file__)) # directory='/path/to/Ansible_Deployer/ansible' # python Main_DEPLOYER.py -DY dev "test,stage,prod,tpp" "xx_tablename" ENVR.yaml API_Name true class TemporalDeployer(): def __init__(self, directory=None): pass # CREATE DEFINITIONS def Define(self, type_in, svc_in, origin, global_accts, sendto, config, triggers=None, targetAPI=None, fullUpdate=None): accID = origin['account'] region = origin['region'] accountRole = global_accts[accID]['role'] print(" ## USING ## %s--> %s, role %s, account originDefinition %s, config %s, copyAnsible to %s" % (type_in, svc_in, accountRole, accID, config, sendto)) print(" !!! !! to assume <cross_acct_role> ROLE make sure you set 'assume_role' in 'ENVR.yaml' to True or False as needed") awsconnect.stsClient_init() sts_client = awsconnect.stsClient print(" ________________-") print(" %s" % (accID)) print(" ________________-") if 'eID' in origin: eID = origin['eID'] if 'services_map' in origin: mapfile = origin['services_map'] eID = serviceID(origin['account'], mapfile, origin['all']) aconnect = awsConnect( accID, eID, origin['role_definer'], sts_client, region) aconnect.connect() results = None if type_in == "-CF": cm = CloudFrontMolder("ansible") acctID, target, acctTitle, ready = cm.cfront_describe( svc_in, aconnect, origin, global_accts, sendto) print("CF here") elif type_in == "-L": lm = LambdaMolder("ansible") acctID, target, acctTitle, ready = lm.lambda_describe( svc_in, aconnect, origin, global_accts, triggers, sendto, targetAPI, fullUpdate) elif type_in == "-G": gm = ApiGatewayMolder("ansible") if targetAPI == svc_in: acctID, target, acctTitle, ready = gm.describe_GatewayALL( svc_in, aconnect, origin, global_accts, triggers, sendto, targetAPI, fullUpdate, True) else: acctID, target, acctTitle, ready = gm.describe_GwResource( svc_in, aconnect, origin, global_accts, triggers, sendto, targetAPI, fullUpdate, True) elif type_in == "-DY": dy = DynamoMolder("ansible") acctID, target, acctTitle, ready = dy.define( svc_in, aconnect, origin, global_accts, sendto) return acctID, target, acctTitle, ready # CHECK GATEWAY FOR OPTIONS. LOOK TO SEE IF OPTIONS ARE THERE!!! def TEST(self, type_in, svc_in, acct, acctName, global_accts, config, targetAPI): accID = acct region = 'us-east-1' accountRole = global_accts[accID]['role'] print(" ## OPTIONS TEST ## %s--> %s, role %s, account originDefinition %s, config %s, copyAnsible to %s" % (type_in, svc_in, accountRole, accID, config, sendto)) print(" !!! [TEST] !! to assume <cross_acct_role> ROLE make sure you set 'assume_role' in 'ENVR.yaml' to True or False as needed") awsconnect.stsClient_init() sts_client = awsconnect.stsClient eID = 10000010001 if 'eID' in global_accts[accID]: eID = global_accts[accID]['eID'] aconnect = awsConnect(accID, eID, accountRole, sts_client, region) aconnect.connect() results = None if type_in == "-CF": cm = CloudFrontMolder("ansible") print("CF TEST here") elif type_in == "-L": lm = LambdaMolder("ansible") print("LAMBDA TEST here") elif type_in == "-G": gm = ApiGatewayTester("ansible") print("GATEWAY TEST here") if targetAPI == svc_in: errors = gm.test_GatewayALL( svc_in, aconnect, acct, acctName, global_accts, targetAPI) else: errors = gm.test_GwResource( svc_in, aconnect, acct, acctName, global_accts, targetAPI) elif type_in == "-DY": dy = DynamoMolder("ansible") print("DYNAMO TEST here") return errors # EXECUTE AGAINST DEFINITIONS # # # PRODUCE RESULTS PASS/FAIL # python microMolder.py -L xx-LambdaName true ENVR.yaml API_Name true # python Main_DEPLOYER.py -DY dev "test,stage" xx_tablename ENVR.yaml API_Name true # python Main_DEPLOYER.py -G dev "stage" API_Name ENVR.yaml API_Name true # . OR # python Main_DEPLOYER.py "xx-stage,xx-test" xx_tablename ENVR.yaml # python Main_Deployer.py "xx-test" xx_tablename ENVR.yaml # # # if __name__ == "__main__": # global directory directory = os.path.join(dir_path, '../../ansible') found = None length = 0 tot = len(sys.argv) - 1 SkipDefinition = False type_in = str(sys.argv[1]).strip() if 'help' in type_in: print(" ************************************************************") print(" Try using the following PSUEDO after *CONFIG.yaml is correct :") print(' python Main_DEPLOYER.py -L dev "test,stage" * ENVR.yaml API_Name true') print( " -[NOTE]--> the above will describe 'dev' and then deploy ALL * to 'test,stage' ") print( " -[NOTE]--> the above will describe 'dev' and then deploy to 'test,stage' ") print( " -[NOTE]--> the above can also deploy API only using -G , CloudFront using -CF, DynamoDB using -DY ") print( ' python Main_DEPLOYER.py -G dev "test,stage" activities[*] ENVR.yaml API_Name true') print( " -[NOTE]--> the above will describe activities api with all methods * ") print( ' python Main_DEPLOYER.py -G dev "test,stage" *[*] ENVR.yaml API_Name true') print(' python Main_DEPLOYER.py -G dev "test,stage" API_Name ENVR.yaml API_Name true') print( " -[NOTE]--> the above will deploy all API under API_Name... both rolename(API_Name) and targetAPI MUST be SAME ") print(" OR to deploy without Defining ") print(" -[NOTE]--> the above will deploy to stage,test ") print(" ************************************************************") exit() targetAPI = fullUpdate = target_environments = None if tot < 6: missing = 6 - tot totTypeIn = len(type_in) msg = "[E] %s arguments missing... found:%s needs 6+ arguments" % ( missing, tot) if "-" in type_in and totTypeIn < 4: example = "... for example: \n python Main_DEPLOYER.py -L dev 'test,stage' Quickboks_temp ENVR.yaml" msg = "%s %s" % (msg, example) raise Exception(msg) elif totTypeIn > 4: SkipDefinition = True if not SkipDefinition: source_environment = str(sys.argv[2]).strip() target_environments = str(sys.argv[3]).strip().split(",") role = str(sys.argv[4]).strip() config = str(sys.argv[5]).strip() # ENVR.yaml if '/' in str(sys.argv[6]): sendto = str(sys.argv[6]).strip() # 'some path' else: sendto = os.path.join(dir_path, '../../ansible/roles') sys.argv.append(sys.argv[7]) sys.argv[7] = sys.argv[6] roleString = roleCleaner(role) if not "roles/" in sendto: sendto = "%s/%s" % (sendto, roleString) # targetAPI = str(sys.argv[7]).strip() ### API_Name if len(sys.argv) > 7: targetAPI = str(sys.argv[7]).strip() print(sys.argv[7]) if targetAPI.lower() == "none" or targetAPI.lower() == "null" or targetAPI == "*": targetAPI = None # fullUpdate = str(sys.argv[8]).strip() ### true if tot > 8: fullUpdate = str(sys.argv[8]).strip().lower() # true if fullUpdate == "none" or fullUpdate == "null" or fullUpdate == "false": fullUpdate = False else: fullUpdate = True else: target_environments = type_in.split(",") role = str(sys.argv[2]).strip() config = str(sys.argv[3]).strip() start_time = time.time() fullpath = "%s/%s" % (real_dir_path, config) origin, global_accts = loadConfig(fullpath, source_environment) # if 'eID' in origin: # eID = origin['eID'] # if 'services_map' in origin: # mapfile = origin['services_map'] # eID = serviceID(origin['account'], mapfile, origin['all']) triggers = origin['triggers'] if triggers is None: raise ValueError( "[E] config file [ %s ] did not load correctly.. PLEASE check / fix and try again" % (fullpath)) td = TemporalDeployer() ready = None if not SkipDefinition: acctID, target, acctTitle, ready = td.Define( type_in, role, origin, global_accts, sendto, config, triggers, targetAPI, fullUpdate) print("-[DEFINED]-- %s seconds ---" % (time.time() - start_time)) # BELOW to skip deployment # exit() if ready or SkipDefinition: deploy_time = time.time() print("########################################################") print("########### Ansible DEPLOYMENT START ##################") print("########################################################") role = role results = deployStart(global_accts, target_environments, roleString) for k, v in results.items(): msg = "%s Account: %s, %s" % (v['name'], k, v['value']) print(msg) if "-G" in type_in: acct = v['value'] acctName = v['name'] print(" GATEWAY releasing ---> checking OPTIONS") # acctID, target, acctTitle, ready = td.TEST(type_in,role,acct,acctName,global_accts,config,targetAPI) print("-[DEPLOYED]-- %s seconds ---" % (time.time() - deploy_time)) # print(global_accts) #print (target_environments) # //logger.info("Finished") print("--[FIN]- %s seconds ---" % (time.time() - start_time))
from model import common import torch import torch.nn as nn class ClipL1(nn.Module): def __init__(self, clip_min=0.0, clip_max=10.0): super(ClipL1, self).__init__() self.clip_max = clip_max self.clip_min = clip_min def forward(self, sr, hr): loss = torch.mean(torch.clamp(torch.abs(sr-hr), self.clip_min, self.clip_max)) return loss
from util.credentials.credentials_provider import CredentialsProviderFactory from util.app_util import AppUtil from util.grant_util import GrantUtil from util.credential_test_util import CredentialsTestUtil from util.role_util import RoleUtil from util.keyvault_util import KeyVaultUtil from util.validator_util import ValidatorUtil from util.provider_util import ProviderUtil from util.config import Config import logging, json import time, os APP_NAME = "LaceworkSAAudit" from util.credentials.credentials_provider import CREDENTIALS_TYPE_APP, CREDENTIALS_TYPE_PORTAL from util.credentials.credentials_provider import KEY_CLIENT_SECRET, KEY_APP_ID class AppManager(object): def __init__(self, config, registerProviders): if not isinstance(config, Config): raise Exception("Invalid Config Object") self.__registerProviders = registerProviders self.__config = config self.__clientSecret = config.getUserClientSecret() self.__credentialsProvider = CredentialsProviderFactory.getCredentialsProvider(config) self.__appUtil = AppUtil(self.__credentialsProvider) self.__grantUtil = GrantUtil(self.__credentialsProvider) self.__validatorUtil = ValidatorUtil(self.__credentialsProvider) self.__providerUtil = ProviderUtil(self.__credentialsProvider) def run(self): updateApp = self.__config.isUpdateApp(); appExists = self.__appUtil.getAppId() != None if appExists and not updateApp: logging.info("App already exists and UpdatePermissionsForExistingApp is " + str(updateApp)) exit(1) elif not appExists and updateApp: logging.info("App does not exist and UpdatePermissionsForExistingApp is " + str(updateApp) + " Nothing to Update") exit(1) if self.__registerProviders: self.__registerProvider() self.__createOrUpdateApp() try: if not appExists: if self.__config.getCredentials().get('type') != CREDENTIALS_TYPE_PORTAL: self.__testCredentials() else: logging.info("Skipping credentials test as it requires permissions to be granted to the App via the UI") else: logging.info("App Updated Successfully. New Client Secret Not generated") self.__clientSecret = None except: logging.exception("Error testing Credentials") self.__printCredentials() if not appExists and self.__config.getCredentials().get('type') == CREDENTIALS_TYPE_PORTAL: logging.info("Please remember to grant permissions for API access to the App " + APP_NAME + " before using credentials.") def __registerProvider(self): self.__providerUtil.registerProvider() def __createOrUpdateApp(self): self.__validatorUtil.validateUserPermissions() appId = self.__appUtil.createAppIfNotExist(self.__clientSecret, APP_NAME); if self.__config.getCredentials().get('type') != CREDENTIALS_TYPE_PORTAL: self.__grantUtil.grantPermission(appId); else: logging.info("Skipping permissions grant as portal credentials do not have required permissions") roleUtil = RoleUtil(appId, self.__credentialsProvider) roleUtil.makeRoleAssignments() keyVaultUtil = KeyVaultUtil(self.__credentialsProvider) keyVaultUtil.setKeyVaultPolicy() def __testCredentials(self): exception = None for i in range(1,5): try: appId = self.__appUtil.getAppId() credentials = {"type": CREDENTIALS_TYPE_APP, KEY_APP_ID: appId, KEY_CLIENT_SECRET : self.__clientSecret} config = Config(credentials, None, [], True, self.__config.getTenantId(), None, self.__config.getCloudType().name, [], False) appCredentialsProvider = CredentialsProviderFactory.getCredentialsProvider(config) credentialsTestUtil = CredentialsTestUtil(appCredentialsProvider) credentialsTestUtil.listKeys() exception = None break except Exception as e: logging.exception("Error testing credentials: Retrying test" + str(e.message)) exception = e time.sleep(5) if exception != None: logging.error("Error testing credentials: " + exception.message) def __printCredentials(self): appId = self.__appUtil.getAppId() map = {"CLIENT_ID": appId, "CLIENT_SECRET": self.__clientSecret, "TENANT_ID": self.__config.getTenantId()} out= json.dumps(map, sort_keys=True, indent=4, separators=(',', ': ')) logging.info("\n" + out) if self.__clientSecret: try: path = os.getcwd() +"/credentials.txt" f = open(path, "w") f.writelines(out) f.close() logging.info("Copy Of Credentials written to file: " + path) except: logging.exception("Could not write data to file ")
""" Make a movie out of a shotgun VAE projection and an audio file. """ __date__ = "Novemeber 2019" import matplotlib.pyplot as plt plt.switch_backend('agg') import numpy as np import os from scipy.io import wavfile from scipy.spatial.distance import euclidean import torch from torch.utils.data import Dataset, DataLoader from ava.models.vae import VAE def shotgun_movie_DC(dc, audio_file, p, output_dir='temp', fps=30, \ shoulder=0.05, c='b', alpha=0.2, s=0.9, marker_c='r', marker_s=40.0, \ marker_marker='*'): """ Make a shotgun VAE projection movie with the given audio file. This will write a series of images to ``output_dir``. To make the ``.mp4``, a couple extra commands will have to be entered in the command line: :: $ ffmpeg -r <fps> -i <output_dir>/%04d.png -i "<audio_file>" -c:a aac -strict -2 -shortest -y output.mp4 Parameters ---------- dc : ava.data.data_container.DataContainer See ava.data.data_container. audio_file : str Path to audio file. p : dict Preprocessing parameters. Must contain keys: ``'fs'``, ``'get_spec'``, ``'num_freq_bins'``, ``'num_time_bins'``, ``'nperseg'``, ``'noverlap'``, ``'window_length'``, ``'min_freq'``, ``'max_freq'``, ``'spec_min_val'``, ``'spec_max_val'``, ``'mel'``, ... output_dir : str, optional Directory where output images are written. Defaults to ``'temp'``. fps : int, optional Frames per second. Defaults to ``20``. shoulder : float, optional The movie will start this far into the audio file and stop this far from the end. This removes weird edge effect of making spectrograms. Defaults to ``0.05``. c : str, optional Passed to ``matplotlib.pyplot.scatter`` for background points. Defaults to ``'b'``. alpha : float, optional Passed to ``matplotlib.pyplot.scatter`` for background points. Defaults to ``0.2``. s : float, optional Passed to ``matplotlib.pyplot.scatter`` for background points. Defaults to ``0.9``. marker_c : str, optional Passed to ``matplotlib.pyplot.scatter`` for the marker. Defaults to ``'r'``. marker_s : float, optional Passed to ``matplotlib.pyplot.scatter`` for the marker. Defaults to ``40.0``. marker_marker : str, optional Passed to ``matplotlib.pyplot.scatter`` for the marker. Defaults to ``'r'``. """ assert dc.model_filename is not None # Read the audio file. fs, audio = wavfile.read(audio_file) assert fs == p['fs'], "found fs="+str(fs)+", expected "+str(p['fs']) # Make spectrograms. specs = [] dt = 1/fps onset = shoulder while onset + p['window_length'] < len(audio)/fs - shoulder: offset = onset + p['window_length'] target_times = np.linspace(onset, offset, p['num_time_bins']) # Then make a spectrogram. spec, flag = p['get_spec'](onset-shoulder, offset+shoulder, audio, p, \ fs=fs, target_times=target_times) assert flag specs.append(spec) onset += dt # Make a DataLoader out of these spectrograms. specs = np.stack(specs) loader = DataLoader(SimpleDataset(specs)) # Get latent means. model = VAE() model.load_state(dc.model_filename) latent = model.get_latent(loader) # Get original latent and embeddings. original_embed = dc.request('latent_mean_umap') original_latent = dc.request('latent_means') # Find nearest neighbors in latent space to determine embeddings. new_embed = np.zeros((len(latent),2)) for i in range(len(latent)): index = np.argmin([euclidean(latent[i], j) for j in original_latent]) new_embed[i] = original_embed[index] # Calculate x and y limits. xmin = np.min(original_embed[:,0]) ymin = np.min(original_embed[:,1]) xmax = np.max(original_embed[:,0]) ymax = np.max(original_embed[:,1]) x_pad = 0.05 * (xmax - xmin) y_pad = 0.05 * (ymax - ymin) xmin, xmax = xmin - x_pad, xmax + x_pad ymin, ymax = ymin - y_pad, ymax + y_pad # Save images. if not os.path.exists(output_dir): os.mkdir(output_dir) for i in range(len(new_embed)): plt.scatter(original_embed[:,0], original_embed[:,1], c=[c]*len(original_embed), \ alpha=alpha, s=s) plt.scatter([new_embed[i,0]], [new_embed[i,1]], s=marker_s, \ marker=marker_marker, c=marker_c) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.axis('off') fn = str(i).zfill(4) + '.png' fn = os.path.join(output_dir, fn) plt.savefig(fn) plt.close('all') class SimpleDataset(Dataset): def __init__(self, specs): self.specs = specs def __len__(self): return self.specs.shape[0] def __getitem__(self, index): return torch.from_numpy(self.specs[index]).type(torch.FloatTensor) if __name__ == '__main__': pass ###
from django.contrib import admin from .models import School, Department, Course admin.site.register(School) admin.site.register(Department) admin.site.register(Course)
from .. import Provider as AutomotiveProvider class Provider(AutomotiveProvider): """Implement automotive provider for ``pt_BR`` locale.""" license_formats = ("???-####",)
def train_model(model, X_train, Y_train, callback_list, **params): train_epochs = params.get("train_epochs") batch_size = params.get("batch_size") val_split = params.get("val_split") model_verbose = params.get("model_verbose") embedding_type = params.get("embedding_type") print("training neural network...") model.fit(X_train, Y_train, epochs = train_epochs, batch_size = batch_size, validation_split = val_split, verbose = model_verbose, shuffle=True, callbacks=callback_list) model.save(f"./MLModels/TheModel-{embedding_type}.h5") return model
import numpy as np import torch from torch import nn # DATASET and DATALOADER class myDataset(torch.utils.data.Dataset): def __init__(self, data, lat_samples, transform=None): self.data = data self.lat_samples = lat_samples self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, index): data = self.data[index] lat_samples = self.lat_samples[index] if self.transform: data = self.transform(data) return (data, lat_samples) def get_dataloaders(n_samples_per_cluster, latent_means, latent_vars, extra_dim=8, var=0.01, batch_size=100, shuffle=True): """A generic data loader """ latent_samples = generate_latent_samples(n_samples_per_cluster, latent_means, latent_vars) data = generate_full_samples(latent_samples, extra_dim, var) kwargs = {'num_workers': 1, 'pin_memory': True} if torch.cuda.is_available() else {} data_loader = torch.utils.data.DataLoader(myDataset(data, latent_samples), batch_size=batch_size, shuffle=shuffle, **kwargs) return data_loader def samples(mu, var, nb_samples=500): """ Return a tensor of (nb_samples, features), sampled from the parameterized gaussian. :param mu: torch.Tensor of the means :param var: torch.Tensor of variances (NOTE: zero covars.) """ out = [] for i in range(nb_samples): out += [ torch.normal(mu, var.sqrt()) ] return torch.stack(out, dim=0) def generate_latent_samples(nb_samples, latent_means, latent_vars): latent_data = [] n_clusters = len(latent_means) for i in range(n_clusters): cluster = samples( torch.Tensor(latent_means[i]), torch.Tensor(latent_vars[i]), nb_samples=nb_samples ) latent_data.append(cluster) return torch.cat(latent_data, dim=0) def generate_full_samples(latent_samples, extra_dim, var): out = [] nb_samples, dim = latent_samples.shape for i in range(nb_samples): zero = torch.zeros(extra_dim) mu = torch.cat([latent_samples[i], zero]) v = var * torch.ones(dim + extra_dim) out += [ torch.normal(mu, v.sqrt()) ] return torch.stack(out, dim=0)
# pylint: disable=missing-docstring """Test the plt fixture.""" import numpy as np def test_rectification(plt): """The test shown in the documentation. Included here to be extra sure that the example works when copy-pasted into a user's tests, and to easily generate the plot that we display in documentation. """ values = list(range(-10, 11)) rectified = [v if v > 0 else 0 for v in values] assert all(v >= 0 for v in rectified) plt.plot(values, label="Original") plt.plot(rectified, label="Rectified") plt.legend() # Use png to render easier in docs plt.saveas = "%s.png" % (plt.saveas[:-4],) def test_mock_iter(plt): fig = plt.figure() for _ in enumerate(fig.axes): assert False, "Mock object iterating forever" plt.saveas = None def test_simple_plot(plt): plt.plot(np.linspace(0, 1, 20), np.linspace(0, 2, 20)) def test_bbox_extra_artists(plt): plt.plot(np.linspace(0, 1, 20), np.linspace(0, 2, 20), label="line") legend = plt.legend(loc="upper left", bbox_to_anchor=(1.0, 1.0)) plt.bbox_extra_artists = (legend,) def test_saveas(plt): assert plt.saveas.endswith("saveas.pdf") plt.saveas = None def test_saveas_pickle(plt): plt.subplots(2, 3) # The pickled figure will contain six axes. plt.saveas = "%s.pickle" % (plt.saveas[:-4],)
from uuid import uuid4 from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.state import token_backend from rest_auth.exceptions import AccountExistError from rest_auth.models import SocialAccount, User from rest_auth.views.constants import AuthError def render_authentication_error(request, error=AuthError.UNKNOWN, exception=None): """ Return a template response or redirect to login cancelled view :param request: django HttpRequest :param error: The error type :param exception: The exception thrown :return: TemplateResponse or HttpResponseRedirect """ if error == AuthError.CANCELLED: return HttpResponseRedirect(reverse('login_cancelled')) context = {} error_name = getattr(exception, 'message', None) if error_name is not None: context['error_name'] = error_name return render( request, 'authentication_error.html', context=context ) def get_or_create_user(extra_data): """ Steps: Check if the user already exists with this email address. If not: 1. Create a User 2. Create a SocialAccount with that user 3. Return the User otherwise: Check if User has a SocialAccount If not: raise AccountExistError otherwise: Return the User :param extra_data: Data received from provider :type extra_data: dict :return An User instance. :rtype User """ email = extra_data['email'] try: user = User.objects.get(email=email) try: SocialAccount.objects.get(user=user) except ObjectDoesNotExist: raise AccountExistError() except ObjectDoesNotExist: user = User( email=email, first_name=extra_data.get('first_name'), last_name=extra_data.get('last_name'), profile_photo=extra_data.get('profile_photo') ) user.set_unusable_password() user.save() SocialAccount.objects.create( user=user, provider=extra_data['provider'], uid=extra_data['uid'], extra_data=extra_data['extra_data'] ) return user def create_access_token_for_user(user): """ Create an access token for user. :param user: :return Encoded token """ refresh = TokenObtainPairSerializer.get_token(user) encoded_token = token_backend.encode(refresh.access_token.payload) return encoded_token
# -*- coding: utf-8 -*- # Copyright (c) 2022 Ricardo Bartels. All rights reserved. # # wordpress-hash-event-api # # This work is licensed under the terms of the MIT license. # For a copy, see file LICENSE.txt included in this # repository or visit: <https://opensource.org/licenses/MIT>. from typing import Tuple from pydantic import BaseSettings from pydantic.env_settings import SettingsSourceCallable class EnvOverridesBaseSettings(BaseSettings): """ overrides order of settings read int model """ @classmethod def config_section_name(cls): return cls.Config.env_prefix[:-1] @classmethod def defaults_dict(cls): return {x.name: x.default for x in cls.__fields__.values()} class Config: env_prefix = "" @classmethod def customise_sources( cls, init_settings: SettingsSourceCallable, env_settings: SettingsSourceCallable, file_secret_settings: SettingsSourceCallable, ) -> Tuple[SettingsSourceCallable, ...]: return env_settings, init_settings, file_secret_settings
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: illuz <iilluzen[at]gmail.com> # File: AC_recursive_n.py # Create Date: 2015-04-05 09:22:43 # Usage: AC_recursive_n.py # Descripton: # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of integers def rightSideView(self, root): ret = [] def dfs(root, deep): if root: if len(ret) <= deep: ret.append(root.val) else: ret[deep] = root.val dfs(root.left, deep + 1) dfs(root.right, deep + 1) dfs(root, 0) return ret # debug s = Solution() r = TreeNode(2) print s.rightSideView(r)
#!/usr/bin/env python # -*- coding: utf-8 -*- import paho.mqtt.client as mqtt import json import time class mqttpublisher(): def __init__(self): self.client = mqtt.Client() self.client.connect("mqtt.realraum.at", 1883, 60) def send(self, structname, datadict): self.client.publish(structname, json.dumps(datadict)) if __name__ == '__main__': pub = mqttpublisher() pub.send("realraum/r3mqtt/demo", {"Ts": int(time.time()), "aBool": bool(True), "aInt": float(42), "aFloat": float(2904.0), "aString": str("hello world") })
import concurrent.futures from auto_surprise.constants import (EVALS_MULTIPLIER, MAX_WORKERS) from auto_surprise.trainer import Trainer from auto_surprise.strategies.base import StrategyBase class BasicReduction(StrategyBase): """ A basic strategy for comparison of algorithms """ def evaluate(self): """ Evaluate performance of algorithms """ print("Starting evaluation using strategy : BasicReduction") tasks = {} iteration = 0 while True: print("Iteration: %i" % iteration) max_evals = EVALS_MULTIPLIER * (iteration + 1) tasks[iteration] = {} futures = {} with concurrent.futures.ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor: # Run for N algorithms for algo in self.algorithms: print("Starting thread with %s algorithm" % algo) trainer = Trainer(algo=algo, data=self.data, target_metric=self.target_metric, hpo_algo=self.hpo_algo, debug=self._debug) futures[executor.submit(trainer.start, max_evals)] = algo # Load results of completed tasks for future in concurrent.futures.as_completed(futures): algo = futures[future] hyperparams, score = future.result() # If no exceptions, then include in tasks, else remove from algorithms list if hyperparams or score: tasks[iteration][algo] = { 'hyperparameters': hyperparams, 'score': score, 'above_baseline': score['loss'] < self.baseline_loss } else: print('Cannot use algo : %s' % algo) tasks[iteration][algo] = { 'above_baseline': False, 'exception': True } if len(tasks[iteration]) == 1: break else: self.__filter_algorithms(tasks[iteration]) iteration += 1 best_model = list(tasks[iteration].keys())[0] best_params = tasks[iteration][best_model]['hyperparameters'] best_score = tasks[iteration][best_model]['score']['loss'] return best_model, best_params, best_score, tasks def __filter_algorithms(self, tasks): """ Rank N algorithms and take the top N/2 algorithms which performed better than baseline result for the next iteration """ filtered_algorithms = dict(filter(lambda algo: algo[1]['above_baseline'], tasks.items())) algorithms_ranking = [i[0] for i in sorted(filtered_algorithms.items(), key=lambda x: x[1]['score']['loss'], reverse=False)] algorithms_count = round(len(self.algorithms) / 2) algorithms = algorithms_ranking[0:algorithms_count] return algorithms
"""The schema for the condensation application data layer. There are several attributes and several miscelaneous constraints. There is a brief synopsis for each entity in the documentation, however for up to date a specific details about constraints read the code """ from datetime import datetime from dateutil import tz from sqlalchemy import ( Table, Column, Integer, String, DateTime, Text, ForeignKey, ForeignKeyConstraint, CheckConstraint, UniqueConstraint, event) from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property #this is a collection of the sql alchemy metadata for the schema _Base = declarative_base() #m to n tables attachments_thread = Table ( "attachments_thread", _Base.metadata, Column("file_id", ForeignKey("files.id"), primary_key=True), Column("thread_id", ForeignKey("threads.id"), primary_key=True)) attachments_comment = Table ( "attachments_comment", _Base.metadata, Column("file_id", ForeignKey("files.id"), primary_key=True), Column("comment_id", ForeignKey("comments.id"), primary_key=True)) def _localize(time): """private method for relocalizing This is a bit of a hack and only works for things in our local time zone""" aware = time.replace(tzinfo = tz.tzutc()) return aware.astimezone(tz.tzlocal()) class User(_Base): """ A user on the site. Attributes: - id (pk): the google authentication id for the user - name: the display name for the user - profile_picture: the url to their profile photo - uploads: file uploads - threads: the threads a user has created - comments: the comments the user has posted""" __tablename__ = "users" id = Column( String(21), CheckConstraint("length(id) = 21"), primary_key=True) name = Column( String(60), CheckConstraint("length(name) > 0"), nullable=False) profile_picture = Column( String(250), nullable=False) uploads = relationship( "File", cascade="all, delete-orphan", back_populates="user") threads = relationship( "Thread", cascade="all, delete-orphan", back_populates="user") comments = relationship( "Comment", cascade="all, delete-orphan", back_populates="user") def toDict(self): """returns dict of primary attributes""" out = {} out["id"] = self.id out["profile_picture"] = self.profile_picture out["name"] = self.name return out class File(_Base): """A file upload from a user. filenames must be unique to each user Attributes: - id (pk): the generated id for the file - user: the user that generated the file - user_id (fk): their google id - name: the symbolic file name - url: the blob location of the file - cloud_key: the azure key to the file - time_created: the time the file was created - time_modified: the last time the file was modified - attached_threads: the threads the file is attached to - attached_comments: the comments the file is attached to """ __tablename__ = "files" id = Column( Integer, primary_key=True) user_id = Column( String(21), ForeignKey(User.id), nullable=False) user = relationship( "User", foreign_keys="File.user_id", back_populates="uploads") name = Column( String(50), CheckConstraint("length(name) > 0"), nullable=False) #no duplicate file names for user __table_args__ = (UniqueConstraint("user_id", "name", name="_uc_user_name"),) url = Column( String(250), CheckConstraint("length(url) > 1"), nullable=False, unique=True) cloud_key = Column( String(60), CheckConstraint("length(cloud_key) > 1"), nullable=False, unique=True) time_created = Column( DateTime, default=datetime.utcnow, nullable=False) time_modified = Column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) attached_threads = relationship( "Thread", secondary=attachments_thread, back_populates="attachments") attached_comments = relationship( "Comment", secondary=attachments_comment, back_populates="attachments") def toDict(self): """returns dict of primary attributes""" out = {} out["id"] = self.id out["user_id"] = self.user_id out["name"] = self.name out["url"] = self.url out["cloud_key"] = self.cloud_key out["time_created"] = _localize(self.time_created) out["time_modified"] = _localize(self.time_modified) return out class Thread(_Base): """A user created thread. Attributes: - id (pk): the generated id of the thread - user: the original poster - user_id(fk): the id of original poster (also number of op's mom?) - heading: the display heading of the post - body: the body of the post - time_created: time created - time_modified: the last time the thread entity was modified - time_last_reply: the time of the last comment - reply_count: the number of replies - attachments: uploaded files attached to thread body - replies: the comments on the thread """ __tablename__ = "threads" id = Column( Integer, primary_key=True) user_id = Column( String(21), ForeignKey(User.id), nullable=False) user = relationship( "User", foreign_keys="Thread.user_id", back_populates="threads") heading = Column( String(160), CheckConstraint("length(heading) > 1"), nullable=False) body = Column( String(20000), CheckConstraint("length(body) > 1"), nullable=False) time_created = Column( DateTime, default=datetime.utcnow, nullable=False) time_modified = Column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) time_last_reply = Column( DateTime, default=datetime.utcnow) @hybrid_property def reply_count(self): if self.replies: return len(self.replies) return 0 attachments = relationship( "File", secondary=attachments_thread, back_populates="attached_threads") replies = relationship( "Comment", cascade="all, delete-orphan", back_populates="thread") def toDict(self): out = {} out["id"] = self.id out["user_id"] = self.user_id out["heading"] = self.heading out["body"] = self.body out["time_created"] = _localize(self.time_created) out["time_modified"] = _localize(self.time_modified) out["time_last_reply"] = _localize(self.time_last_reply) out["reply_count"] = self.reply_count return out @event.listens_for(Thread.replies, 'append') def comment(thread, comment, initiator): """updates the last comment time, when a comment is added""" thread.time_last_reply = datetime.utcnow() class Comment(_Base): """A user created comment on the thread. Attributes: - id(pk): the generated id of the comment - user: the user that posted the comment - user_id(fk): the id of the user - thread: the thread the comment is responding to - thread_id(fk): the generated id of the thread - body: the body of the post - time_created: the time of the comment - time_modified: the time the comment was modified - attachments: the list of file attachments""" __tablename__ = "comments" id = Column( Integer, primary_key=True) user = relationship( "User", foreign_keys="Comment.user_id", back_populates="comments") user_id = Column( String(21), ForeignKey(User.id), nullable=False) thread = relationship( "Thread", foreign_keys="Comment.thread_id", back_populates="replies") thread_id = Column( Integer, ForeignKey(Thread.id), nullable=False) body = Column( String(20000), CheckConstraint("length(body) > 1"), nullable=False) time_created = Column( DateTime, default=datetime.utcnow, nullable=False) time_modified = Column( DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) attachments = relationship( "File", secondary=attachments_comment, back_populates="attached_comments") def toDict(self): """populates a dictionary with our primary attributes""" out = {} out["id"] = self.id out["user_id"] = self.user_id out["thread_id"] = self.thread_id out["body"] = self.body out["time_created"] = _localize(self.time_created) out["time_modified"] = _localize(self.time_modified) out["user_id"] = self.user_id return out
from torch.autograd import Variable import torch from torch.nn.modules.module import Module from torch.nn.modules.container import Sequential from torch.nn.modules.activation import LogSoftmax from torch.nn import functional as F def _assert_no_grad(variable): assert not variable.requires_grad, \ "nn criterions don't compute the gradient w.r.t. targets - please " \ "mark these variables as volatile or not requiring gradients" class _Loss(Module): def __init__(self, size_average=True): super(_Loss, self).__init__() self.size_average = size_average class _WeightedLoss(_Loss): def __init__(self, weight=None, size_average=True): super(_WeightedLoss, self).__init__(size_average) self.register_buffer('weight', weight) class NLLLoss(_WeightedLoss): r"""The negative log likelihood loss. It is useful to train a classification problem with n classes If provided, the optional argument `weights` should be a 1D Tensor assigning weight to each of the classes. This is particularly useful when you have an unbalanced training set. The input given through a forward call is expected to contain log-probabilities of each class: input has to be a 2D Tensor of size `(minibatch, n)` Obtaining log-probabilities in a neural network is easily achieved by adding a `LogSoftmax` layer in the last layer of your network. You may use `CrossEntropyLoss` instead, if you prefer not to add an extra layer. The target that this loss expects is a class index `(0 to N-1, where N = number of classes)` The loss can be described as:: loss(x, class) = -x[class] or in the case of the weights argument it is specified as follows:: loss(x, class) = -weights[class] * x[class] or in the case of ignore_index:: loss(x, class) = class != ignoreIndex ? -weights[class] * x[class] : 0 Args: weight (Tensor, optional): a manual rescaling weight given to each class. If given, has to be a Tensor of size "nclasses" size_average (bool, optional): By default, the losses are averaged over observations for each minibatch. However, if the field size_average is set to False, the losses are instead summed for each minibatch. Default: True ignore_index (int, optional): Specifies a target value that is ignored and does not contribute to the input gradient. When size_average is True, the loss is averaged over non-ignored targets. Shape: - Input: :math:`(N, C)` where `C = number of classes` - Target: :math:`(N)` where each value is `0 <= targets[i] <= C-1` Examples:: >>> m = nn.LogSoftmax() >>> loss = nn.NLLLoss() >>> # input is of size nBatch x nClasses = 3 x 5 >>> input = autograd.Variable(torch.randn(3, 5), requires_grad=True) >>> # each element in target has to have 0 <= value < nclasses >>> target = autograd.Variable(torch.LongTensor([1, 0, 4])) >>> output = loss(m(input), target) >>> output.backward() """ def __init__(self, weight=None, size_average=True, ignore_index=-100): super(NLLLoss, self).__init__(weight, size_average) self.ignore_index = ignore_index def forward(self, input, target): _assert_no_grad(target) return F.nll_loss(input, target, self.weight, self.size_average, self.ignore_index) class NLLLoss2d(NLLLoss): r"""This is negative log likehood loss, but for image inputs. It computes NLL loss per-pixel. Args: weight (Tensor, optional): a manual rescaling weight given to each class. If given, has to be a 1D Tensor having as many elements, as there are classes. size_average: By default, the losses are averaged over observations for each minibatch. However, if the field size_average is set to False, the losses are instead summed for each minibatch. Default: True Shape: - Input: :math:`(N, C, H, W)` where `C = number of classes` - Target: :math:`(N, H, W)` where each value is `0 <= targets[i] <= C-1` Examples:: >>> m = nn.Conv2d(16, 32, (3, 3)).float() >>> loss = nn.NLLLoss2d() >>> # input is of size nBatch x nClasses x height x width >>> input = autograd.Variable(torch.randn(3, 16, 10, 10)) >>> # each element in target has to have 0 <= value < nclasses >>> target = autograd.Variable(torch.LongTensor(3, 8, 8).random_(0, 4)) >>> output = loss(m(input), target) >>> output.backward() """ pass
import sys sum = 0 def get_stats(values, sum): if len(values) == 0: print ("All zeros") return values.sort() mean = sum / len(values) median = values[len(values)//2] mode_d = {} for x in values: mode_d[x] = mode_d.get(x, 0) + 1 mode = max(mode_d.values()) print (values) print (f"Mean is {mean}.\nMedian is {median}\nMode is {mode}\nRange is {values[0]}..{values[-1]}") def get_inputs(values): global sum while True: inp = input() if inp.lstrip("-").isdigit(): sum += int(inp) values.append(int(inp)) elif inp == 'm': get_stats(values, sum) continue else: break if __name__ == "__main__": values = [] get_inputs(values)
import pandas # create a list of 100000 pairs with values (i,i) then output pairs as 'rising_limbo.csv' pairs = [(i, i) for i in range(100_000)] pandas.DataFrame(pairs).to_csv('rising_limbo.csv', header=False, index=False)
from .rpc.request import ( rpc_request ) _default_endpoint = 'http://localhost:9500' _default_timeout = 30 ######################### # Transaction Pool RPCs # ######################### def get_pending_transactions(endpoint=_default_endpoint, timeout=_default_timeout) -> list: """ Get list of pending transactions Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- list # TODO: Add link to reference RPC documentation """ return rpc_request('hmy_pendingTransactions', endpoint=endpoint, timeout=timeout)['result'] #################### # Transaction RPCs # #################### def get_transaction_by_hash(tx_hash, endpoint=_default_endpoint, timeout=_default_timeout) -> dict: """ Get transaction by hash Parameters ---------- tx_hash: str Transaction hash to fetch endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation None if transaction hash not found """ params = [ tx_hash ] return rpc_request('hmy_getTransactionByHash', params=params, endpoint=endpoint, timeout=timeout)['result'] def get_transaction_by_block_hash_and_index(block_hash, tx_index, endpoint=_default_endpoint, timeout=_default_timeout ) -> dict: """ Get transaction based on index in list of transactions in a block by block hash Parameters ---------- block_hash: str Block hash for transaction tx_index: int Transaction index to fetch endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation """ params = [ block_hash, str(hex(tx_index)) ] return rpc_request('hmy_getTransactionByBlockHashAndIndex', params=params, endpoint=endpoint, timeout=timeout)['result'] def get_transaction_by_block_number_and_index(block_num, tx_index, endpoint=_default_endpoint, timeout=_default_timeout ) -> dict: """ Get transaction based on index in list of transactions in a block by block number Parameters ---------- block_num: int Block number for transaction tx_index: int Transaction index to fetch endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation """ params = [ str(hex(block_num)), str(hex(tx_index)) ] return rpc_request('hmy_getTransactionByBlockNumberAndIndex', params=params, endpoint=endpoint, timeout=timeout)['result'] def get_transaction_receipt(tx_receipt, endpoint=_default_endpoint, timeout=_default_timeout) -> dict: """ Get transaction receipt Parameters ---------- tx_receipt: str Transaction receipt to fetch endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation None if transcation receipt hash not found """ params = [ tx_receipt ] return rpc_request('hmy_getTransactionReceipt', params=params, endpoint=endpoint, timeout=timeout)['result'] def get_transaction_error_sink(endpoint=_default_endpoint, timeout=_default_timeout) -> list: """ Get transaction error sink Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- list # TODO: Add link to reference RPC documentation """ return rpc_request('hmy_getCurrentTransactionErrorSink', endpoint=endpoint, timeout=timeout)['result'] def send_raw_transaction(raw_tx, endpoint=_default_endpoint, timeout=_default_timeout) -> str: """ Send signed transaction Parameters ---------- raw_tx: str Hex representation of signed transaction endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- str Transaction hash """ params = [ raw_tx ] return rpc_request('hmy_sendRawTransaction', params=params, endpoint=endpoint, timeout=timeout)['result'] ############################### # CrossShard Transaction RPCs # ############################### def get_pending_cx_receipts(endpoint=_default_endpoint, timeout=_default_timeout) -> list: """ Get list of pending cross shard transactions Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- list # TODO: Add link to reference RPC documentation """ return rpc_request('hmy_getPendingCXReceipts', endpoint=endpoint, timeout=timeout)['result'] def get_cx_receipt_by_hash(cx_hash, endpoint = _default_endpoint, timeout = _default_timeout) -> dict: """ Get cross shard receipt by hash Parameters ---------- cx_hash: str Hash of cross shard transaction receipt endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation None if cx receipt hash not found """ params = [ cx_hash ] return rpc_request('hmy_getCXReceiptByHash', params=params, endpoint=endpoint, timeout=timeout)['result'] def resend_cx_receipt(cx_receipt, endpoint=_default_endpoint, timeout=_default_timeout) -> bool: """ Send cross shard receipt Parameters ---------- cx_hash: str Hash of cross shard transaction receipt endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- bool If the receipt transactions was succesfully resent """ params = [ cx_receipt ] return rpc_request('hmy_resendCx', params=params, endpoint=endpoint, timeout=timeout)['result'] ############################ # Staking Transaction RPCs # ############################ def get_staking_transaction_by_hash(tx_hash, endpoint=_default_endpoint, timeout=_default_timeout) -> dict: """ Get staking transaction by hash Parameters ---------- tx_hash: str Hash of staking transaction to fetch endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation None if staking transaction hash not found """ params = [ tx_hash ] return rpc_request('hmy_getStakingTransactionByHash', params=params, endpoint=endpoint, timeout=timeout)['result'] def get_staking_transaction_by_block_hash_and_index(block_hash, tx_index, endpoint=_default_endpoint, timeout=_default_timeout ) -> dict: """ Get staking transaction based on index in list of staking transactions for a block by block hash Parameters ---------- block_hash: str Block hash for staking transaction tx_index: int Staking transaction index to fetch endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation """ params = [ block_hash, str(hex(tx_index)) ] return rpc_request('hmy_getStakingTransactionByBlockHashAndIndex', params=params, endpoint=endpoint, timeout=timeout)['result'] def get_staking_transaction_by_block_number_and_index(block_num, tx_index, endpoint=_default_endpoint, timeout=_default_timeout ) -> dict: """ Get staking transaction based on index in list of staking transactions for a block by block number Parameters ---------- block_num: int Block number for staking transaction tx_index: int Staking transaction index to fetch endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- dict # TODO: Add link to reference RPC documentation """ params = [ str(hex(block_num)), str(hex(tx_index)) ] return rpc_request('hmy_getStakingTransactionByBlockNumberAndIndex', params=params, endpoint=endpoint, timeout=timeout)['result'] def get_staking_transaction_error_sink(endpoint=_default_endpoint, timeout=_default_timeout) -> list: """ Get staking transaction error sink Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- list # TODO: Add link to reference RPC documentation """ return rpc_request('hmy_getCurrentStakingErrorSink', endpoint=endpoint, timeout=timeout)['result'] def send_raw_staking_transaction(raw_tx, endpoint=_default_endpoint, timeout=_default_timeout) -> str: """ Send signed staking transaction Parameters ---------- raw_tx: str Hex representation of signed staking transaction endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- str Staking transaction hash """ params = [ raw_tx ] return rpc_request('hmy_sendRawStakingTransaction', params=params, endpoint=endpoint, timeout=timeout)['result']
# Copyright 2020 The TensorFlow Probability Authors. # # 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ # Lint as: python3 """Tests for tensorflow_probability.experimental.lazybones.utils.""" import math from absl.testing import absltest import tensorflow_probability as tfp lb = tfp.experimental.lazybones class DeferredUtilsTest(absltest.TestCase): def test_iter_edges(self): m = lb.DeferredInput(math) a = m.exp(1.) b = m.log(2.) c = a + b self.assertSetEqual( set([ ('__call__', '__add__'), ('__call__', '__add__'), ('exp', '__call__'), ('math', 'exp'), ('log', '__call__'), ('math', 'log'), ]), set((p.name, v.name) for p, v in lb.utils.iter_edges(c))) def test_get_leaves(self): m = lb.DeferredInput(math) a = m.exp(1.) b = m.log(2.) self.assertSetEqual({a, b}, lb.utils.get_leaves(m)) self.assertSetEqual({a, b}, lb.utils.get_leaves([a, b, a])) def test_get_roots(self): m = lb.DeferredInput(math) a = m.exp(1.) b = m.log(2.) c = a + b self.assertSetEqual({m}, lb.utils.get_roots(m)) self.assertSetEqual({m}, lb.utils.get_roots(c)) self.assertSetEqual({m}, lb.utils.get_roots([a, b])) def test_is_any_ancestor(self): o = lb.DeferredInput(math) n = lb.DeferredInput(math) m = lb.DeferredInput(math) a = m.exp(1.) b = m.log(2.) c = a + b # pylint: disable=unused-variable self.assertFalse(lb.utils.is_any_ancestor(n, m)) self.assertTrue(lb.utils.is_any_ancestor(a, m)) self.assertTrue(lb.utils.is_any_ancestor([a, n], m)) self.assertFalse(lb.utils.is_any_ancestor([o, n], m)) self.assertTrue(lb.utils.is_any_ancestor([a, n], [m, o])) if __name__ == '__main__': absltest.main()
import functools from .abi import ( # noqa: F401 abi_middleware, ) from .attrdict import ( # noqa: F401 attrdict_middleware, ) from .cache import ( # noqa: F401 _latest_block_based_cache_middleware as latest_block_based_cache_middleware, _simple_cache_middleware as simple_cache_middleware, _time_based_cache_middleware as time_based_cache_middleware, construct_latest_block_based_cache_middleware, construct_simple_cache_middleware, construct_time_based_cache_middleware, ) from .exception_handling import ( # noqa: F401 construct_exception_handler_middleware, ) from .exception_retry_request import ( # noqa: F401 http_retry_request_middleware, ) from .filter import ( # noqa: F401 local_filter_middleware, ) from .fixture import ( # noqa: F401 construct_error_generator_middleware, construct_fixture_middleware, construct_result_generator_middleware, ) from .formatting import ( # noqa: F401 construct_formatting_middleware, ) from .gas_price_strategy import ( # noqa: F401 gas_price_strategy_middleware, ) from .geth_poa import ( # noqa: F401 geth_poa_middleware, ) from .names import ( # noqa: F401 name_to_address_middleware, ) from .normalize_errors import ( # noqa: F401 normalize_errors_middleware, ) from .normalize_request_parameters import ( # noqa: F401 request_parameter_normalizer, ) from .pythonic import ( # noqa: F401 pythonic_middleware, ) from .signing import ( # noqa: F401 construct_sign_and_send_raw_middleware, ) from .stalecheck import ( # noqa: F401 make_stalecheck_middleware, ) from .validation import ( # noqa: F401 validation_middleware, ) def combine_middlewares(middlewares, web3, provider_request_fn): """ Returns a callable function which will call the provider.provider_request function wrapped with all of the middlewares. """ return functools.reduce( lambda request_fn, middleware: middleware(request_fn, web3), reversed(middlewares), provider_request_fn, )
import string import nltk import textblob as textblob from nltk import word_tokenize, pos_tag, ne_chunk, tree2conlltags from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.preprocessing import MinMaxScaler from constants import emoticons from feature_extraction import * from preprocess import preprocess_data import scipy.sparse as sp import re def bag_of_words_features2( train_data, test_data, val_data, max_features=2000, binary=False ): """Return features using bag of words""" vectorizer = CountVectorizer( ngram_range=(1, 3), min_df=3, stop_words="english", binary=binary ) joined_train_data = train_data["lemmas"].apply(" ".join) joined_test_data = test_data["lemmas"].apply(" ".join) joined_val_data = val_data["lemmas"].apply(" ".join) X_train = vectorizer.fit_transform(joined_train_data) X_train = X_train.astype("float16") X_test = vectorizer.transform(joined_test_data) X_test = X_test.astype("float16") X_val = vectorizer.transform(joined_val_data) X_val = X_val.astype("float16") return X_train, X_test, X_val def tfidf_features2(train_data, test_data, val_data, binary=False): """Return features using TFIDF""" joined_train_data = train_data["lemmas"].apply(" ".join) joined_test_data = test_data["lemmas"].apply(" ".join) joined_val_data = val_data["lemmas"].apply(" ".join) vectorizer = TfidfVectorizer( token_pattern=r"\w{1,}", min_df=0.2, max_df=0.8, use_idf=True, binary=binary, ngram_range=(1, 3), ) X_train = vectorizer.fit_transform(joined_train_data) X_train = X_train.astype("float16") X_test = vectorizer.transform(joined_test_data) X_test = X_test.astype("float16") X_val = vectorizer.transform(joined_val_data) X_val = X_val.astype("float16") return X_train, X_test, X_val def bag_of_words_features(data, binary=False): """Return features using bag of words""" vectorizer = CountVectorizer( ngram_range=(1, 3), min_df=3, stop_words="english", binary=binary ) return vectorizer.fit_transform(data["joined_lemmas"]) def tfidf_features(data, binary=False, return_vectorizer=False): """Return features using TFIDF""" vectorizer = TfidfVectorizer( token_pattern=r"\w{1,}", min_df=0.2, max_df=0.8, use_idf=True, binary=binary, ngram_range=(1, 3), ) if return_vectorizer: x = vectorizer.fit_transform(data["joined_lemmas"]) return vectorizer, x return vectorizer.fit_transform(data["joined_lemmas"]) def bag_of_words_features_1( train_data, test_data, max_features=2000, binary=False, kfold=False ): """Return features using bag of words""" vectorizer = CountVectorizer( ngram_range=(1, 3), stop_words="english", binary=binary ) if not kfold: joined_train_data = train_data["lemmas"].apply(" ".join) joined_test_data = test_data["lemmas"].apply(" ".join) else: joined_train_data = train_data joined_test_data = test_data X_train = vectorizer.fit_transform(joined_train_data) X_train = X_train.astype("float16") X_test = vectorizer.transform(joined_test_data) X_test = X_test.astype("float16") return X_train, X_test def tfidf_features_1(train_data, test_data, kfold, binary=False): """Return features using TFIDF""" if not kfold: joined_train_data = train_data["lemmas"].apply(" ".join) joined_test_data = test_data["lemmas"].apply(" ".join) else: joined_train_data = train_data joined_test_data = test_data vectorizer = TfidfVectorizer( analyzer="word", max_features=200000, token_pattern=r"\w{1,}", use_idf=True, binary=binary, sublinear_tf=True, ngram_range=(1, 2), ) X_train = vectorizer.fit_transform(joined_train_data) X_test = vectorizer.transform(joined_test_data) return X_train, X_test def count_words(tokens): return len(tokens) def longest_word(tokens): return max(list(map(len, tokens))) def shortest_word(tokens): return min(list(map(len, tokens))) def count_emoticons(lemmas): number_of_emoticons = 0 for emoticon in emoticons: if emoticon in lemmas: number_of_emoticons += 1 return number_of_emoticons def read_book(filename): with open(filename, "r", encoding="UTF-8") as f: rl = f.readlines() rl = " ".join(rl) rl = rl.replace("\n", "") rl = rl.replace("\ufeff", "") f.close() return rl def get_iob(rl, name, book_analysis=False): tokens = list( filter(lambda token: token not in string.punctuation, word_tokenize(rl)) ) tagged_tokens = pos_tag(tokens) ner_tree = ne_chunk(tagged_tokens) iob_tagged = tree2conlltags(ner_tree) persons = list(filter(lambda x: "PERSON" in x[2], iob_tagged)) tokens = list(map(lambda token: str(token).lower(), tokens)) lemmatizer = nltk.stem.WordNetLemmatizer() lemmas = [lemmatizer.lemmatize(token) for token in tokens] stop = stopwords.words("english") no_stopwords = [item for item in lemmas if item not in stop] if book_analysis: print(f"{name} length: {len(rl)}") print(f"{name} persons: {len(persons)}") print(f"{name} tokens: {len(tokens)}") return persons, no_stopwords def is_url(s): return int(len(re.findall(r"(https?://[^\s]+)", s)) > 0) def is_person_in_book(message, persons): return any(list([word in persons for word in message])) def is_word_in_book(message, words): return any(list([word in words for word in message])) def contains_upper(message): for char in message: if str(char).isupper(): return True return False def contains_number(message): for char in message: if str(char).isnumeric(): return True return False def person_mentioned(data, iob): persons = list(map(lambda person: str(person[0]).lower(), iob)) return data["lemmas"].apply(lambda message: is_word_in_book(message, persons)) def book_words(data, book_no_stopwords): return data["no_stopwords"].apply( lambda message: is_person_in_book(message, book_no_stopwords) ) def count_tag_types(message, type): pos_tags = { "noun": ["NN", "NNS", "NNP", "NNPS"], "pron": ["PRP", "PRP$", "WP", "WP$"], "verb": ["VB", "VBD", "VBG", "VBN", "VBP", "VBZ"], "adj": ["JJ", "JJR", "JJS"], "adv": ["RB", "RBR", "RBS", "WRB"], } cnt = 0 try: wiki = textblob.TextBlob(message) cnt = sum([1 if list(t)[1] in pos_tags[type] else 0 for t in wiki.tags]) except: pass return cnt def compare_message_to_book(message, book): vect = TfidfVectorizer() tfidf = vect.fit_transform([message, book]) return ((tfidf * tfidf.T).A).min() def message_book_similarity(data, book): return data["Message"].apply(lambda message: compare_message_to_book(message, book)) def custom_features_extractor(data, book_analysis=False): data["message_length"] = data["Message"].apply(len) data["longest_word"] = data["lemmas"].apply(max).apply(len) data["shortest_word"] = data["lemmas"].apply(min).apply(len) data["num_of_words"] = data["lemmas"].apply(len) data["contains_question_marks"] = data["Message"].str.contains("\?").apply(int) data["num_of_question_marks"] = data["Message"].str.count("\?") data["contains_exclamation_point"] = data["Message"].str.contains("\!").apply(int) data["contains_uppercase"] = data["Message"].apply(contains_upper) data["contains_numbers"] = data["Message"].apply(contains_number) data["num_of_exclamation_point"] = data["Message"].str.count("\!") data["num_of_emoticons"] = data["lemmas"].apply(count_emoticons) data["is_url"] = data["Message"].apply(is_url) data["num_nouns"] = data["Message"].apply(lambda x: count_tag_types(x, "noun")) data["num_verbs"] = data["Message"].apply(lambda x: count_tag_types(x, "verb")) data["num_adjs"] = data["Message"].apply(lambda x: count_tag_types(x, "adj")) data["num_advs"] = data["Message"].apply(lambda x: count_tag_types(x, "adv")) data["num_prons"] = data["Message"].apply(lambda x: count_tag_types(x, "pron")) book1 = read_book("data/ID260 and ID261 - The Lady or the Tiger.txt") book2 = read_book("data/ID264 and ID265 - Just Have Less.txt") book3 = read_book( "data/ID266 and ID267 - Design for the Future When the Future Is Bleak.txt" ) book1_persons, book1_no_stopwords = get_iob(book1, "book1", book_analysis) book2_persons, book2_no_stopwords = get_iob(book2, "book2", book_analysis) book3_persons, book3_no_stopwords = get_iob(book3, "book3", book_analysis) if book_analysis: print(f'Book1 nouns:{count_tag_types(book1, "noun")}') print(f'Book1 verbs:{count_tag_types(book1, "verb")}') print(f'Book1 adjectives:{count_tag_types(book1, "adj")}') print(f'Book1 adv:{count_tag_types(book1, "adv")}') print(f'Book1 pronouns:{count_tag_types(book1, "pron")}') print(f'Book2 nouns:{count_tag_types(book2, "noun")}') print(f'Book2 verbs:{count_tag_types(book2, "verb")}') print(f'Book2 adjectives:{count_tag_types(book2, "adj")}') print(f'Book2 adv:{count_tag_types(book2, "adv")}') print(f'Book2 pronouns:{count_tag_types(book2, "pron")}') print(f'Book3 nouns:{count_tag_types(book3, "noun")}') print(f'Book3 verbs:{count_tag_types(book3, "verb")}') print(f'Book3 adjectives:{count_tag_types(book3, "adj")}') print(f'Book3 adv:{count_tag_types(book3, "adv")}') print(f'Book3 pronouns:{count_tag_types(book3, "pron")}') data["book1_persons_mentioned"] = person_mentioned(data, book1_persons) data["book2_persons_mentioned"] = person_mentioned(data, book2_persons) data["book3_persons_mentioned"] = person_mentioned(data, book3_persons) data["words_in_book1"] = book_words(data, book1_no_stopwords) data["words_in_book2"] = book_words(data, book2_no_stopwords) data["words_in_book3"] = book_words(data, book3_no_stopwords) data["book1_similarity"] = message_book_similarity(data, book1) data["book2_similarity"] = message_book_similarity(data, book2) data["book3_similarity"] = message_book_similarity(data, book3) tfidf = tfidf_features(data) bow = bag_of_words_features(data) scaler = MinMaxScaler() X_cols = scaler.fit_transform(data[data.columns[14:]]) X_sparse = sp.hstack( [sp.csr_matrix(tfidf), sp.csr_matrix(bow), sp.csr_matrix(X_cols)] ) return X_sparse if __name__ == "__main__": print("Start") data = preprocess_data() custom_features_extractor(data, book_analysis=True)
from ..helpers.dom_type import DomType from ..errors.invalid_dom_type import InvalidDomTypeError class TestCaseStep: def __init__(self, dom_type, selector, validate_type, validation_value, action, action_input): self.dom_type = dom_type self.selector = selector self.validate_type = validate_type self.validation_value = validation_value self.action = action self.action_input = action_input
#!/usr/bin/env python # -*- coding: utf-8 -*- import re, time import logging import base64, hashlib import binascii, textwrap, json, copy from subprocess import Popen, PIPE try: from urllib.request import urlopen # Python 3 except ImportError: from urllib2 import urlopen # Python 2 LOGGER = logging.getLogger(__name__) LOGGER.addHandler(logging.StreamHandler()) LOGGER.setLevel(logging.INFO) class ACMEAccount(object): # Account key for ACME def __init__(self, account_key): self.account_key = account_key # path for account key self._jwk = None self._fingerprint = None def _b64(self, b): return base64.urlsafe_b64encode(b).decode('utf8').replace("=", "") @property def jwk(self): # Generate JWK(JSON Web Key) if self._jwk: return self._jwk # Get modulus and publicExponent from account key p = Popen(["openssl", "rsa", "-in", self.account_key, "-noout", "-text"], stdout=PIPE, stderr=PIPE) out, err = p.communicate() if p.returncode != 0: raise IOError("OpenSSL Error: %s" % err) pubn, pube = re.search(r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)", out, re.MULTILINE|re.DOTALL).groups() pubn = re.sub(r"[\s:]", "", pubn) pube = "{0:x}".format(int(pube)) pube = "0{0}".format(pube) if len(pube) % 2 else pube self._jwk = { "kty": "RSA", # Key type "n": self._b64(binascii.unhexlify(pubn)), # modulus "e": self._b64(binascii.unhexlify(pube)), # public exponent } return self._jwk @property def fingerprint(self): # Calculate fingerprint of access key if self._fingerprint: return self._fingerprint akey_json = json.dumps(self.jwk, sort_keys=True, separators=(',', ':')) self._fingerprint = self._b64(hashlib.sha256(akey_json).digest()) return self._fingerprint def sign(self, s): # Sign input string with the account key p = Popen(["openssl", "dgst", "-sha256", "-sign", self.account_key], stdin=PIPE, stdout=PIPE, stderr=PIPE) out, err = p.communicate(s) if p.returncode != 0: raise IOError("OpenSSL Error: %s" % err) return out class ACMEClient(object): # Client for ACME DEFAULT_DIRECTORY = "https://acme-v01.api.letsencrypt.org/directory" # endpoint for 'directory' resource def __init__(self, account_key, log=LOGGER, directory=DEFAULT_DIRECTORY): self._nonce = None # NONCE value self.account = ACMEAccount(account_key) self.directory_endpoint = directory self.resources = self._get_resources() self.log = log def _get_resources(self): # Get endpoints from 'directory' ua = urlopen(self.directory_endpoint) self._nonce = ua.headers["Replay-Nonce"] return json.load(ua) def _b64(self, b): # encode into URL safe base64 return base64.urlsafe_b64encode(b).replace("=", "") @property def nonce(self): # Return NONCE and clear the NONCE if not self._nonce: raise RuntimeError("No NONCE provided.") nonce = self._nonce self._nonce = None return nonce def read_domains(self, csr): # Read domain names from CN of CSR # Reading SAN has not been implemented yet. p = Popen(["openssl", "req", "-in", csr, "-noout", "-subject"], stdout=PIPE, stderr=PIPE) out, err = p.communicate() m = re.search(r"/CN=([\w\.-]+)", out) return [m.group(1)] def send_request(self, url, payload): # Send protected request to the specified URL # New NONCE will be obtained the response. protected = {"alg": "RS256", "jwk": self.account.jwk, "nonce": self.nonce} data = { "protected": self._b64(json.dumps(protected)), "payload": self._b64(json.dumps(payload)), } signature = self.account.sign("{0}.{1}".format(data["protected"], data["payload"])) data["signature"] = self._b64(signature) try: res = urlopen(url, json.dumps(data)) return res.getcode(), res.read() except IOError as e: res = e return getattr(e, "code", None), getattr(e, "read", e.__str__)() finally: self._nonce = res.headers["Replay-Nonce"] def register_account(self): # Register account key self.log.info("Registering account...") endpoint = self.resources["new-reg"] code, body = self.send_request(endpoint, { "resource": "new-reg", "agreement": "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf", }) if code == 201: self.log.info("Registered.") elif code == 409: self.log.info("Already registered, ignored.") else: raise RuntimeError("Error in 'new-reg': %d %s" % (code, body)) return code, json.loads(body) def get_status(self, domain): # Get challenges and status endpoint = self.resources["new-authz"] code, body = self.send_request(endpoint, { "resource": "new-authz", "identifier": {"type": "dns", "value": domain}, }) if code != 201: raise RuntimeError("Error in 'new-authz': %d %s" % (code, body)) return json.loads(body) def is_valid(self, domain): # Check status is valid info = self.get_status(domain) return bool(info["status"] == "valid") def get_challenge(self, domain, typename): # Get challenge object with typename # typename: http-01, dns-01 ... info = self.get_status(domain) for c in info["challenges"]: if c["type"] == typename: client = self class _Challenge(object): # Challenge object for responding # c = client.get_challenge(DOMAIN, "dns-01") # ... append _acme-challenge record to target domain ... # c.respond() def __init__(self): self.status = c["status"] self.token = c["token"] self.keyauth = "%s.%s" % (self.token, client.account.fingerprint) self.digested_key_authorization = client._b64(hashlib.sha256(self.keyauth).digest()) def respond(self): # Respond the challenge code, body = client.send_request(c["uri"], {"resource": "challenge", "keyAuthorization": self.keyauth}) if code != 202: raise RuntimeError("Error in 'challenge': %d %s" % (code, body)) # Check result of verification by the server while True: time.sleep(10) ua = urlopen(c["uri"]) st = json.load(ua) if st["status"] == "pending": continue if st["status"] == "valid": break raise RuntimeError("Error in 'verification': %d %s" % (code, json.dumps(st))) return code, json.loads(body) return _Challenge() raise ValueError("Challenge type '%s' is not found: %s" % (typename, json.dumps(info))) def get_certificate(self, csr): # Get certificate with CSR p = Popen(["openssl", "req", "-in", csr, "-outform", "DER"], stdout=PIPE, stderr=PIPE) csr_der, err = p.communicate() endpoint = self.resources["new-cert"] code, body = self.send_request(endpoint, { "resource": "new-cert", "csr": self._b64(csr_der), }) if code != 201: raise ValueError("Error in 'new-cert': %d %s" % (code, body)) # Return signed certificate self.log.info("Certificate signed, successfully.") crt = "-----BEGIN CERTIFICATE-----\n" crt += "\n".join(textwrap.wrap(base64.b64encode(body), 64)) + "\n" crt += "-----END CERTIFICATE-----\n" return crt class AWSRoute53(object): # AWS Route53 operation def __init__(self, region=None, access_key=None, secret_access_key=None): # Target recordset: _acme-challenge + <domain> # Append token to TXT import boto3 self.client = boto3.client("route53",region_name=region, aws_access_key_id=access_key, aws_secret_access_key=secret_access_key) def change_record(self, action, zone_id, domain, token): # Add/delete _acme_challenge to the domain # action: CREATE|DELETE|UPSERT res = self.client.change_resource_record_sets( HostedZoneId=zone_id, ChangeBatch={ "Comment": "Create or Delete _acme_challenge", "Changes": [{ "Action": action, "ResourceRecordSet": { "Name": "_acme-challenge.%s." % domain, "Type": "TXT", "TTL": 300, "ResourceRecords": [{"Value": '"%s"' % token}], } }] } ) def set_token(self, zone_id, domain, token): # Add token to _acme_challenge # tk = aws.set_token(ZONE_ID, DOMAIN, TOKEN) # ... respond to ACME ... # tk.delete() aws = self class _AWSRoute53Token(object): def delete(self): aws.delete_token(zone_id, domain, token) self.change_record("UPSERT", zone_id, domain, token) return _AWSRoute53Token() def delete_token(self, zone_id, domain, token): # Delete token from _acme_challenge return self.change_record("DELETE", zone_id, domain, token) if __name__ == "__main__": import sys, time import ConfigParser inifile = ConfigParser.SafeConfigParser() inifile.read("./config.ini") REGION = inifile.get("aws", "region") ZONE_ID = inifile.get("aws", "zoneId") ACCKEY = inifile.get("aws", "accessKey") SECKEY = inifile.get("aws", "secretAccessKey") KEYFILE = inifile.get("letsencrypt", "accountKeyFile") CSRFILE = inifile.get("letsencrypt", "csrFile") CRTFILE = inifile.get("letsencrypt", "certificateFile") client = ACMEClient(KEYFILE) domain = client.read_domains(CSRFILE)[0] client.register_account() challenge = client.get_challenge(domain, "dns-01") if challenge.status == "valid": LOGGER.info(" + Domain '%s' is valid." % domain) else: LOGGER.info(" + Setting TXT record for _acme-challenge.%s on Route53") aws = AWSRoute53(REGION, ACCKEY, SECKEY) r53token = aws.set_token(ZONE_ID, domain, challenge.digested_key_authorization) LOGGER.info(" + Waiting 120 seconds for responding.") time.sleep(120) try: LOGGER.info(" + Respond the challenge.") challenge.respond() except Exception, e: LOGGER.error("Validation failed for %s\n%s" % (domain, e)) sys.exit(1) finally: LOGGER.info(" + Delete TXT record") r53token.delete() LOGGER.info("Getting certificate") with open(CRTFILE, "w") as fh: fh.write(client.get_certificate(CSRFILE)) LOGGER.info("Done.")
import datetime import time import math from collections import defaultdict, Counter from operator import itemgetter from xml.etree import ElementTree from sqlalchemy import desc from config import CONFIG from db import db from models import Player, Record, Listing, Alliance from pixelstarshipsapi import PixelStarshipsApi from utils import float_range, int_range, Singleton class Pixyship(metaclass=Singleton): PSS_SPRITES_URL = 'https://pixelstarships.s3.amazonaws.com/{}.png' # A map to find the correct interior for a given race's ship # This fails for some rock ship cause this isn't actually how it works RACE_SPECIFIC_SPRITE_MAP = { 83: [83, 84, 83, 82, 1302, 561, 3134], # basic lifts 1532: [1532, 1534, 1532, 1533, 1536, 1535, 3163], # endgame lifts 871: [871, 872, 871, 869, 870, 873, 3135], # armors } ABILITY_MAP = { 'DamageToSameRoomCharacters': {'name': 'Gas', 'sprite': 2706}, 'HealRoomHp': {'name': 'Urgent Repair', 'sprite': 2709}, 'HealSelfHp': {'name': 'First Aid', 'sprite': 2707}, 'AddReload': {'name': 'Rush', 'sprite': 2703}, 'FireWalk': {'name': 'Fire Walk', 'sprite': 5389}, 'DamageToCurrentEnemy': {'name': 'Critical Strike', 'sprite': 2708}, 'DamageToRoom': {'name': 'Ultra Dismantle', 'sprite': 2710}, 'DeductReload': {'name': 'System Hack', 'sprite': 2704}, 'HealSameRoomCharacters': {'name': 'Healing Rain', 'sprite': 2705}, 'Freeze': {'name': 'Freeze', 'sprite': 5390}, 'SetFire': {'name': 'Arson', 'sprite': 5388}, 'Bloodlust': {'name': 'Bloodlust', 'sprite': 13866}, 'Invulnerability': {'name': 'Phase Shift', 'sprite': 13319}, 'ProtectRoom': {'name': 'Stasis Shield', 'sprite': 13320}, 'None': {'name': '', 'sprite': 110} # Empty sprite } COLLECTION_ABILITY_MAP = { 'EmpSkill': 'EMP Discharge', 'SharpShooterSkill': 'Sharpshooter', 'ResurrectSkill': 'Resurrection', 'BloodThirstSkill': 'Vampirism', 'MedicalSkill': 'Combat Medic', 'FreezeAttackSkill': 'Cryo Field', 'InstantKillSkill': 'Headshot', 'None': 'None' } RARITY_MAP = { 'Legendary': 7, 'Special': 6, 'Hero': 5, 'Epic': 4, 'Unique': 3, 'Elite': 2, 'Common': 1, } RARITY_COLOR = { 'Common': 'grey', 'Elite': 'white', 'Unique': 'blue', 'Epic': 'purple', 'Hero': 'gold', 'Special': 'gold', 'Legendary': 'gold', } TYPE_PSS_API_NAME_FIELD = { 'ship': 'ShipDesignName', 'room': 'RoomName', 'char': 'CharacterDesignName', 'item': 'ItemDesignName', 'collection': 'CollectionDesignId', 'sprite': 'SpriteKey', } DEFAULT_EXPIRATION_DURATION = 60 * 60 * 1 # 1 hours EQUIPMENT_SLOTS = ['Head', 'Body', 'Leg', 'Weapon', 'Accessory', 'Pet'] SLOT_MAP = { 'None': None, 'EquipmentHead': 'Head', 'EquipmentWeapon': 'Weapon', 'EquipmentBody': 'Body', 'EquipmentLeg': 'Leg', 'EquipmentAccessory': 'Accessory', 'EquipmentPet': 'Pet', 'MineralPack': 'Mineral Pack', 'GasPack': 'Gas Pack', 'InstantPrize': 'Instant Prize', 'InstantTraining': 'Instant Training', 'ReducePrestige': 'Reduce Prestige', 'ReduceFatigue': 'Reduce Fatigue', 'ResetTraining': 'Reset Training', 'AIBook': 'AI Book', 'FillMineralStorage': 'Fill Mineral Storage', 'FillGasStorage': 'Fill Gas Storage', 'SpeedUpConstruction': 'SpeedUp Construction', } ROOM_TYPE_MAP = { 'Wall': 'Armor', } ENHANCE_MAP = { 'FireResistance': 'Fire Resistance', 'FreezeAttackSkill': 'Freeze', 'Hp': 'HP', 'None': None } SHORT_ENHANCE_MAP = { 'Ability': 'ABL', 'Attack': 'ATK', 'Engine': 'ENG', 'FireResistance': 'RST', 'FreezeAttackSkill': 'ABL', 'Hp': 'HP', 'Pilot': 'PLT', 'Repair': 'RPR', 'Science': 'SCI', 'Stamina': 'STA', 'Weapon': 'WPN', 'None': None } RESEARCH_TYPE_MAP = { 'CrewLevelUpCost': 'Crew LevelUp Cost', 'ConcurrentConstruction': 'Concurrent Construction', 'TradeCapacity': 'Trade', 'ModuleCapacity': 'Module', 'StickerCapacity': 'Sticker', 'AmmoSalvageCapacity': 'Ammo Recycling', 'CollectAll': 'Collector', 'ItemRecycling': 'Item Recycling', 'BoostGauge': 'Boost Gauge', 'None': None } # Daily IAP mask (see https://github.com/PieInTheSky-Inc/YaDc) IAP_NAMES = { 500: 'Clip', 1200: 'Roll', 2500: 'Stash', 6500: 'Case', 14000: 'Vault' } # 0 - Rock? # 1 - Pirate/Dark # 2 - Fed/Blue # 3 - Qtari/Gold # 4 - Visiri/Red # 5 - UFO/Green # 6 - Starbase RACES = { 1: "Pirate", 2: "Federation", 3: "Qtarian", 4: "Visiri", 5: "Gray", } MODULE_ENHANCEMENT_MAP = { 'Turret': 'Attack' } MODULE_BONUS_RATIO_MAP = { 'Turret': 100 } MANUFACTURE_CAPACITY_MAP = { 'Shield': 'Restore', 'Recycling': 'Max Blend', 'Council': 'Max Donations', } MANUFACTURE_RATE_MAP = { 'Recycling': 'Harvest', } MANUFACTURE_RATE_PER_HOUR_MAP = { 'Laser': True, 'Mineral': True, 'Gas': True, 'Supply': True, } MANUFACTURE_CAPACITY_RATIO_MAP = { 'Shield': 100, 'Recycling': 1, } LABEL_CAPACITY_MAP = { 'Medical': 'Healing', 'Shield': 'Shield', 'Stealth': 'Cloak', 'Engine': 'Evasion', 'Trap': 'Crew Dmg', 'Radar': 'Detection', 'Training': 'Training Lvl', 'Recycling': 'DNA Capacity', 'Gas': 'Salvage', 'Mineral': 'Salvage', 'Council': 'Garrison', 'Command': 'Max AI', 'Bridge': 'Escape', } CAPACITY_RATIO_MAP = { 'Medical': 100, } def __init__(self): self._changes = None self._characters = None self._collections = None self._dailies = None self._situations = None self._items = None self._prestiges = {} self._researches = None self._prices = {} self._trainings = {} self._achievements = {} self._rooms = None self._ships = None self._sprites = None self._rooms_sprites = None self._upgrades = None self._rooms_by_name = None self._pixel_starships_api = None self.__data_expiration = {} @property def pixel_starships_api(self): if not self._pixel_starships_api or self.expired('api'): self._pixel_starships_api = PixelStarshipsApi() self.expire_at('api', 60 * 60 * 12) # 12h return self._pixel_starships_api @property def sprites(self): if not self._sprites or self.expired('sprite'): self._sprites = self._get_sprites_from_db() self.expire_at('sprite', self.DEFAULT_EXPIRATION_DURATION) return self._sprites @property def rooms_sprites(self): if not self._rooms_sprites or self.expired('room_sprite'): self._rooms_sprites = self._get_room_sprites_from_db() self.expire_at('room_sprite', self.DEFAULT_EXPIRATION_DURATION) return self._rooms_sprites @property def prices(self): if not self._prices or self.expired('prices'): self._prices = self._get_prices_from_db() self.expire_at('prices', self.DEFAULT_EXPIRATION_DURATION) return self._prices @property def trainings(self): if not self._trainings or self.expired('trainings'): self._trainings = self._get_trainings_from_db() self.expire_at('trainings', self.DEFAULT_EXPIRATION_DURATION) return self._trainings @property def achievements(self): if not self._achievements or self.expired('achievements'): self._achievements = self._get_achievements_from_db() self.expire_at('achievements', self.DEFAULT_EXPIRATION_DURATION) return self._achievements @property def ships(self): if not self._ships or self.expired('ship'): self._ships = self._get_ships_from_db() self.expire_at('ship', self.DEFAULT_EXPIRATION_DURATION) return self._ships @property def rooms(self): if not self._rooms or self.expired('room'): self._rooms, self._upgrades, self._rooms_by_name = self._get_rooms_from_db() self.expire_at('room', self.DEFAULT_EXPIRATION_DURATION) return self._rooms @property def rooms_by_name(self): if not self._rooms_by_name or self.expired('room'): self._rooms, self._upgrades, self._rooms_by_name = self._get_rooms_from_db() self.expire_at('room', self.DEFAULT_EXPIRATION_DURATION) return self._rooms_by_name @property def researches(self): if not self._researches or self.expired('room'): self._researches = self._get_researches_from_db() self.expire_at('research', self.DEFAULT_EXPIRATION_DURATION) return self._researches @property def upgrades(self): if not self._upgrades or self.expired('room'): self._rooms, self._upgrades, self._rooms_by_name = self._get_rooms_from_db() self.expire_at('room', self.DEFAULT_EXPIRATION_DURATION) return self._upgrades @property def characters(self): if not self._characters or self.expired('char'): self._characters = self._get_characters_from_db() if self._characters: self.expire_at('char', self.DEFAULT_EXPIRATION_DURATION) self.fill_char_collection_data() return self._characters @property def collections(self): if not self._collections or self.expired('collection'): self._collections = self._get_collections_from_db() if self._collections: self.expire_at('collection', self.DEFAULT_EXPIRATION_DURATION) self.fill_char_collection_data() return self._collections @property def items(self): if not self._items or self.expired('item'): self._items = self._get_items_from_db() self.expire_at('item', self.DEFAULT_EXPIRATION_DURATION) return self._items @property def dailies(self): if not self._dailies or self.expired('daily'): self._dailies = self._get_dailies_from_api() self.expire_at('daily', 60 * 5) return self._dailies @property def changes(self): if not self._changes or self.expired('change'): self._changes = self.get_changes_from_db() self.expire_at('change', 60 * 5) return self._changes @property def situations(self): if not self._situations or self.expired('situation'): self._situations = self._get_situations_from_api() self.expire_at('situation', 60 * 5) return self._situations def expired(self, key): """Check if cached data is expired.""" if key not in self.__data_expiration: return True data_expiration = self.__data_expiration[key] if not data_expiration: return True return datetime.datetime.utcnow().timestamp() - data_expiration > 0 def expire_at(self, key, secs): """Set expiration duration date.""" self.__data_expiration[key] = datetime.datetime.utcnow().timestamp() + secs def get_object(self, object_type, oid, reload_on_err=True): """Get PixyShip object from given PSS API type (LimitedCatalogType for example).""" try: if object_type == 'Item': return self.items[oid] if object_type == 'Character': return self.characters[oid] if object_type == 'Room': return self.rooms[oid] if object_type == 'Ship': return self.ships[oid] if object_type == 'Research': return self.researches[oid] except KeyError: print('KeyErrors') # Happens when there's new things, reload if reload_on_err: self._items = None self._characters = None self._items = None self._ships = None self._researches = None return self.get_object(object_type, oid, False) else: raise def fill_char_collection_data(self): """Updata char data with collection.""" if self.characters and self.collections: # update crew with collection data for char in self._characters.values(): if char['collection']: char['collection_sprite'] = self.collections[char['collection']]['icon_sprite'] char['collection_name'] = self.collections[char['collection']]['name'] # collection with crews for collection_id, collection in self._collections.items(): collection['chars'] = [char for char in self.characters.values() if char['collection'] == collection_id] def get_sprite_infos(self, sprite_id): """Get sprite infos from given id.""" if not sprite_id: return {} if isinstance(sprite_id, str): sprite_id = int(sprite_id) if not isinstance(sprite_id, int): return {} sprite = self.sprites.get(sprite_id) if not sprite: return {} return { 'source': sprite['image_file'], 'x': sprite['x'], 'y': sprite['y'], 'width': sprite['width'], 'height': sprite['height'], } def is_room_upgradeable(self, room_design_id, ship_design_id): """Check if room is upgradeable.""" upgrade_id = self.upgrades.get(room_design_id) if not upgrade_id: return False req_ship_level = self.rooms[upgrade_id]['min_ship_level'] ship_level = self.ships[ship_design_id]['level'] return req_ship_level <= ship_level @staticmethod def generate_layout(rooms, ship): """Compute ship layout matrix.""" layout = [[0] * ship['columns'] for _ in range(ship['rows'])] for room in rooms: room_position_x = room['column'] room_position_y = room['row'] room_id = room['id'] for x in range(room['width']): for y in range(room['height']): layout[room_position_y + y][room_position_x + x] = room_id return layout def compute_total_armor_effects(self, rooms, layout): """For each given rooms based on given layout, compute effective armor effects.""" for room in rooms: room_armor = 0 if room['power_gen'] + room['power_use'] > 0: # check left, right, top and bottom side room_position_x = room['column'] room_position_y = room['row'] room_width = room['width'] room_height = room['height'] for x in range(room_width): room_armor += self.get_armor_capacity(layout, rooms, room_position_x + x, room_position_y - 1) room_armor += self.get_armor_capacity(layout, rooms, room_position_x + x, room_position_y + room_height) for y in range(room_height): room_armor += self.get_armor_capacity(layout, rooms, room_position_x - 1, room_position_y + y) room_armor += self.get_armor_capacity(layout, rooms, room_position_x + room_width, room_position_y + y) room['armor'] = room_armor @staticmethod def get_armor_capacity(layout, rooms, x, y): """If room at given position is an armor, return armor capacity.""" neighbor = layout[y][x] if not neighbor: return 0 room = [r for r in rooms if r['id'] == neighbor][0] if room['type'] == 'Armor': return room['capacity'] return 0 def interiorize(self, room_id, ship_id): """Convert rooms to the correct interior depending on ship race.""" room = self.get_object('Room', room_id) if room['type'] in ('Armor', 'Lift'): ship = self.get_object('Ship', ship_id) if room['sprite']['source'] in self.RACE_SPECIFIC_SPRITE_MAP: # make a new sprite in a new room to keep from overwriting original data room = room.copy() sprite = room['sprite'].copy() sprite['source'] = self.RACE_SPECIFIC_SPRITE_MAP[room['sprite']['source']][ship['race']] room['sprite'] = sprite return room def get_exterior_sprite(self, room_id, ship_id): """Retrieve exterior sprite if existing""" ship = self.get_object('Ship', ship_id) exterior_sprite = None for _, room_sprite in self.rooms_sprites.items(): if room_sprite['room_id'] == room_id \ and room_sprite['race'] == ship['race'] \ and room_sprite['type'] == 'Exterior': exterior_sprite = self.get_sprite_infos(room_sprite['sprite_id']) return exterior_sprite @staticmethod def find_user_id(search_name): """Given a name return the user_id from database. This should only be an exact match.""" result = Player.query.filter(Player.name.ilike(search_name)).limit(1).first() if result: return result.id return None def get_upgrade_room(self, room_design_id): """Get the target upgrade room.""" upgrade_id = self.upgrades[room_design_id] if upgrade_id: return self.rooms[upgrade_id] return None def _get_sprites_from_db(self): """Load sprites from database.""" records = Record.query.filter_by(type='sprite', current=True).all() sprites = {} for record in records: sprite = self.pixel_starships_api.parse_sprite_node(ElementTree.fromstring(record.data)) sprites[record.type_id] = { 'image_file': int(sprite['ImageFileId']), 'x': int(sprite['X']), 'y': int(sprite['Y']), 'width': int(sprite['Width']), 'height': int(sprite['Height']), 'sprite_key': sprite['SpriteKey'], } return sprites def update_sprites(self): """Update data and save records.""" sprites = self.pixel_starships_api.get_sprites() for sprite in sprites: record_id = sprite['SpriteId'] Record.update_data('sprite', record_id, sprite['pixyship_xml_element']) def _get_room_sprites_from_api(self): """Get room sprites from API.""" rooms_sprites = self.pixel_starships_api.get_rooms_sprites() return { int(room_sprite['RoomDesignSpriteId']): { 'room_id': int(room_sprite['RoomDesignId']), 'race': int(room_sprite['RaceId']), 'sprite_id': int(room_sprite['SpriteId']), 'type': room_sprite['RoomSpriteType'], } for room_sprite in rooms_sprites } def _get_room_sprites_from_db(self): """Load sprites from database.""" records = Record.query.filter_by(type='room_sprite', current=True).all() room_sprites = {} for record in records: room_sprite = self.pixel_starships_api.parse_room_sprite_node(ElementTree.fromstring(record.data)) room_sprites[record.type_id] = { 'room_id': int(room_sprite['RoomDesignId']), 'race': int(room_sprite['RaceId']), 'sprite_id': int(room_sprite['SpriteId']), 'type': room_sprite['RoomSpriteType'], } return room_sprites def update_room_sprites(self): """Update data and save records.""" room_sprites = self.pixel_starships_api.get_rooms_sprites() for room_sprite in room_sprites: record_id = room_sprite['RoomDesignSpriteId'] Record.update_data('room_sprite', record_id, room_sprite['pixyship_xml_element']) def _get_trainings_from_db(self): """Load trainings from database.""" records = Record.query.filter_by(type='training', current=True).all() trainings = {} for record in records: training = self.pixel_starships_api.parse_training_node(ElementTree.fromstring(record.data)) trainings[record.type_id] = { 'id': int(training['TrainingDesignId']), 'sprite': self.get_sprite_infos(int(training['TrainingSpriteId'])), 'hp': int(training['HpChance']), 'attack': int(training['AttackChance']), 'pilot': int(training['PilotChance']), 'repair': int(training['RepairChance']), 'weapon': int(training['WeaponChance']), 'science': int(training['ScienceChance']), 'engine': int(training['EngineChance']), 'stamina': int(training['StaminaChance']), 'ability': int(training['AbilityChance']), 'xp': int(training['XpChance']), 'fatigue': int(training['Fatigue']), 'minimum_guarantee': int(training['MinimumGuarantee']) } return trainings def update_trainings(self): """Update data and save records.""" trainings = self.pixel_starships_api.get_trainings() for training in trainings: record_id = int(training['TrainingDesignId']) Record.update_data('training', record_id, training['pixyship_xml_element']) def _get_achievements_from_db(self): """Load achievements from database.""" records = Record.query.filter_by(type='achievement', current=True).all() achievements = {} all_parent_achievement_design_id = [] for record in records: achievement = self.pixel_starships_api.parse_achievement_node(ElementTree.fromstring(record.data)) starbux_reward = 0 mineral_reward = 0 gas_reward = 0 all_parent_achievement_design_id.append(int(achievement['ParentAchievementDesignId'])) reward_content = achievement['RewardString'] if reward_content: reward_type, reward_value = reward_content.split(':') if reward_type == 'starbux': starbux_reward = int(reward_value) elif reward_type == 'mineral': mineral_reward = int(reward_value) elif reward_type == 'gas': gas_reward = int(reward_value) achievements[record.type_id] = { 'id': int(achievement['AchievementDesignId']), 'sprite': self.get_sprite_infos(int(achievement['SpriteId'])), 'name': achievement['AchievementTitle'], 'description': achievement['AchievementDescription'], 'starbux_reward': starbux_reward, 'mineral_reward': mineral_reward, 'gas_reward': gas_reward, 'max_reward': max([starbux_reward, mineral_reward, gas_reward]), 'pin_reward': False # default value, defined after } # second loop to define pin's reward for achievement in achievements.values(): if not achievement['id'] in all_parent_achievement_design_id: achievement['pin_reward'] = True return achievements def update_achievements(self): """Update data and save records.""" achievements = self.pixel_starships_api.get_achievements() for achievement in achievements: record_id = int(achievement['AchievementDesignId']) Record.update_data('achievement', record_id, achievement['pixyship_xml_element']) @staticmethod def _get_prices_from_db(): """Get all history market summary from database.""" sql = """ SELECT item_id , currency , SUM(amount) as count , percentile_disc(.25) WITHIN GROUP (ORDER BY price/amount) AS p25 , percentile_disc(.5) WITHIN GROUP (ORDER BY price/amount) AS p50 , percentile_disc(.75) WITHIN GROUP (ORDER BY price/amount) AS p75 FROM listing WHERE amount > 0 AND sale_at > (now() - INTERVAL '48 HOURS') GROUP BY item_id, currency """ result = db.session.execute(sql).fetchall() prices = defaultdict(dict) for row in result: item_id = row[0] currency = row[1] prices[item_id][currency] = { 'count': row[2], 'p25': row[3], 'p50': row[4], 'p75': row[5], } return prices @staticmethod def get_item_prices_from_db(item_id): """Get item history market from database.""" sql = """ SELECT item_id , item_name , currency , sale_at::DATE AS sale_date , SUM(amount) AS count , percentile_disc(.25) WITHIN GROUP (ORDER BY price/amount) AS p25 , percentile_disc(.5) WITHIN GROUP (ORDER BY price/amount) AS p50 , percentile_disc(.75) WITHIN GROUP (ORDER BY price/amount) AS p75 FROM listing WHERE item_id = :item_id AND amount > 0 AND sale_at::DATE >= now() - '6 months'::INTERVAL GROUP BY item_id, item_name, currency, sale_at::DATE ORDER BY item_id, item_name, currency, sale_at::DATE """ result = db.session.execute(sql, {'item_id': item_id}).fetchall() prices = defaultdict(lambda: defaultdict(dict)) for row in result: currency = row[2] sale_date = str(row[3]) prices[currency][sale_date] = { 'count': row[4], 'p25': row[5], 'p50': row[6], 'p75': row[7], } data = { 'id': item_id, 'prices': prices, } return data @staticmethod def get_item_last_sales_from_db(item_id, limit): """Get last sales from database.""" sql = """ SELECT sale_at, amount, currency, price, user_name as buyer_name, seller_name, id FROM listing WHERE item_id = :item_id AND amount > 0 AND user_name IS NOT NULL AND seller_name IS NOT NULL ORDER BY sale_at DESC LIMIT :limit """ result = db.session.execute(sql, {'item_id': item_id, 'limit': limit}).fetchall() last_sales = [] for row in result: last_sales.append({ 'id': int(row[6]), 'date': str(row[0]), 'quantity': row[1], 'currency': row[2], 'price': row[3], 'buyer': row[4], 'seller': row[5], }) return last_sales def update_ships(self): """Get ships from API and save them in database.""" ships = self.pixel_starships_api.get_ships() for ship in ships: record_id = ship['ShipDesignId'] Record.update_data('ship', record_id, ship['pixyship_xml_element']) def _get_ships_from_db(self): """Load ships from database.""" records = Record.query.filter_by(type='ship', current=True).all() ships = {} for record in records: ship = self.pixel_starships_api.parse_ship_node(ElementTree.fromstring(record.data)) starbux_cost, mineral_cost, items_cost = self._parse_ship_unlock_costs(ship['MineralCost'], ship['StarbuxCost'], ship['UnlockCost']) ships[record.type_id] = { 'id': record.type_id, 'name': ship['ShipDesignName'], 'description': ship['ShipDescription'], 'level': int(ship['ShipLevel']), 'hp': int(ship['Hp']), 'repair_time': int(ship['RepairTime']), 'full_repair_time': time.strftime('%H:%M:%S', time.gmtime(int(ship['RepairTime']) * int(ship['Hp']))), 'exterior_sprite': self.get_sprite_infos(int(ship['ExteriorSpriteId'])), 'interior_sprite': self.get_sprite_infos(int(ship['InteriorSpriteId'])), 'logo_sprite': self.get_sprite_infos(int(ship['LogoSpriteId'])), 'mini_ship_sprite': self.get_sprite_infos(int(ship['MiniShipSpriteId'])), 'frame_sprite': self.get_sprite_infos(int(ship['RoomFrameSpriteId'])), 'left_door_sprite': self.get_sprite_infos(int(ship['DoorFrameLeftSpriteId'])), 'right_door_sprite': self.get_sprite_infos(int(ship['DoorFrameRightSpriteId'])), 'rows': int(ship['Rows']), 'columns': int(ship['Columns']), 'race': int(ship['RaceId']), 'mask': ship['Mask'], 'mineral_cost': mineral_cost, 'starbux_cost': starbux_cost, 'items_cost': items_cost, 'mineral_capacity': ship['MineralCapacity'], 'gas_capacity': ship['GasCapacity'], 'equipment_capacity': ship['EquipmentCapacity'], 'ship_type': ship['ShipType'], } return ships def update_researches(self): """Update data and save records.""" researches = self.pixel_starships_api.get_researches() for research in researches: record_id = research['ResearchDesignId'] Record.update_data('research', record_id, research['pixyship_xml_element']) def _get_researches_from_db(self): """Load researches from database.""" records = Record.query.filter_by(type='research', current=True).all() researches = {} for record in records: research = self.pixel_starships_api.parse_research_node(ElementTree.fromstring(record.data)) researches[record.type_id] = { **research, 'id': record.type_id, 'name': research['ResearchName'], 'description': research['ResearchDescription'], 'gas_cost': int(research['GasCost']), 'starbux_cost': int(research['StarbuxCost']), 'lab_level': int(research['RequiredLabLevel']), 'research_seconds': int(research['ResearchTime']), 'logo_sprite': self.get_sprite_infos(research['LogoSpriteId']), 'sprite': self.get_sprite_infos(research['ImageSpriteId']), 'required_research_id': int(research['RequiredResearchDesignId']), 'research_type': self.RESEARCH_TYPE_MAP.get(research['ResearchDesignType'], research['ResearchDesignType']) } for research in researches.values(): research['required_research_name'] = ( researches[research['required_research_id']]['name'] if research['required_research_id'] else '' ) return researches @staticmethod def _parse_price_from_pricestring(pricestring): """Split amount and currency.""" if not pricestring: return 0, None parts = pricestring.split(':') return int(parts[1]), parts[0] def update_rooms(self): """Get rooms from API and save them in database.""" rooms = self.pixel_starships_api.get_rooms() for room in rooms: record_id = room['RoomDesignId'] Record.update_data('room', record_id, room['pixyship_xml_element'], ['AvailabilityMask']) def _get_rooms_from_db(self): """Load rooms from database.""" records = Record.query.filter_by(type='room', current=True).all() rooms = {} for record in records: room = self.pixel_starships_api.parse_room_node(ElementTree.fromstring(record.data)) missile_design = room['MissileDesign'] room_price, room_price_currency = self._parse_price_from_pricestring(room['PriceString']) room_type = self.ROOM_TYPE_MAP.get(room['RoomType'], room['RoomType']) rooms[record.type_id] = { 'id': record.type_id, 'name': room['RoomName'], 'short_name': room['RoomShortName'], 'type': room_type, 'level': int(room['Level']), 'capacity': int(room['Capacity']) / self.CAPACITY_RATIO_MAP.get(room['RoomType'], 1), 'capacity_label': self.LABEL_CAPACITY_MAP.get(room['RoomType'], 'Capacity'), 'range': int(room['Range']), 'height': int(room['Rows']), 'width': int(room['Columns']), 'sprite': self.get_sprite_infos(int(room['ImageSpriteId'])), 'construction_sprite': self.get_sprite_infos(int(room['ConstructionSpriteId'])), 'power_use': int(room['MaxSystemPower']), 'power_gen': int(room['MaxPowerGenerated']), 'min_ship_level': int(room['MinShipLevel']), 'upgrade_from_id': int(room['UpgradeFromRoomDesignId']), 'defense': int(room['DefaultDefenceBonus']), 'reload': int(room['ReloadTime']), 'refill_cost': int(room['RefillUnitCost']), 'show_frame': room_type not in ('Lift', 'Armor', 'Corridor'), 'upgrade_cost': room_price, 'upgrade_currency': room_price_currency, 'upgrade_seconds': int(room['ConstructionTime']), 'description': room['RoomDescription'], 'enhancement_type': room['EnhancementType'], 'manufacture_type': room['ManufactureType'], 'manufacture_rate': float(room['ManufactureRate']), 'manufacture_rate_label': self.MANUFACTURE_RATE_MAP.get(room['RoomType'], 'Manufacture Rate'), 'manufacture_rate_per_hour': math.ceil(float(room['ManufactureRate']) * 3600) if self.MANUFACTURE_RATE_PER_HOUR_MAP.get(room['RoomType'], False) else None, 'manufacture_capacity': int(room['ManufactureCapacity']) / self.MANUFACTURE_CAPACITY_RATIO_MAP.get(room['RoomType'], 1), 'manufacture_capacity_label': self.MANUFACTURE_CAPACITY_MAP.get(room['RoomType'], None), 'cooldown_time': int(room['CooldownTime']), 'requirement': self._parse_requirement(room['RequirementString']), 'extension_grids': int(room.get('SupportedGridTypes', '0')) & 2 != 0, 'has_weapon_stats': True if missile_design else False, 'purchasable': True if 'AvailabilityMask' in room else False, 'system_damage': float(missile_design['SystemDamage']) if missile_design else 0, 'hull_damage': float(missile_design['HullDamage']) if missile_design else 0, 'character_damage': float(missile_design['CharacterDamage']) if missile_design else 0, 'shield_damage': float(missile_design['ShieldDamage']) if missile_design else 0, 'direct_system_damage': float(missile_design['DirectSystemDamage']) if missile_design else 0, 'volley': float(missile_design['Volley']) if missile_design else 0, 'volley_delay': float(missile_design['VolleyDelay']) if missile_design else 0, 'speed': float(missile_design['Speed']) if missile_design else 0, 'fire_length': float(missile_design['FireLength']) if missile_design else 0, 'emp_length': float(missile_design['EMPLength']) if missile_design else 0, 'stun_length': float(missile_design['StunLength']) if missile_design else 0, 'hull_percentage_damage': float(missile_design['HullPercentageDamage']) if missile_design else 0, } upgrades = { room['upgrade_from_id']: room_id for room_id, room in rooms.items() } rooms_by_name = { room['name']: room for room_id, room in rooms.items() } return rooms, upgrades, rooms_by_name def _parse_equipment_slots(self, char): """Determine equipments slots with char equipment mask.""" equipment_mask = int(char['EquipmentMask']) output = [int(x) for x in '{:06b}'.format(equipment_mask)] slots = {self.EQUIPMENT_SLOTS[5 - i]: {} for i, b in enumerate(output) if b} return slots def update_characters(self): """Get crews from API and save them in database.""" characters = self.pixel_starships_api.get_characters() for character in characters: record_id = character['CharacterDesignId'] Record.update_data('char', record_id, character['pixyship_xml_element']) def _get_characters_from_db(self): """Load crews from database.""" records = Record.query.filter_by(type='char', current=True).all() characters = {} for record in records: character_node = ElementTree.fromstring(record.data) character = self.pixel_starships_api.parse_character_node(character_node) characters[record.type_id] = { 'name': character['CharacterDesignName'], 'id': record.type_id, 'sprite': self.get_sprite_infos(int(character['ProfileSpriteId'])), 'head_sprite': self.get_sprite_infos(int(character['CharacterParts']['Head']['StandardSpriteId'])), 'body_sprite': self.get_sprite_infos(int(character['CharacterParts']['Body']['StandardSpriteId'])), 'leg_sprite': self.get_sprite_infos(int(character['CharacterParts']['Leg']['StandardSpriteId'])), 'rarity': character['Rarity'].lower(), # Sprites for gems are 1593. 1594 'rarity_order': self.RARITY_MAP[character['Rarity']], 'hp': int_range(character, 'Hp', 'FinalHp'), 'pilot': float_range(character, 'Pilot', 'FinalPilot'), 'attack': float_range(character, 'Attack', 'FinalAttack'), 'repair': float_range(character, 'Repair', 'FinalRepair'), 'weapon': float_range(character, 'Weapon', 'FinalWeapon'), 'engine': float_range(character, 'Engine', 'FinalEngine'), 'research': float_range(character, 'Research', 'FinalResearch'), 'science': float_range(character, 'Science', 'FinalScience'), 'ability': float_range(character, 'SpecialAbilityArgument', 'SpecialAbilityFinalArgument'), 'special_ability': self.ABILITY_MAP.get(character['SpecialAbilityType'], {'name': ''})['name'], 'ability_sprite': self.get_sprite_infos(self.ABILITY_MAP.get(character['SpecialAbilityType'], {'sprite': 110})['sprite']), 'fire_resist': int(character['FireResistance']), 'resurrect': 0, 'walk': int(character['WalkingSpeed']), 'run': int(character['RunSpeed']), 'training_limit': int(character['TrainingCapacity']), 'progression_type': character['ProgressionType'], 'equipment': self._parse_equipment_slots(character), 'collection': int(character['CollectionDesignId']), 'collection_sprite': None, 'collection_name': '', 'description': character['CharacterDesignDescription'], } # computed properties characters[record.type_id]['width'] = max( characters[record.type_id]['head_sprite']['width'], characters[record.type_id]['body_sprite']['width'], characters[record.type_id]['leg_sprite']['width'] ) return characters def update_collections(self): """Get collections from API and save them in database.""" collections = self.pixel_starships_api.get_collections() for collection in collections: record_id = collection['CollectionDesignId'] Record.update_data('collection', record_id, collection['pixyship_xml_element']) def _get_collections_from_db(self): """Load collections from database.""" records = Record.query.filter_by(type='collection', current=True).all() collections = {} for record in records: collection_node = ElementTree.fromstring(record.data) collection = self.pixel_starships_api.parse_collection_node(collection_node) collection.update({ 'id': int(collection['CollectionDesignId']), 'name': collection['CollectionName'], 'min': int(collection['MinCombo']), 'max': int(collection['MaxCombo']), 'base_enhancement': int(collection['BaseEnhancementValue']), 'sprite': self.get_sprite_infos(int(collection['SpriteId'])), 'step_enhancement': int(collection['StepEnhancementValue']), 'icon_sprite': self.get_sprite_infos(int(collection['IconSpriteId'])), 'chars': [], 'ability_name': self.COLLECTION_ABILITY_MAP[collection['EnhancementType']], }) collections[record.type_id] = collection return collections @staticmethod def _parse_item_recipe(item_list_string, items): """Parse recipe infos from API.""" recipe = [] if item_list_string: ingredients = [i.split('x') for i in item_list_string.split('|')] for ingredient in ingredients: # replace hack, 2021 easter event come with additional 'item:' prefix ingredient_item_id = ingredient[0].replace('item:', '') item = items.get(int(ingredient_item_id)) if item: line = Pixyship._create_light_item(item, items) line['count'] = int(ingredient[1]) recipe.append(line) return recipe @staticmethod def _create_light_item(item, items=None): return { 'id': item['id'], 'name': item['name'], 'sprite': item['sprite'], 'rarity': item['rarity'], 'slot': item['slot'], 'type': item['type'], 'disp_enhancement': item['disp_enhancement'], 'short_disp_enhancement': item['short_disp_enhancement'], 'bonus': item['bonus'], 'module_extra_disp_enhancement': item['module_extra_disp_enhancement'], 'module_extra_short_disp_enhancement': item['module_extra_short_disp_enhancement'], 'module_extra_enhancement_bonus': item['module_extra_enhancement_bonus'], 'prices': item['prices'], 'recipe': item['recipe'] if not items else Pixyship._parse_item_recipe(item['ingredients'], items), } def _parse_item_content(self, item_content_string, last_item, items): """Parse content infos from API.""" content = [] if item_content_string: content_items = item_content_string.split('|') for content_item in content_items: if not content_item: continue content_item_unpacked = content_item.split(':') content_item_type = content_item_unpacked[0] content_item_id_count_unpacked = content_item_unpacked[1].split('x') content_item_id = content_item_id_count_unpacked[0] line = {} # if change's a Character, get all infos of the crew if content_item_type == 'character': try: line['char'] = self.characters[int(content_item_id)] except KeyError: continue # if change's a Item, get all infos of the item elif content_item_type == 'item': try: item = items.get(int(content_item_id)) except KeyError: continue line['item'] = Pixyship._create_light_item(item) # avoid infinite recursion when item reward can be the item itself if last_item['id'] != item['id']: line['item']['content'] = self._parse_item_content(item['content_string'], item, items) # Unknown type else: continue content_item_count = 1 if len(content_item_id_count_unpacked) > 1: content_item_count = int(content_item_id_count_unpacked[1]) line.update({ 'count': content_item_count, 'id': content_item_id, 'type': content_item_type, }) content.append(line) return content def _parse_ship_unlock_costs(self, mineral_cost_string, starbux_cost_string, unlock_cost_string): """Parse ship unlock cost infos from API.""" starbux_cost = 0 mineral_cost = 0 items_cost = [] if unlock_cost_string: costs = unlock_cost_string.split('|') for cost in costs: cost_type, cost_value = cost.split(':') if cost_type == 'starbux': starbux_cost = int(cost_value) continue if cost_type == 'mineral': mineral_cost = int(cost_value) continue if cost_type == 'item': item = self.items.get(int(cost_value)) if item: item_cost = Pixyship._create_light_item(item) items_cost.append(item_cost) continue else: # no UnlockCost, use MineralCost and StarbuxCost starbux_cost = int(starbux_cost_string) mineral_cost = int(mineral_cost_string) return starbux_cost, mineral_cost, items_cost def update_items(self): """Get items from API and save them in database.""" items = self.pixel_starships_api.get_items() for item in items: record_id = item['ItemDesignId'] Record.update_data('item', record_id, item['pixyship_xml_element'], ['FairPrice', 'MarketPrice']) def _get_items_from_db(self): """Get items from database.""" records = Record.query.filter_by(type='item', current=True).all() items = {} for record in records: item_node = ElementTree.fromstring(record.data) item = self.pixel_starships_api.parse_item_node(item_node) number_of_rewards = 0 if item['Content'] and float(item['ModuleArgument']) != 0: number_of_rewards = item['ModuleArgument'] module_extra_enhancement = self._parse_module_extra_enhancement(item) items[record.type_id] = { 'name': item['ItemDesignName'], 'description': item['ItemDesignDescription'], 'sprite': self.get_sprite_infos(int(item['ImageSpriteId'])), 'logo_sprite': self.get_sprite_infos(int(item['LogoSpriteId'])), 'slot': self.SLOT_MAP.get(item['ItemSubType'], item['ItemSubType']), 'enhancement': item.get('EnhancementType').lower(), 'disp_enhancement': self.ENHANCE_MAP.get(item['EnhancementType'], item['EnhancementType']), 'short_disp_enhancement': self.SHORT_ENHANCE_MAP.get(item['EnhancementType'], item['EnhancementType']), 'bonus': float(item.get('EnhancementValue')), 'module_extra_enhancement': module_extra_enhancement['enhancement'], 'module_extra_disp_enhancement': module_extra_enhancement['disp_enhancement'], 'module_extra_short_disp_enhancement': module_extra_enhancement['short_disp_enhancement'], 'module_extra_enhancement_bonus': module_extra_enhancement['bonus'], 'type': item.get('ItemType'), 'rarity': item.get('Rarity').lower(), 'ingredients': item['Ingredients'], 'content_string': item['Content'], 'number_of_rewards': number_of_rewards, 'market_price': int(item['MarketPrice']), 'fair_price': int(item['FairPrice']), 'prices': self.prices.get(int(item['ItemDesignId'])), 'training': self.trainings.get(int(item['TrainingDesignId'])), 'id': record.type_id, 'saleable': (int(item['Flags']) & 1) != 0 } # Second pass required for self references for item in items.values(): item['recipe'] = self._parse_item_recipe(item['ingredients'], items) # Third pass required for self references for item in items.values(): item['content'] = self._parse_item_content(item['content_string'], item, items) return items def get_top100_alliances_from_api(self): """Get the top 100 alliances.""" alliances = self.pixel_starships_api.get_alliances() return { int(alliance['AllianceId']): { 'name': alliance['AllianceName'], } for alliance in alliances } def get_sales_from_api(self, item_id): """Get market history of item.""" # get max sale_id to retrieve only new sales max_sale_id_result = Listing.query \ .filter(Listing.item_id == item_id) \ .order_by(desc(Listing.id)) \ .limit(1) \ .first() if max_sale_id_result is not None: max_sale_id = max_sale_id_result.id if max_sale_id_result.id is not None else 0 else: max_sale_id = 0 sales = self.pixel_starships_api.get_sales(item_id, max_sale_id) return sales def get_alliance_users_from_api(self, alliance_id): """Get the top 100 alliances.""" users = self.pixel_starships_api.get_alliance_users(alliance_id) return self._parse_users(users) def get_top100_users_from_api(self): """Get the top 100 players.""" users = self.pixel_starships_api.get_users(1, 100) return self._parse_users(users) @staticmethod def _parse_users(users): """Create users dict from XML PSS API response.""" # force users to be a list if not isinstance(users, list): users = [users] return { int(user['Id']): { 'name': user['Name'], 'trophies': int(user['Trophy']), 'alliance_id': int(user['AllianceId']), 'last_login_at': user['LastLoginDate'], 'alliance_name': user.get('AllianceName'), 'alliance_sprite_id': int(user['AllianceSpriteId']), } for user in users } def _get_prestige_to_from_api(self, character_id): """Get prestige paires and groups which create given char_id.""" prestiges = self.pixel_starships_api.get_prestiges_character_to(character_id) # if only one unique prestige, add it in list if not isinstance(prestiges, list): prestiges = list((prestiges,)) prestiges_to = list( set( tuple( sorted([int(prestige['CharacterDesignId1']), int(prestige['CharacterDesignId2'])]) ) for prestige in prestiges ) ) # determine which crews to group temp_to = prestiges_to grouped_to = defaultdict(list) while len(temp_to): counter = Counter([x for y in temp_to for x in y]) [(most_id, _)] = counter.most_common(1) # find all the pairs with the id new_to = [] for pair in temp_to: if most_id == pair[0]: grouped_to[most_id].append(pair[1]) elif most_id == pair[1]: grouped_to[most_id].append(pair[0]) else: new_to.append(pair) temp_to = new_to return prestiges_to, grouped_to def _get_prestige_from_from_api(self, character_id): """Get prestige paires and groups created with given char_id.""" prestiges = self.pixel_starships_api.get_prestiges_character_from(character_id) prestiges_from = [[int(prestige['CharacterDesignId2']), int(prestige['ToCharacterDesignId'])] for prestige in prestiges] grouped_from = defaultdict(list) for response in prestiges_from: grouped_from[response[1]].append(response[0]) return prestiges_from, grouped_from def get_prestiges_from_api(self, char_id): """Get all prestige combinaisons.""" prestiges_to, grouped_to = self._get_prestige_to_from_api(char_id) prestiges_from, grouped_from = self._get_prestige_from_from_api(char_id) all_ids = list(set([i for prestige in prestiges_to for i in prestige] + [i for prestige in prestiges_from for i in prestige] + [char_id])) all_chars = [self.characters[i] for i in all_ids] return { 'to': grouped_to, 'from': grouped_from, 'chars': all_chars, 'expires_at': datetime.datetime.now() + datetime.timedelta(minutes=1) } def get_changes_from_db(self): """Get changes from database.""" # retrieve minimum dates of each types min_changes_dates_sql = """ SELECT type, MIN(created_at) + INTERVAL '1 day' AS min FROM record WHERE type IN ('item', 'ship', 'char', 'room', 'sprite') GROUP BY type """ min_changes_dates_result = db.session.execute(min_changes_dates_sql).fetchall() min_changes_dates_conditions = [] for min_changes_dates_record in min_changes_dates_result: if min_changes_dates_record['type'] == 'sprite': # only new condition = "(c.type = '{}' AND o.data IS NULL AND (o.id IS NOT NULL OR c.created_at > '{}'))".format( min_changes_dates_record['type'], min_changes_dates_record['min'] ) else: condition = "(c.type = '{}' AND (o.id IS NOT NULL OR c.created_at > '{}'))".format( min_changes_dates_record['type'], min_changes_dates_record['min'] ) min_changes_dates_conditions.append(condition) sql = """ SELECT * FROM ( SELECT DISTINCT ON (c.id) c.id, c.type, c.type_id, c.data, c.created_at, o.data as old_data FROM record c LEFT JOIN record o ON o.type = c.type AND o.type_id = c.type_id AND o.current = FALSE WHERE c.current = TRUE AND ({}) ORDER BY c.id, o.created_at DESC ) AS sub ORDER BY created_at DESC LIMIT {} """.format(' OR '.join(min_changes_dates_conditions), CONFIG.get('CHANGES_MAX_ASSETS', 5000)) result = db.session.execute(sql).fetchall() changes = [] for record in result: record_data = ElementTree.fromstring(record['data']).attrib sprite = self.get_record_sprite(record['type'], record['type_id']) change = { 'type': record['type'], 'id': record['type_id'], 'name': record_data[self.TYPE_PSS_API_NAME_FIELD[record['type']]], 'changed_at': record['created_at'], 'data': record['data'], 'old_data': record['old_data'], 'change_type': 'Changed' if record['old_data'] else 'New', 'sprite': sprite } # if change's a Character, get all infos of the crew if record['type'] == 'char': change['char'] = self.characters[record['type_id']] # if change's a Item, get all infos of the item if record['type'] == 'item': item = self.items[record['type_id']] change['item'] = Pixyship._create_light_item(item) changes.append(change) return changes def _format_daily_offer(self, description, sprite_id, items, cost=None, details=None, expires=None): return { 'description': description, 'sprite': self.get_sprite_infos(sprite_id), 'objects': items, 'cost': cost, 'details': details, 'expires': expires, } @staticmethod def _format_daily_object(count, type_str, object_str): return { 'count': count, 'type': type_str, 'object': object_str, } @staticmethod def _format_daily_price(amount, currency): return { 'price': amount, 'currency': currency, } def _parse_requirement(self, requirement_string): """Split requirements into items.""" if not requirement_string: return None requirement_type, id_and_amount = requirement_string.split(':') if '>=' in id_and_amount: requirement_id, requirement_count = id_and_amount.split('>=') else: requirement_id, requirement_count = id_and_amount.split('>') requirement_type = requirement_type.strip().capitalize() requirement_id = int(requirement_id.strip()) requirement_count = int(requirement_count.strip()) # in some case (example: Coal Factory), the amount needed is '> 0' not '>= 1' if requirement_count == 0: requirement_count = 1 requirement_object = { 'count': requirement_count, 'type': requirement_type, 'object': self.get_object(requirement_type, requirement_id), } return requirement_object def _parse_daily_cargo(self, item_list_string, cost_list_string): """Split daily cargo data into prices and items.""" splitted_items = [i.split('x') for i in item_list_string.split('|')] items = [ { 'count': int(item[1]), 'type': 'Item', 'object': self.items[int(item[0])], } for item in splitted_items ] splitted_prices = [i.split(':') for i in cost_list_string.split('|')] prices = [] for splitted_price in splitted_prices: price = { 'currency': splitted_price[0] } amount = splitted_price[1].split('x') if len(amount) > 1: item_id = int(amount[0]) price['price'] = item_id price['count'] = amount[1] price['object'] = self.items[item_id] else: price['price'] = int(splitted_price[1]) prices.append(price) cargo = [self._format_daily_offer('Cargo', None, [item], price) for item, price in zip(items, prices)] return cargo def _parse_daily_items(self, item_list_string): items_split = [i.split('x') for i in item_list_string.split('|')] items = [ { 'count': int(item[1]), 'type': 'Item', 'object': self.items[int(item[0])], } for item in items_split ] return items def _get_dailies_from_api(self): """Get settings service data, sales, motd from API.""" data = self.pixel_starships_api.get_dailies() offers = { 'shop': self._format_daily_offer( 'Shop', 592, [ self._format_daily_object( 1, data['LimitedCatalogType'], self.get_object(data['LimitedCatalogType'], int(data['LimitedCatalogArgument'])) ) ], self._format_daily_price(data['LimitedCatalogCurrencyAmount'], data['LimitedCatalogCurrencyType']), { 'left': data['LimitedCatalogQuantity'], 'max': data['LimitedCatalogMaxTotal'], }, data['LimitedCatalogExpiryDate'] ), 'blueCargo': { 'sprite': self.get_sprite_infos(11880), 'items': [ self._format_daily_offer( 'Mineral Crew', None, [self._format_daily_object(1, 'Character', self.get_object('Character', int(data['CommonCrewId'])))], ), self._format_daily_offer( 'Starbux Crew', None, [self._format_daily_object(1, 'Character', self.get_object('Character', int(data['HeroCrewId'])))], ) ], }, 'greenCargo': { 'sprite': self.get_sprite_infos(11881), 'items': self._parse_daily_cargo(data['CargoItems'], data['CargoPrices']), }, 'dailyRewards': self._format_daily_offer( 'Reward', 2326, [ self._format_daily_object( int(data['DailyRewardArgument']), 'Currency', self._format_daily_price(int(data['DailyRewardArgument']), data['DailyRewardType']) ) ] + self._parse_daily_items(data['DailyItemRewards']), ), 'sale': self._format_daily_offer( 'Sale', 11006, [ self._format_daily_object( 1, data['SaleType'], self.get_object(data['SaleType'], int(data['SaleArgument'])) ) ], { 'options': self._format_daily_sale_options(int(data['SaleItemMask'])) } ) } dailies = { 'stardate': self.pixel_starships_api.get_stardate(), 'news': { 'news': data['News'], 'news_date': data['NewsUpdateDate'], 'maintenance': self.pixel_starships_api.maintenance_message, # not anymore available with the new API endpoint 'sprite': self.get_sprite_infos(data['NewsSpriteId']), }, 'tournament_news': data['TournamentNews'], 'current_situation': self._get_current_situation(), 'offers': offers, } return dailies def _get_situations_from_api(self): """Get situations from API.""" data = self.pixel_starships_api.get_situations() situations = [] for datum in data: situation = { 'id': int(datum['SituationDesignId']), 'name': datum['SituationName'], 'description': datum['SituationDescription'], 'sprite': self.get_sprite_infos(datum['IconSpriteId']), 'from': datum['FromDate'], 'end': datum['EndDate'], } situations.append(situation) return situations def _get_current_situation(self): """Get running situation depending on the current date.""" utc_now = datetime.datetime.utcnow() for situation in self.situations: from_date = datetime.datetime.strptime(situation['from'], "%Y-%m-%dT%H:%M:%S") end_date = datetime.datetime.strptime(situation['end'], "%Y-%m-%dT%H:%M:%S") if from_date <= utc_now <= end_date: situation_left_delta = end_date - utc_now situation_left_seconds = situation_left_delta.days * 24 * 3600 + situation_left_delta.seconds situation_left_minutes, situation_left_seconds = divmod(situation_left_seconds, 60) situation_left_hours, situation_left_minutes = divmod(situation_left_minutes, 60) situation_left_days, situation_left_hours = divmod(situation_left_hours, 24) situation_left_weeks, situation_left_days = divmod(situation_left_days, 7) situation_left_formatted = '' if situation_left_weeks > 0: situation_left_formatted += '{}w'.format(situation_left_weeks) if situation_left_days > 0: situation_left_formatted += ' {}d'.format(situation_left_days) if situation_left_hours > 0: situation_left_formatted += ' {}h'.format(situation_left_hours) if situation_left_minutes > 0: situation_left_formatted += ' {}m'.format(situation_left_minutes) situation['left'] = situation_left_formatted.strip() return situation return None def get_record_sprite(self, record_type, record_id, reload_on_error=True): """Get sprite date for the given record ID.""" try: if record_type == 'item': return self.items[record_id]['sprite'] if record_type == 'char': return self.characters[record_id]['sprite'] if record_type == 'room': return self.rooms[record_id]['sprite'] if record_type == 'ship': return self.ships[record_id]['mini_ship_sprite'] if record_type == 'sprite': return self.get_sprite_infos(record_id) except KeyError: # happens when there's new things, reload if reload_on_error: self._items = None self._characters = None self._rooms = None self._ships = None return self.get_record_sprite(record_type, record_id, False) else: raise def get_player_data(self, search: str = None): """Retrieve all players data or players found by given search.""" query = ( db.session .query(Player.name, Player.trophies, Alliance.name.label('alliance_name'), Alliance.sprite_id) .outerjoin(Alliance, Alliance.id == Player.alliance_id) ) if search: query = query.filter(Player.name.ilike('%' + search + '%')) query = ( query .order_by(Player.trophies.desc()) .limit(100) ) results = query.all() return [ { 'name': player.name, 'lower': player.name.lower(), 'trophies': player.trophies, 'alliance': player.alliance_name, 'alliance_sprite': self.get_sprite_infos(player.sprite_id), } for player in results ] def get_ship_data(self, player_name): """Get user and ship data from API.""" ship, user, rooms, stickers, upgrades = self.summarize_ship(player_name) if user: data = { 'rooms': rooms, 'user': user, 'ship': ship, 'stickers': stickers, 'upgrades': upgrades, 'status': 'found' } data['user']['confirmed'] = True data = self._limit_ship_data(data) else: data = { 'status': 'not found' } response = { 'data': data, 'status': 'success' } return response @staticmethod def _limit_ship_data(data): """Remove ship data that shouldn't be visible to others.""" data['user']['confirmed'] = False data.pop('upgrades') data['ship'].pop('power_gen') data['ship'].pop('power_use') data['ship'].pop('hp') data['ship'].pop('shield') data['ship'].pop('immunity_date') for r in data['rooms']: r.pop('armor') r.pop('upgradable') r.pop('defense') return data def summarize_ship(self, player_name): """Get ship, user, rooms and upgrade from given player name.""" user_id = self.find_user_id(player_name) if not user_id: return None, None, None, None, None inspect_ship = self.pixel_starships_api.inspect_ship(user_id) # only seen on admin players so far if not inspect_ship: return None, None, None, None, None upgrades = [] user_data = inspect_ship['User'] more_user_data = self.pixel_starships_api.search_users(user_data['Name'], True)[0] ship_data = inspect_ship['Ship'] user = dict( id=user_data['Id'], name=user_data['Name'], sprite=self.get_sprite_infos(int(user_data['IconSpriteId'])), alliance_name=user_data.get('AllianceName'), alliance_membership=user_data.get('AllianceMembership'), alliance_join_date=more_user_data.get('AllianceJoinDate'), alliance_sprite=self.get_sprite_infos(int(user_data.get('AllianceSpriteId'))), trophies=int(user_data['Trophy']), last_date=user_data['LastAlertDate'], pvpattack_wins=int(more_user_data['PVPAttackWins']), pvpattack_losses=int(more_user_data['PVPAttackLosses']), pvpattack_draws=int(more_user_data['PVPAttackDraws']), pvpattack_ratio=self._compute_pvp_ratio(int(more_user_data['PVPAttackWins']), int(more_user_data['PVPAttackLosses']), int(more_user_data['PVPAttackDraws'])), pvpdefence_draws=int(more_user_data['PVPDefenceDraws']), pvpdefence_wins=int(more_user_data['PVPDefenceWins']), pvpdefence_losses=int(more_user_data['PVPDefenceLosses']), pvpdefence_ratio=self._compute_pvp_ratio(int(more_user_data['PVPDefenceWins']), int(more_user_data['PVPDefenceLosses']), int(more_user_data['PVPDefenceDraws'])), highest_trophy=int(more_user_data['HighestTrophy']), crew_donated=int(more_user_data['CrewDonated']), crew_received=int(more_user_data['CrewReceived']), creation_date=more_user_data['CreationDate'], race=self.RACES.get(int(ship_data['OriginalRaceId']), 'Unknown'), last_login_date=more_user_data['LastLoginDate'], ) ship_id = int(ship_data['ShipDesignId']) immunity_date = ship_data['ImmunityDate'] rooms = [] for room_data in ship_data['Rooms']: room = dict( self.interiorize(int(room_data['RoomDesignId']), ship_id), design_id=int(room_data['RoomDesignId']), id=int(room_data['RoomId']), row=int(room_data['Row']), column=int(room_data['Column']), construction=bool(room_data['ConstructionStartDate']), upgradable=self.is_room_upgradeable(int(room_data['RoomDesignId']), ship_id), ) room['exterior_sprite'] = self.get_exterior_sprite(int(room_data['RoomDesignId']), ship_id) if room['upgradable']: upgrade_room = self.get_upgrade_room(room['design_id']) if upgrade_room: cost = upgrade_room['upgrade_cost'] upgrades.append( dict( description=room['name'], amount=cost, currency=upgrade_room['upgrade_currency'], seconds=upgrade_room['upgrade_seconds']) ) rooms.append(room) ship = dict( self.ships[ship_id], power_use=sum([room['power_use'] for room in rooms]), power_gen=sum([room['power_gen'] for room in rooms]), shield=sum([room['capacity'] for room in rooms if room['type'] == 'Shield']), immunity_date=immunity_date, hue=ship_data['HueValue'], saturation=ship_data['SaturationValue'], brightness=ship_data['BrightnessValue'], ) stickers = self._parse_ship_stickers(ship_data) layout = self.generate_layout(rooms, ship) self.compute_total_armor_effects(rooms, layout) return ship, user, rooms, stickers, sorted(upgrades, key=itemgetter('amount')) @staticmethod def get_tournament_infos(): utc_now = datetime.datetime.utcnow() first_day_next_month = (utc_now.date().replace(day=1) + datetime.timedelta(days=32)).replace(day=1) tournament_start = first_day_next_month - datetime.timedelta(days=7) tournament_start_time = datetime.datetime(tournament_start.year, tournament_start.month, tournament_start.day) tournament_left_delta = tournament_start_time - utc_now tournament_left_seconds = tournament_left_delta.days * 24 * 3600 + tournament_left_delta.seconds tournament_left_minutes, tournament_left_seconds = divmod(tournament_left_seconds, 60) tournament_left_hours, tournament_left_minutes = divmod(tournament_left_minutes, 60) tournament_left_days, tournament_left_hours = divmod(tournament_left_hours, 24) tournament_left_weeks, tournament_left_days = divmod(tournament_left_days, 7) tournament_left_formatted = '' if tournament_left_weeks > 0: tournament_left_formatted += '{}w'.format(tournament_left_weeks) if tournament_left_days > 0: tournament_left_formatted += ' {}d'.format(tournament_left_days) if tournament_left_hours > 0: tournament_left_formatted += ' {}h'.format(tournament_left_hours) if tournament_left_minutes > 0: tournament_left_formatted += ' {}m'.format(tournament_left_minutes) infos = { 'start': tournament_start, 'end': first_day_next_month, 'left': tournament_left_formatted.strip(), 'started': tournament_left_delta.total_seconds() < 0 } return infos def _parse_ship_stickers(self, ship_data): stickers_string = ship_data['StickerString'] if not stickers_string: return None stickers = [] for sticker_string in stickers_string.split('|'): item_id = int(sticker_string.split('@')[0]) item = self.items[item_id] coords = sticker_string.split('@')[1].split('-') sticker = { 'sprite': item['logo_sprite'], 'x': coords[0], 'y': coords[1], 'size': coords[2], } stickers.append(sticker) return stickers def _format_daily_sale_options(self, sale_item_mask): """"From flag determine Sale options.""" result = [] options = self.pixel_starships_api.parse_sale_item_mask(sale_item_mask) for option in options: name = self.IAP_NAMES[option] result.append({'name': name, 'value': option}) return result def get_researches_and_ship_min_level(self): """Retrieve research and min ship level of the needed lab.""" researches = self.researches # get lab room and its min ship level for research in researches.values(): # TODO: don't use the name but the lab level lab_name = 'Laboratory Lv{}'.format(research['lab_level']) if lab_name in self.rooms_by_name: room = self.rooms_by_name[lab_name] research['min_ship_level'] = room['min_ship_level'] return researches @staticmethod def _compute_pvp_ratio(wins, losses, draws): """Compute PVP ratio, same formula as Dolores Bot.""" ratio = 0.0 battles = wins + losses + draws if battles > 0: ratio = (wins + .5 * draws) / battles ratio *= 100 return round(ratio, 2) def _parse_module_extra_enhancement(self, item): """Parse module extra enhancement from a given item.""" enhancement = self.MODULE_ENHANCEMENT_MAP.get(item['ModuleType'], None) disp_enhancement = self.ENHANCE_MAP.get(enhancement, enhancement) short_disp_enhancement = self.SHORT_ENHANCE_MAP.get(enhancement, enhancement), bonus = 0 if float(item['ModuleArgument']) != 0: bonus = float(item['ModuleArgument']) / self.MODULE_BONUS_RATIO_MAP.get(item['ModuleType'], 1) return { 'enhancement': enhancement, 'disp_enhancement': disp_enhancement, 'short_disp_enhancement': short_disp_enhancement, 'bonus': bonus } def get_item_upgrades(self, item_id): upgrades = [] for current_item_id in self.items.keys(): item = self.items[current_item_id] if not item['recipe']: continue for recipe_item in item['recipe']: if recipe_item['id'] == item_id: upgrades.append(Pixyship._create_light_item(item)) return upgrades
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "yolo4keras", version = "0.1.0", url = "https://github.com/Kajiyu/yolo4keras", description = "Yolo implementation for Keras", author = "Kaji", license = 'MIT', classifiers = [ 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], install_requires = [ 'numpy', 'tensorflow', 'keras', ], keywords = 'object-detecting', packages = find_packages(), packages = ['yolo4keras'], )
# -*- coding: utf-8 -*- # 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, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. TRAITS = [ # traits corresponding to the allowed values of "hw_video_model" # image metadata property # https://github.com/openstack/nova/blob/1f74441/nova/objects/fields.py#L501-L509 'MODEL_BOCHS', 'MODEL_CIRRUS', 'MODEL_GOP', 'MODEL_NONE', 'MODEL_QXL', 'MODEL_VGA', 'MODEL_VIRTIO', 'MODEL_VMVGA', 'MODEL_XEN', ]
bl_info = { "name": "Unitize Mesh", "author": "Dennis", "description": "Scales a mesh's geometry such that it fits in a unit cube around the origin.", "blender": (2, 81, 0), "category": "Object", } import bpy import math class Unitize(bpy.types.Operator): """Scales a mesh's geometry such that it fits in a unit cube around the origin.""" bl_idname = 'object.unitize' bl_label = "Unitize Mesh" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): if len( context.selected_objects ) != 1: self.report({'WARNING'}, "Select exactly one object") return {'CANCELLED'} else: obj = context.selected_objects[0] # Phase 1 # # Find the current bounds of the mesh minX = math.inf minY = math.inf minZ = math.inf maxX = -math.inf maxY = -math.inf maxZ = -math.inf for v in obj.data.vertices: minX = min( minX, v.co.x ) minY = min( minY, v.co.y ) minZ = min( minZ, v.co.z ) maxX = max( maxX, v.co.x ) maxY = max( maxY, v.co.y ) maxZ = max( maxZ, v.co.z ) offX = ( maxX + minX ) / 2 offY = ( maxY + minY ) / 2 offZ = ( maxZ + minZ ) / 2 sizeX = maxX - minX sizeY = maxY - minY sizeZ = maxZ - minZ size = max( sizeX, sizeY, sizeZ ) # Phase 2 # # Transform all vertices to make them fit in the unit cube around # the origin: [-.5,.5]x[-.5,.5]x[-.5,.5] for v in obj.data.vertices: v.co.x = ( v.co.x - offX ) / size v.co.y = ( v.co.y - offY ) / size v.co.z = ( v.co.z - offZ ) / size return {'FINISHED'} def register(): bpy.utils.register_class(Unitize) def unregister(): bpy.utils.unregister_class(Unitize) if __name__ == '__main__': register()
# -*- encoding: utf-8 -*- # # Copyright © 2014-2015 eNovance # # 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, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from collections import defaultdict import contextlib import datetime import uuid from oslo_config import cfg from oslo_log import log import retrying import six from six.moves.urllib.parse import quote try: from swiftclient import client as swclient from swiftclient import utils as swift_utils except ImportError: swclient = None from gnocchi import storage from gnocchi.storage import _carbonara LOG = log.getLogger(__name__) OPTS = [ cfg.StrOpt('swift_auth_version', default='1', help='Swift authentication version to user.'), cfg.StrOpt('swift_preauthurl', help='Swift pre-auth URL.'), cfg.StrOpt('swift_authurl', default="http://localhost:8080/auth/v1.0", help='Swift auth URL.'), cfg.StrOpt('swift_preauthtoken', secret=True, help='Swift token to user to authenticate.'), cfg.StrOpt('swift_user', default="admin:admin", help='Swift user.'), cfg.StrOpt('swift_key', secret=True, default="admin", help='Swift key/password.'), cfg.StrOpt('swift_tenant_name', help='Swift tenant name, only used in v2 auth.'), cfg.StrOpt('swift_container_prefix', default='gnocchi', help='Prefix to namespace metric containers.'), cfg.IntOpt('swift_timeout', min=0, default=300, help='Connection timeout in seconds.'), ] def retry_if_result_empty(result): return len(result) == 0 class SwiftStorage(_carbonara.CarbonaraBasedStorage): POST_HEADERS = {'Accept': 'application/json', 'Content-Type': 'text/plain'} def __init__(self, conf): super(SwiftStorage, self).__init__(conf) if swclient is None: raise RuntimeError("python-swiftclient unavailable") self.swift = swclient.Connection( auth_version=conf.swift_auth_version, authurl=conf.swift_authurl, preauthtoken=conf.swift_preauthtoken, user=conf.swift_user, key=conf.swift_key, tenant_name=conf.swift_tenant_name, timeout=conf.swift_timeout, retries=0) self._container_prefix = conf.swift_container_prefix self.swift.put_container(self.MEASURE_PREFIX) def _container_name(self, metric): return '%s.%s' % (self._container_prefix, str(metric.id)) @staticmethod def _object_name(split_key, aggregation, granularity): return '%s_%s_%s' % (split_key, aggregation, granularity) def _create_metric(self, metric): # TODO(jd) A container per user in their account? resp = {} self.swift.put_container(self._container_name(metric), response_dict=resp) # put_container() should return 201 Created; if it returns 204, that # means the metric was already created! if resp['status'] == 204: raise storage.MetricAlreadyExists(metric) def _store_measures(self, metric, data): now = datetime.datetime.utcnow().strftime("_%Y%m%d_%H:%M:%S") self.swift.put_object( self.MEASURE_PREFIX, six.text_type(metric.id) + "/" + six.text_type(uuid.uuid4()) + now, data) def _build_report(self, details): headers, files = self.swift.get_container(self.MEASURE_PREFIX, delimiter='/', full_listing=True) metrics = len(files) measures = int(headers.get('x-container-object-count')) metric_details = defaultdict(int) if details: headers, files = self.swift.get_container(self.MEASURE_PREFIX, full_listing=True) for f in files: metric = f['name'].split('/', 1)[0] metric_details[metric] += 1 return metrics, measures, metric_details if details else None def _list_metric_with_measures_to_process(self, block_size, full=False): limit = None if not full: limit = block_size * (self.partition + 1) headers, files = self.swift.get_container(self.MEASURE_PREFIX, delimiter='/', full_listing=full, limit=limit) if not full: files = files[block_size * self.partition:] return set(f['subdir'][:-1] for f in files if 'subdir' in f) def _list_measure_files_for_metric_id(self, metric_id): headers, files = self.swift.get_container( self.MEASURE_PREFIX, path=six.text_type(metric_id), full_listing=True) return files def _pending_measures_to_process_count(self, metric_id): return len(self._list_measure_files_for_metric_id(metric_id)) def _bulk_delete(self, container, objects): objects = [quote(('/%s/%s' % (container, obj['name'])).encode('utf-8')) for obj in objects] headers, body = self.swift.post_account( headers=self.POST_HEADERS, query_string='bulk-delete', data=b''.join(obj.encode('utf-8') + b'\n' for obj in objects)) resp = swift_utils.parse_api_response(headers, body) LOG.debug('# of objects deleted: %s, # of objects skipped: %s', resp['Number Deleted'], resp['Number Not Found']) def _delete_unprocessed_measures_for_metric_id(self, metric_id): files = self._list_measure_files_for_metric_id(metric_id) self._bulk_delete(self.MEASURE_PREFIX, files) @contextlib.contextmanager def _process_measure_for_metric(self, metric): files = self._list_measure_files_for_metric_id(metric.id) measures = [] for f in files: headers, data = self.swift.get_object( self.MEASURE_PREFIX, f['name']) measures.extend(self._unserialize_measures(data)) yield measures # Now clean objects self._bulk_delete(self.MEASURE_PREFIX, files) def _store_metric_measures(self, metric, timestamp_key, aggregation, granularity, data): self.swift.put_object( self._container_name(metric), self._object_name(timestamp_key, aggregation, granularity), data) def _delete_metric_measures(self, metric, timestamp_key, aggregation, granularity): self.swift.delete_object( self._container_name(metric), self._object_name(timestamp_key, aggregation, granularity)) def _delete_metric(self, metric): self._delete_unaggregated_timeserie(metric) container = self._container_name(metric) try: headers, files = self.swift.get_container( container, full_listing=True) except swclient.ClientException as e: if e.http_status != 404: # Maybe it never has been created (no measure) raise else: self._bulk_delete(container, files) try: self.swift.delete_container(container) except swclient.ClientException as e: if e.http_status != 404: # Deleted in the meantime? Whatever. raise @retrying.retry(stop_max_attempt_number=4, wait_fixed=500, retry_on_result=retry_if_result_empty) def _get_measures(self, metric, timestamp_key, aggregation, granularity): try: headers, contents = self.swift.get_object( self._container_name(metric), self._object_name( timestamp_key, aggregation, granularity)) except swclient.ClientException as e: if e.http_status == 404: try: self.swift.head_container(self._container_name(metric)) except swclient.ClientException as e: if e.http_status == 404: raise storage.MetricDoesNotExist(metric) raise raise storage.AggregationDoesNotExist(metric, aggregation) raise return contents def _list_split_keys_for_metric(self, metric, aggregation, granularity): container = self._container_name(metric) try: headers, files = self.swift.get_container( container, full_listing=True) except swclient.ClientException as e: if e.http_status == 404: raise storage.MetricDoesNotExist(metric) raise keys = [] for f in files: try: key, agg, g = f['name'].split('_', 2) except ValueError: # Might be "none", or any other file. Be resilient. continue if aggregation == agg and granularity == float(g): keys.append(key) return keys @retrying.retry(stop_max_attempt_number=4, wait_fixed=500, retry_on_result=retry_if_result_empty) def _get_unaggregated_timeserie(self, metric): try: headers, contents = self.swift.get_object( self._container_name(metric), "none") except swclient.ClientException as e: if e.http_status == 404: raise storage.MetricDoesNotExist(metric) raise return contents def _store_unaggregated_timeserie(self, metric, data): self.swift.put_object(self._container_name(metric), "none", data) def _delete_unaggregated_timeserie(self, metric): try: self.swift.delete_object(self._container_name(metric), "none") except swclient.ClientException as e: if e.http_status != 404: raise # The following methods deal with Gnocchi <= 1.3 archives def _get_metric_archive(self, metric, aggregation): """Retrieve data in the place we used to store TimeSerieArchive.""" try: headers, contents = self.swift.get_object( self._container_name(metric), aggregation) except swclient.ClientException as e: if e.http_status == 404: raise storage.AggregationDoesNotExist(metric, aggregation) raise return contents def _store_metric_archive(self, metric, aggregation, data): """Stores data in the place we used to store TimeSerieArchive.""" self.swift.put_object(self._container_name(metric), aggregation, data) def _delete_metric_archives(self, metric): for aggregation in metric.archive_policy.aggregation_methods: try: self.swift.delete_object(self._container_name(metric), aggregation) except swclient.ClientException as e: if e.http_status != 404: raise
""" =================================================== Analysis Tools (:mod:`pchangetools.analysis_tools`) =================================================== .. currentmodule:: pchangetools.analysis_tools Tools for generating graphics for teaching computational thinking from ECMWF reanalysis data. Initial work by Scott Collis scollis@anl.gov .. autosummary:: :toctree: generated/ Anal_Obj """ import xarray as xr class Anal_Obj(object): """A class for manipulating reanalyses Cooldocs Attributes ---------- era_data : xarray dataset xarray data set ith the initial ERA reanalysis data_loc : string String with the location of the netcdf file for the ERA data """ def __init__(self, era_filename): self.data_loc = era_filename self.era_data = xr.open_dataset(self.data_loc)
"""BOM additional fields on station and observation Revision ID: 28a206c84987 Revises: 659f03439631 Create Date: 2020-10-09 05:12:59.186661 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "28a206c84987" down_revision = "659f03439631" branch_labels = None depends_on = None def upgrade(): op.add_column( "bom_observation", sa.Column("cloud", sa.Text(), nullable=True) ) op.add_column( "bom_observation", sa.Column("cloud_type", sa.Text(), nullable=True) ) op.add_column( "bom_observation", sa.Column("humidity", sa.Numeric(), nullable=True) ) op.add_column( "bom_observation", sa.Column("wind_gust", sa.Numeric(), nullable=True) ) op.add_column( "bom_station", sa.Column("altitude", sa.Integer(), nullable=True) ) def downgrade(): op.drop_column("bom_station", "altitude") op.drop_column("bom_observation", "wind_gust") op.drop_column("bom_observation", "humidity") op.drop_column("bom_observation", "cloud_type") op.drop_column("bom_observation", "cloud")
"""Configuration Module provides a dictionary-like with configuration settings. It also sets up the logging. * The ``LEGA_LOG`` environment variable is used to configure where the logs go. Without it, there is no logging capabilities. Its content can be a path to an ``INI`` or ``YAML`` format, or a string representing the defaults loggers (ie default, debug, syslog, ...) * The ``LEGA_CONF`` environment variable specifies the configuration settings. If not specified, this modules tries to load the default location ``/etc/ega/conf.ini`` The files must be either in ``INI`` format or in ``YAML`` format, in which case, it must end in ``.yaml`` or ``.yml``. """ from . import logging as lega_logging import logging logging.setLoggerClass(lega_logging.LEGALogger) import os import configparser import warnings import stat from logging.config import fileConfig, dictConfig from pathlib import Path import yaml from yaml import SafeLoader as sf LOG_FILE = os.getenv('LEGA_LOG', None) CONF_FILE = os.getenv('LEGA_CONF', '/etc/ega/conf.ini') LOG = logging.getLogger(__name__) sf.add_constructor('tag:yaml.org,2002:python/tuple', lambda self, node: tuple(sf.construct_sequence(self, node))) def get_from_file(filepath, mode='rb', remove_after=False): """Return file content. Raises ValueError if it errors. """ try: with open(filepath, mode) as s: return s.read() except Exception as e: # Crash if not found, or permission denied raise ValueError(f'Error loading {filepath}') from e finally: if remove_after: try: os.remove(filepath) except Exception: # Crash if not found, or permission denied LOG.warning('Could not remove %s', filepath, exc_info=True) def convert_sensitive(value): """Fetch a sensitive value from different sources. * If `value` starts with 'env://', we strip it out and the remainder acts as the name of an environment variable to read. If the environment variable does not exist, we raise a ValueError exception. * If `value` starts with 'file://', we strip it out and the remainder acts as the filepath of a file to read (in text mode). If any error occurs while read the file content, we raise a ValueError exception. * If `value` starts with 'secret://', we strip it out and the remainder acts as the filepath of a file to read (in binary mode), and we remove it after. If any error occurs while read the file content, we raise a ValueError exception. * If `value` starts with 'value://', we strip it out and the remainder acts as the value itself. It is used to enforce the value, in case its content starts with env:// or file:// (eg a file:// URL). * Otherwise, `value` is the value content itself. """ if value is None: # Not found return None # Short-circuit in case the value starts with value:// (ie, it is enforced) if value.startswith('value://'): return value[8:] if value.startswith('env://'): envvar = value[6:] LOG.debug('Loading value from env var: %s', envvar) warnings.warn( "Loading sensitive data from environment variable is not recommended " "and might be removed in future versions." " Use secret:// instead", DeprecationWarning, stacklevel=4 ) envvalue = os.getenv(envvar, None) if envvalue is None: raise ValueError(f'Environment variable {envvar} not found') return envvalue if value.startswith('file://'): path = value[7:] LOG.debug('Loading value from path: %s', path) statinfo = os.stat(path) if statinfo.st_mode & stat.S_IRGRP or statinfo.st_mode & stat.S_IROTH: warnings.warn( "Loading sensitive data from a file that is group or world readable " "is not recommended and might be removed in future versions." " Use secret:// instead", DeprecationWarning, stacklevel=4 ) return get_from_file(path, mode='rt') # str if value.startswith('secret://'): path = value[9:] LOG.debug('Loading secret from path: %s', path) return get_from_file(path, mode='rb', remove_after=True) # bytes # It's the value itself (even if it starts with postgres:// or amqp(s)://) return value class Configuration(configparser.RawConfigParser): """Configuration from a config file.""" logger = None def __init__(self): """Set up.""" # Load the configuration settings configparser.RawConfigParser.__init__(self, delimiters=('=', ':'), comment_prefixes=('#', ';'), default_section='DEFAULT', interpolation=None, converters={ 'sensitive': convert_sensitive, }) if ( not CONF_FILE # has no value or not os.path.isfile(CONF_FILE) # does not exist or not os.access(CONF_FILE, os.R_OK) # is not readable ): warnings.warn("No configuration settings found", UserWarning, stacklevel=2) else: self.read([CONF_FILE], encoding='utf-8') # Configure the logging system if not LOG_FILE: warnings.warn("No logging supplied", UserWarning, stacklevel=2) else: try: self._load_log(LOG_FILE) except Exception as e: # import traceback # traceback.print_stack() warnings.warn(f"No logging supplied: {e!r}", UserWarning, stacklevel=3) if e.__cause__: warnings.warn(f'Cause: {e.__cause__!r}', UserWarning, stacklevel=3) def __repr__(self): """Show the configuration files.""" res = f'Configuration file: {CONF_FILE}' if self.logger: res += f'\nLogging settings loaded from {self.logger}' return res def _load_log(self, filename): """Try to load `filename` as configuration file for logging.""" assert(filename) _here = Path(__file__).parent # Try first if it is a default logger _logger = _here / f'loggers/{filename}.yaml' if _logger.exists(): with open(_logger, 'r') as stream: dictConfig(yaml.load(stream, Loader=sf)) return _logger # Otherwise trying it as a path _filename = Path(filename) if not _filename.exists(): raise ValueError(f"The file '{filename}' does not exist") if _filename.suffix in ('.yaml', '.yml'): with open(_filename, 'r') as stream: dictConfig(yaml.load(stream, Loader=sf)) return filename if _filename.suffix in ('.ini', '.INI'): fileConfig(filename) return filename # Otherwise, fail raise ValueError(f"Unsupported log format for {filename}") CONF = Configuration()
#ruamel may create environment conflicts, proceed with caution: # pip install --user 'ruamel.yaml<0.16,>0.15.95' --no-deps import ruamel.yaml as yaml def load_yaml_cards(sample_cards): SampleList = None SampleDict = dict() try: import ruamel.yaml ruamel.yaml.preserve_quotes = True except: print("Cannot load ruamel package to convert yaml file. Consider installing in a virtual environment with 'pip install --user 'ruamel.yaml<0.16,>0.15.95' --no-deps'") for scard in sample_cards: with open(scard, "r") as sample: if SampleList is None: SampleList = ruamel.yaml.load(sample, Loader=ruamel.yaml.RoundTripLoader) else: SampleList.update(ruamel.yaml.load(sample, Loader=ruamel.yaml.RoundTripLoader)) for scard in sample_cards: with open(scard, "r") as sample: SampleDict[scard] = ruamel.yaml.load(sample, Loader=ruamel.yaml.RoundTripLoader) return SampleList, SampleDict inputSamplesAll, inputSampleCardDict = load_yaml_cards(["../Kai/python/samplecards/2018_NanoAODv7_additional.yaml"]) # inputSamplesAll, inputSampleCardDict = load_yaml_cards(["../Kai/python/samplecards/2017_NanoAODv7_additional.yaml"]) for inputSampleCardName, inputSampleCardYaml in inputSampleCardDict.items(): for name in inputSampleCardYaml.keys(): print("print " + name) era = inputSampleCardYaml[name].get("era", "FAILURE") for channel, code in {"2017": {"ElMu": "ElMu=(ESV_TriggerAndLeptonLogic_selection & 24576) > 0", "MuMu": "MuMu=(ESV_TriggerAndLeptonLogic_selection & 24576) == 0 && (ESV_TriggerAndLeptonLogic_selection & 6144) > 0", "ElEl": "ElEl=(ESV_TriggerAndLeptonLogic_selection & 24576) == 0 && (ESV_TriggerAndLeptonLogic_selection & 6144) == 0 && (ESV_TriggerAndLeptonLogic_selection & 512) > 0"}, "2018": {"ElMu": "ElMu=(ESV_TriggerAndLeptonLogic_selection & 20480) > 0", "MuMu": "MuMu=(ESV_TriggerAndLeptonLogic_selection & 20480) == 0 && (ESV_TriggerAndLeptonLogic_selection & 2048) > 0", "ElEl": "ElEl=(ESV_TriggerAndLeptonLogic_selection & 20480) == 0 && (ESV_TriggerAndLeptonLogic_selection & 2048) == 0 && (ESV_TriggerAndLeptonLogic_selection & 512) > 0"} }[era].items(): print("python ~/Work/CMSSW_10_2_24_patch1/src/FourTopNAOD/RDF/scripts/nanoframe.py --input", "'{}'".format(inputSampleCardYaml[name].get("source", {}).get("NANOv7_CorrNov")), "--filter", "'{}'".format(code), "--simultaneous 4 --nThreads 8 --write --prefetch", "--redir root://cms-xrd-global.cern.ch//pnfs/iihe/cms --outdir", "{}".format("/eos/user/n/nmangane/files/NANOv7_CorrNov/skims/"+era+"/"+name+"/"+channel+"/")) #Alternate redirector: root://maite.iihe.ac.be/pnfs/iihe/cms # python ~/Work/CMSSW_10_2_24_patch1/src/FourTopNAOD/RDF/scripts/nanoframe.py --input 'dbs:/ST_tW_top_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8/nmangane-NoveCampaign-31deb7c86682c648bf5094175e82e051/USER instance=prod/phys03' --filter 'ElMu>==>(ESV_TriggerAndLeptonLogic_selection & 24576) > 0' --simultaneous 4 --nThreads 8 --write --prefetch --redir root://cms-xrd-global.cern.ch//pnfs/iihe/cms --outdir /eos/user/n/nmangane/files/NANOv7_CorrNov/skims/2017/ST_tW/ElMu/ # python ~/Work/CMSSW_10_2_24_patch1/src/FourTopNAOD/RDF/scripts/nanoframe.py --input 'dbs:/ST_tW_top_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8/nmangane-NoveCampaign-31deb7c86682c648bf5094175e82e051/USER instance=prod/phys03' --filter 'MuMu>==>(ESV_TriggerAndLeptonLogic_selection & 24576) == 0 && (ESV_TriggerAndLeptonLogic_selection & 6144) > 0' --simultaneous 4 --nThreads 8 --write --prefetch --redir root://cms-xrd-global.cern.ch//pnfs/iihe/cms --outdir /eos/user/n/nmangane/files/NANOv7_CorrNov/skims/2017/ST_tW/MuMu/ # python ~/Work/CMSSW_10_2_24_patch1/src/FourTopNAOD/RDF/scripts/nanoframe.py --input 'dbs:/ST_tW_top_5f_inclusiveDecays_TuneCP5_PSweights_13TeV-powheg-pythia8/nmangane-NoveCampaign-31deb7c86682c648bf5094175e82e051/USER instance=prod/phys03' --filter 'ElEl>==>(ESV_TriggerAndLeptonLogic_selection & 24576) == 0 && (ESV_TriggerAndLeptonLogic_selection & 6144) == 0 && (ESV_TriggerAndLeptonLogic_selection & 512) > 0' --simultaneous 4 --nThreads 8 --write --prefetch --redir root://cms-xrd-global.cern.ch//pnfs/iihe/cms --outdir /eos/user/n/nmangane/files/NANOv7_CorrNov/skims/2017/ST_tW/ElEl/ # python ~/Work/CMSSW_10_2_24_patch1/src/FourTopNAOD/RDF/scripts/nanoframe.py --input 'list:/eos/home-n/nmangane/analysis/LongTermFilelists/2018__NANOv7_CorrNov__ElMu_A.txt' --filter 'ElMu>==>(ESV_TriggerAndLeptonLogic_selection & 20480) > 0' --simultaneous 4 --nThreads 8 --write --prefetch --redir root://cms-xrd-global.cern.ch//pnfs/iihe/cms --outdir /eos/user/n/nmangane/files/NANOv7_CorrNov/skims/2018/ElMu_A/ElMu/ # python ~/Work/CMSSW_10_2_24_patch1/src/FourTopNAOD/RDF/scripts/nanoframe.py --input 'list:/eos/home-n/nmangane/analysis/LongTermFilelists/2018__NANOv7_CorrNov__MuMu_A.txt' --filter 'MuMu>==>(ESV_TriggerAndLeptonLogic_selection & 20480) == 0 && (ESV_TriggerAndLeptonLogic_selection & 2048) > 0' --simultaneous 4 --nThreads 8 --write --prefetch --redir root://cms-xrd-global.cern.ch//pnfs/iihe/cms --outdir /eos/user/n/nmangane/files/NANOv7_CorrNov/skims/2018/MuMu_A/MuMu/ # python ~/Work/CMSSW_10_2_24_patch1/src/FourTopNAOD/RDF/scripts/nanoframe.py --input 'list:/eos/home-n/nmangane/analysis/LongTermFilelists/2018__NANOv7_CorrNov__ElEl_A.txt' --filter 'ElEl>==>(ESV_TriggerAndLeptonLogic_selection & 20480) == 0 && (ESV_TriggerAndLeptonLogic_selection & 2048) == 0 && (ESV_TriggerAndLeptonLogic_selection & 512) > 0' --simultaneous 4 --nThreads 8 --write --prefetch --redir root://cms-xrd-global.cern.ch//pnfs/iihe/cms --outdir /eos/user/n/nmangane/files/NANOv7_CorrNov/skims/2018/ElEl_A/ElEl/
import vtk from vtk import * import string import sys f = open(sys.argv[1],'r') outfile = sys.argv[2] l = f.readline() tokens = string.split(string.strip(l),' ') Nnodes = int(tokens[0]) Nelts = int(tokens[1]) Points = vtk.vtkPoints() print 'Reading',Nnodes,'nodes...', for i in range(Nnodes): d = string.split(string.strip(f.readline()),' ') id = Points.InsertNextPoint(float(d[0]),float(d[1]),float(d[2])) print 'Done' Triangles = vtk.vtkCellArray() Triangle = vtk.vtkTriangle() print 'Reading',Nelts,'elements...', for i in range(Nelts): d = string.split(f.readline()) Triangle.GetPointIds().SetId(0,int(d[0])-1) Triangle.GetPointIds().SetId(1,int(d[1])-1) Triangle.GetPointIds().SetId(2,int(d[2])-1) Triangles.InsertNextCell(Triangle) print 'Done' f.close() polydata = vtk.vtkPolyData() polydata.SetPoints(Points) polydata.SetPolys(Triangles) polydata.Modified() if vtk.VTK_MAJOR_VERSION <= 5: polydata.Update() writer = vtk.vtkXMLPolyDataWriter(); writer.SetFileName(outfile); if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(polydata) else: writer.SetInputData(polydata) writer.SetDataModeToBinary() writer.Write()
# -*- coding: utf-8 -*- def cypher(message): cyphered = [] for letter in message: binary = bin(ord(letter)) cyphered.append(binary) return''.join(cyphered) def decypher(message): chars = message.split('0b') chars.pop(0) decyphered = [] for char in chars: decyphered.append(chr(int('0b{}'.format(char), 2))) return''.join(decyphered) def main(): message = raw_input("ingresa el mensaje:") cyphered = cypher(message) print("cyphered message: \n{}".format(cyphered)) decyphered = decypher(cyphered) print("Decyphered message: \n{}".format(decyphered)) if __name__ == '__main__': main()
# type: ignore import pytest import datetime from sqlalchemy import create_engine from sqlalchemy.types import Integer, String, DateTime from sqlalchemy.schema import Column, ForeignKey from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy_oso import roles as oso_roles, register_models from sqlalchemy_oso.roles import enable_roles from sqlalchemy_oso.session import set_get_session from oso import Oso, Variable Base = declarative_base(name="RoleBase") class Organization(Base): __tablename__ = "organizations" id = Column(Integer, primary_key=True) name = Column(String()) base_repo_role = Column(String()) def repr(self): return {"id": self.id, "name": self.name} class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) email = Column(String()) def repr(self): return {"id": self.id, "email": self.email} class Team(Base): __tablename__ = "teams" id = Column(Integer, primary_key=True) name = Column(String(256)) # many-to-one relationship with organizations organization_id = Column(Integer, ForeignKey("organizations.id")) organization = relationship("Organization", backref="teams", lazy=True) def repr(self): return {"id": self.id, "name": self.name} class Repository(Base): __tablename__ = "repositories" id = Column(Integer, primary_key=True) name = Column(String(256)) # many-to-one relationship with organizations organization_id = Column(Integer, ForeignKey("organizations.id")) organization = relationship("Organization", backref="repositories", lazy=True) # time info created_date = Column(DateTime, default=datetime.datetime.utcnow) updated_date = Column(DateTime, default=datetime.datetime.utcnow) def repr(self): return {"id": self.id, "name": self.name} class Issue(Base): __tablename__ = "issues" id = Column(Integer, primary_key=True) name = Column(String(256)) repository_id = Column(Integer, ForeignKey("repositories.id")) repository = relationship("Repository", backref="issues", lazy=True) RepositoryRoleMixin = oso_roles.resource_role_class( Base, User, Repository, ["READ", "TRIAGE", "WRITE", "MAINTAIN", "ADMIN"], ) class RepositoryRole(Base, RepositoryRoleMixin): def repr(self): return {"id": self.id, "name": str(self.name)} # For the tests, make OrganizationRoles NOT mutually exclusive OrganizationRoleMixin = oso_roles.resource_role_class( Base, User, Organization, ["OWNER", "MEMBER", "BILLING"], mutually_exclusive=False ) class OrganizationRole(Base, OrganizationRoleMixin): def repr(self): return {"id": self.id, "name": str(self.name)} TeamRoleMixin = oso_roles.resource_role_class( Base, User, Team, ["MAINTAINER", "MEMBER"] ) class TeamRole(Base, TeamRoleMixin): def repr(self): return {"id": self.id, "name": str(self.name)} def load_fixture_data(session): john = User(email="john@beatles.com") paul = User(email="paul@beatles.com") admin = User(email="admin@admin.com") mike = User(email="mike@monsters.com") sully = User(email="sully@monsters.com") ringo = User(email="ringo@beatles.com") randall = User(email="randall@monsters.com") users = [ john, paul, admin, mike, sully, ringo, randall, ] for user in users: session.add(user) beatles = Organization(name="The Beatles", base_repo_role="READ") monsters = Organization(name="Monsters Inc.", base_repo_role="READ") organizations = [beatles, monsters] for org in organizations: session.add(org) vocalists = Team(name="Vocalists", organization=beatles) percussion = Team(name="Percussion", organization=beatles) scarers = Team(name="Scarers", organization=monsters) teams = [ vocalists, percussion, scarers, ] for team in teams: session.add(team) abby_road = Repository(name="Abbey Road", organization=beatles) paperwork = Repository(name="Paperwork", organization=monsters) repositories = [ abby_road, paperwork, ] for repo in repositories: session.add(repo) # TODO: issues roles = [ RepositoryRole(name="READ", repository=abby_road, user=john), RepositoryRole(name="READ", repository=abby_road, user=paul), RepositoryRole(name="READ", repository=paperwork, user=mike), RepositoryRole(name="READ", repository=paperwork, user=sully), OrganizationRole( name="OWNER", organization=beatles, user=john, ), OrganizationRole( name="MEMBER", organization=beatles, user=paul, ), OrganizationRole( name="MEMBER", organization=beatles, user=ringo, ), OrganizationRole( name="OWNER", organization=monsters, user=mike, ), OrganizationRole( name="MEMBER", organization=monsters, user=sully, ), OrganizationRole( name="MEMBER", organization=monsters, user=randall, ), TeamRole(name="MEMBER", team=vocalists, user=paul), TeamRole(name="MAINTAINER", team=vocalists, user=john), TeamRole(name="MAINTAINER", team=percussion, user=ringo), TeamRole(name="MEMBER", team=scarers, user=randall), TeamRole(name="MAINTAINER", team=scarers, user=sully), ] for role in roles: session.add(role) session.commit() # TEST FIXTURES @pytest.fixture def test_db_session(): engine = create_engine("sqlite://") Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() load_fixture_data(session) return session @pytest.fixture def oso_with_session(test_db_session): oso = Oso() set_get_session(oso, lambda: test_db_session) register_models(oso, Base) return oso @pytest.fixture def john(test_db_session): return test_db_session.query(User).filter_by(email="john@beatles.com").first() @pytest.fixture def paul(test_db_session): return test_db_session.query(User).filter_by(email="paul@beatles.com").first() @pytest.fixture def ringo(test_db_session): return test_db_session.query(User).filter_by(email="ringo@beatles.com").first() @pytest.fixture def abbey_road(test_db_session): return test_db_session.query(Repository).filter_by(name="Abbey Road").first() @pytest.fixture def beatles(test_db_session): return test_db_session.query(Organization).filter_by(name="The Beatles").first() def test_user_resources_relationship_fields(test_db_session): beatles = test_db_session.query(Organization).filter_by(name="The Beatles").first() users = beatles.users users.sort(key=lambda x: x.email) assert len(users) == 3 assert users[0].email == "john@beatles.com" def test_resource_users_relationship_fields(john): orgs = john.organizations assert len(orgs) == 1 assert orgs[0].name == "The Beatles" def test_get_user_resources_and_roles(test_db_session, john): # Test with ORM method roles = john.organization_roles assert len(roles) == 1 assert roles[0].name == "OWNER" assert roles[0].organization.name == "The Beatles" # Test with oso method roles = oso_roles.get_user_roles(test_db_session, john, Organization) assert len(roles) == 1 assert roles[0].name == "OWNER" assert roles[0].organization.name == "The Beatles" def test_get_user_roles_for_resource(test_db_session, john, beatles): # Test with ORM method resource_roles = ( test_db_session.query(OrganizationRole) .filter_by(user=john, organization=beatles) .all() ) assert len(resource_roles) == 1 assert resource_roles[0].name == "OWNER" # Test with oso method resource_roles = oso_roles.get_user_roles( test_db_session, john, Organization, beatles.id ) assert len(resource_roles) == 1 assert resource_roles[0].name == "OWNER" def test_get_resource_roles(test_db_session, abbey_road): # Test with ORM method user_roles = abbey_road.roles assert user_roles[0].user.email == "john@beatles.com" assert user_roles[0].name == "READ" assert user_roles[1].user.email == "paul@beatles.com" assert user_roles[0].name == "READ" # Test with oso method user_roles = oso_roles.get_resource_roles(test_db_session, abbey_road) assert user_roles[0].user.email == "john@beatles.com" assert user_roles[0].name == "READ" assert user_roles[1].user.email == "paul@beatles.com" assert user_roles[0].name == "READ" def test_get_resource_users_by_role(test_db_session, abbey_road): # Test with ORM method users = ( test_db_session.query(User) .join(RepositoryRole) .filter_by(repository=abbey_road, name="READ") .all() ) assert len(users) == 2 assert users[0].email == "john@beatles.com" assert users[1].email == "paul@beatles.com" # Test with oso method users = oso_roles.get_resource_users_by_role(test_db_session, abbey_road, "READ") assert len(users) == 2 assert users[0].email == "john@beatles.com" assert users[1].email == "paul@beatles.com" def test_add_user_role(test_db_session, abbey_road, ringo, beatles): roles = ( test_db_session.query(RepositoryRole) .filter_by(user=ringo, repository=abbey_road) .all() ) assert len(roles) == 0 # Test can't add invalid role with pytest.raises(ValueError): oso_roles.add_user_role(test_db_session, ringo, abbey_road, "FAKE", commit=True) # Test adding valid role oso_roles.add_user_role(test_db_session, ringo, abbey_road, "READ", commit=True) roles = ( test_db_session.query(RepositoryRole) .filter_by(user=ringo, repository=abbey_road) .all() ) assert len(roles) == 1 assert roles[0].name == "READ" # ensure user cannot have duplicate role with pytest.raises(Exception): oso_roles.add_user_role(test_db_session, ringo, abbey_road, "READ", commit=True) # ensure user cannot have two roles for the same resource if `mutually_exclusive=True` with pytest.raises(Exception): oso_roles.add_user_role( test_db_session, ringo, abbey_road, "WRITE", commit=True ) roles = ( test_db_session.query(OrganizationRole) .filter_by(user=ringo, organization=beatles) .order_by(OrganizationRole.name) .all() ) assert len(roles) == 1 assert roles[0].name == "MEMBER" # ensure user cannot have two roles for the same resource with pytest.raises(Exception): oso_roles.add_user_role(test_db_session, ringo, beatles, "MEMBER", commit=True) # ensure user can have two roles for the same resource if `mutually_exclusive=False` oso_roles.add_user_role(test_db_session, ringo, beatles, "BILLING") roles = ( test_db_session.query(OrganizationRole) .filter_by(user=ringo, organization=beatles) .order_by(OrganizationRole.name) .all() ) assert len(roles) == 2 assert roles[0].name == "BILLING" def test_delete_user_role(test_db_session, john, paul, abbey_road): # Test with explicit role arg roles = ( test_db_session.query(RepositoryRole) .filter_by(user=john, repository=abbey_road, name="READ") .all() ) assert len(roles) == 1 oso_roles.delete_user_role(test_db_session, john, abbey_road, "READ") roles = ( test_db_session.query(RepositoryRole) .filter_by(user=john, repository=abbey_road, name="READ") .all() ) assert len(roles) == 0 # Test with no role arg roles = ( test_db_session.query(RepositoryRole) .filter_by(user=paul, repository=abbey_road) .all() ) assert len(roles) == 1 oso_roles.delete_user_role(test_db_session, paul, abbey_road) roles = ( test_db_session.query(RepositoryRole) .filter_by(user=paul, repository=abbey_road) .all() ) assert len(roles) == 0 def test_reassign_user_role(test_db_session, john, abbey_road): roles = ( test_db_session.query(RepositoryRole) .filter_by(user=john, repository=abbey_road) .all() ) assert len(roles) == 1 assert roles[0].name == "READ" oso_roles.reassign_user_role(test_db_session, john, abbey_road, "WRITE") roles = ( test_db_session.query(RepositoryRole) .filter_by(user=john, repository=abbey_road) .all() ) assert len(roles) == 1 assert roles[0].name == "WRITE" def test_set_get_session(oso_with_session): test_str = """get_repo(name: String) if session = OsoSession.get() and repo = session.query(Repository).filter_by(name: name).first() and repo.name = name; """ oso = oso_with_session oso.load_str(test_str) results = oso.query_rule("get_repo", "Abbey Road") assert next(results) results = oso.query_rule("get_repo", "Abbey Road") assert next(results) def test_duplicate_resource_role(): with pytest.raises(ValueError): oso_roles.resource_role_class( Base, User, Repository, ["READ", "TRIAGE", "WRITE", "MAINTAIN", "ADMIN"], ) def test_enable_roles( test_db_session, oso_with_session, john, ringo, abbey_road, beatles ): oso = oso_with_session enable_roles(oso) # Get test data read_repo_role = ( test_db_session.query(RepositoryRole) .filter_by(user=john, repository=abbey_road) .first() ) org_owner_role = ( test_db_session.query(OrganizationRole) .filter_by(user=john, organization=beatles) .first() ) # test base `resource_role_applies_to` results = list( oso.query_rule( "resource_role_applies_to", abbey_road, Variable("role_resource") ) ) assert len(results) == 1 assert results[0].get("bindings").get("role_resource") == abbey_road # test custom `resource_role_applies_to` rules (for nested resources) resource_role_applies_to_str = """resource_role_applies_to(repo: Repository, parent_org) if parent_org := repo.organization and parent_org matches Organization; """ oso.load_str(resource_role_applies_to_str) results = list( oso.query_rule( "resource_role_applies_to", abbey_road, Variable("role_resource") ) ) results.sort(key=lambda x: x.get("bindings").get("role_resource").name) assert len(results) == 2 assert results[0].get("bindings").get("role_resource") == abbey_road assert results[1].get("bindings").get("role_resource") == beatles # test `user_in_role` for RepositoryRole results = list(oso.query_rule("user_in_role", john, Variable("role"), abbey_road)) assert len(results) == 1 assert results[0].get("bindings").get("role").name == "READ" # test `user_in_role` for OrganizationRole results = list(oso.query_rule("user_in_role", john, Variable("role"), beatles)) assert len(results) == 1 assert results[0].get("bindings").get("role").name == "OWNER" # test `inherits_role` and `resource_role_order` # make sure `inherits_role` returns nothing without a role order rule results = list( oso.query_rule("inherits_role", org_owner_role, Variable("inherited_role")) ) assert len(results) == 0 # test role_order rule role_order_str = 'organization_role_order(["OWNER", "MEMBER", "BILLING"]);' oso.load_str(role_order_str) results = list( oso.query_rule("inherits_role", org_owner_role, Variable("inherited_role")) ) results.sort(key=lambda x: x.get("bindings").get("inherited_role").name) assert len(results) == 2 assert results[0].get("bindings").get("inherited_role").name == "BILLING" assert results[1].get("bindings").get("inherited_role").name == "MEMBER" # make sure this query fails before any rules are added results = list(oso.query_rule("role_allow", john, "READ", abbey_road)) assert len(results) == 0 # test basic `role_allow` rule role_allow_str = ( 'role_allow(role: RepositoryRole{name: "READ"}, "READ", repo: Repository);' ) oso.load_str(role_allow_str) results = list(oso.query_rule("role_allow", read_repo_role, "READ", abbey_road)) assert len(results) == 1 # test `role_allow` rule using nested resource nested_role_allow_str = ( 'role_allow(role: OrganizationRole{name: "MEMBER"}, "READ", repo: Repository);' ) oso.load_str(nested_role_allow_str) results = list(oso.query_rule("role_allow", org_owner_role, "READ", abbey_road)) assert len(results) == 1 # test top-level `allow` results = list(oso.query_rule("allow", john, "READ", abbey_road)) assert len(results) == 2 results = list(oso.query_rule("allow", ringo, "READ", abbey_road)) assert len(results) == 1
from db import db, User def get_user_by_email(email): return User.query.filter(User.email == email).first() def get_user_by_session_token(session_token): return User.query.filter(User.session_token == session_token).first() def get_user_by_update_token(update_token): return User.query.filter(User.update_token == update_token).first() def verify_credentials(email, password): optional_user = get_user_by_email(email) if optional_user is None: return False, None return optional_user.verify_password(password), optional_user def create_user(email, password): optional_user = get_user_by_email(email) if optional_user is not None: return False, optional_user user = User( email=email, password=password ) db.session.add(user) db.session.commit() return True, user def renew_session(update_token): user = get_user_by_update_token(update_token) print(user) if user is None: raise Exception('Invalid update token') user.renew_session() db.session.commit() return user
import pandas as pd fp = 'hospital_100.csv' df = pd.read_csv(fp, index_col=False) df_clean = df.drop(columns=['Address2','Address3', 'State','HospitalType','HospitalOwner', 'EmergencyService','Condition','MeasureCode','MeasureName', 'Score','Sample','Stateavg']) modDf = df_clean.dropna() modDf.to_csv('med_demo.csv', index=False)
# models.py import datetime import traceback from flask import current_app from invenio_accounts.models import User from invenio_db import db from sqlalchemy import ARRAY from sqlalchemy.dialects.postgresql import JSONB from base32_lib import base32 from sqlalchemy.orm import relationship from sqlalchemy_utils import ChoiceType from werkzeug.utils import cached_property from oarepo_enrollments.fields import StringArrayType, StringArray from oarepo_enrollments.proxies import current_enrollments from oarepo_enrollments.signals import enrollment_linked, enrollment_failed, enrollment_successful, enrollment_revoked, \ revocation_failed, enrollment_accepted, enrollment_rejected, enrollment_duplicit_user class Enrollment(db.Model): id = db.Column(db.Integer, primary_key=True) enrollment_type = db.Column(db.String(32), nullable=False) key = db.Column(db.String(100), nullable=False, unique=True) external_key = db.Column(db.String(100)) enrolled_email = db.Column(db.String(128), nullable=False) enrolled_user_id = db.Column(db.Integer, db.ForeignKey(User.id), name="enrolled_user") enrolled_user = relationship(User, foreign_keys=[enrolled_user_id]) granting_user_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False, name="granting_user") granting_user = relationship(User, foreign_keys=[granting_user_id]) granting_email = db.Column(db.String(128)) revoker_id = db.Column(db.ForeignKey(User.id), name="revoker") revoker = relationship(User, foreign_keys=[revoker_id]) extra_data = db.Column(db.JSON().with_variant(JSONB(), dialect_name='postgresql')) PENDING = 'P' LINKED = 'L' ACCEPTED = 'A' REJECTED = 'N' SUCCESS = 'S' FAILURE = 'F' REVOKED = 'R' ENROLLMENT_STATUS_CHOICES = [ (PENDING, 'Pending'), (SUCCESS, 'Success'), (ACCEPTED, 'Accepted'), (REJECTED, 'Not accepted'), (LINKED, 'User attached'), (FAILURE, 'Failed'), (REVOKED, 'Revoked'), ] ENROLLMENT_STATUS_CHOICES_REVERSE = {v: k for k, v in ENROLLMENT_STATUS_CHOICES} state = db.Column(ChoiceType(ENROLLMENT_STATUS_CHOICES), default=PENDING, nullable=False) actions = db.Column( StringArray().with_variant( StringArrayType(256), dialect_name='sqlite') ) start_timestamp = db.Column(db.DateTime(), nullable=False) expiration_timestamp = db.Column(db.DateTime(), nullable=True) user_attached_timestamp = db.Column(db.DateTime()) accepted_timestamp = db.Column(db.DateTime()) rejected_timestamp = db.Column(db.DateTime()) finalization_timestamp = db.Column(db.DateTime()) revocation_timestamp = db.Column(db.DateTime()) failure_reason = db.Column(db.Text()) accept_url = db.Column(db.String(256)) reject_url = db.Column(db.String(256)) success_url = db.Column(db.String(256)) failure_url = db.Column(db.String(256)) parent_enrollment_id = db.Column(db.Integer, db.ForeignKey(id), nullable=True, name="parent_enrollment") parent_enrollment = relationship("Enrollment", backref='dependent_enrollments', remote_side=id) @classmethod def create(cls, enrollment_type, external_key, enrolled_email, granting_user, granting_email=None, accept_url=None, reject_url=None, success_url=None, failure_url=None, expiration_interval=None, extra_data=None, actions=None, parent_enrollment=None): if not extra_data: extra_data = {} if not granting_email: granting_email = granting_user.email if not expiration_interval: expiration_interval = current_app.config['OAREPO_ENROLLMENT_EXPIRATION'] if not current_app.config.get('TESTING', False) and enrollment_type not in current_enrollments.handlers: raise AttributeError(f'No handler defined for enrollment type {enrollment_type}') enrolled_user = User.query.filter_by(email=enrolled_email).one_or_none() e = cls() e.enrollment_type = enrollment_type e.external_key = external_key e.key = base32.generate(length=32, split_every=4) e.enrolled_email = enrolled_email e.enrolled_user = enrolled_user e.granting_user = granting_user e.granting_email = granting_email or (granting_user.email if granting_user else None) e.accept_url = accept_url e.reject_url = reject_url e.success_url = success_url e.failure_url = failure_url e.extra_data = extra_data e.external_key = external_key e.actions = actions e.start_timestamp = datetime.datetime.now() e.expiration_timestamp = e.start_timestamp + datetime.timedelta(days=expiration_interval) if enrolled_user: e.state = Enrollment.LINKED e.user_attached_timestamp = datetime.datetime.now() if parent_enrollment: e.parent_enrollment_id = parent_enrollment.id db.session.add(e) return e @cached_property def handler(self): return current_enrollments.handlers[self.enrollment_type](self) @property def expired(self): return datetime.datetime.now() > self.expiration_timestamp def check_user_allowed(self, user): if self.enrolled_user and self.enrolled_user != user: self.failure_reason = f'User {user.email} wants to enroll in ' \ f'an already assigned enrollment {self.handler.title}' db.session.add(self) enrollment_duplicit_user.send(self, enrollment=self, impostor=user) return False return True def attach_user(self, user, timestamp=None): assert self.state == Enrollment.PENDING self.state = Enrollment.LINKED self.user_attached_timestamp = timestamp or datetime.datetime.now() self.enrolled_user = user enrollment_linked.send(self, enrollment=self) db.session.add(self) self.process_dependent_enrollments() def enroll(self, user, timestamp=None): try: self.handler.enroll(user, **self.extra_data) self.state = Enrollment.SUCCESS self.enrolled_user = user self.finalization_timestamp = timestamp or datetime.datetime.now() enrollment_successful.send(self, enrollment=self) db.session.add(self) except Exception as e: self.state = Enrollment.FAILURE self.failure_reason = getattr(e, 'message', str(e)) enrollment_failed.send(self, enrollment=self, exception=e) self.finalization_timestamp = timestamp or datetime.datetime.now() db.session.add(self) raise finally: self.process_dependent_enrollments() def revoke(self, revoker, timestamp=None): if revoker and revoker.is_anonymous: revoker = None self.revoker = revoker try: self.state = Enrollment.REVOKED if self.enrolled_user: self.handler.revoke(self.enrolled_user, **self.extra_data) self.revocation_timestamp = timestamp or datetime.datetime.now() db.session.add(self) enrollment_revoked.send(self, enrollment=self) except Exception as e: self.failure_reason = getattr(e, 'message', str(e)) self.revocation_timestamp = timestamp or datetime.datetime.now() db.session.add(self) revocation_failed.send(self, enrollment=self, exception=e) raise finally: self.process_dependent_enrollments() def accept(self, timestamp=None): self.state = Enrollment.ACCEPTED self.accepted_timestamp = timestamp or datetime.datetime.now() db.session.add(self) enrollment_accepted.send(self, enrollment=self) self.process_dependent_enrollments() def reject(self, timestamp=None): self.state = Enrollment.REJECTED self.rejected_timestamp = timestamp or datetime.datetime.now() db.session.add(self) enrollment_rejected.send(self, enrollment=self) self.process_dependent_enrollments() @classmethod def list(cls, external_key=None, enrollment_type=None, state=None, actions=None): ret = None if external_key: if ret is None: ret = cls.query ret = ret.filter(cls.external_key == external_key) if enrollment_type: if ret is None: ret = cls.query ret = ret.filter(cls.enrollment_type == enrollment_type) if state: if ret is None: ret = cls.query ret = ret.filter(cls.state.in_(state)) if actions: if ret is None: ret = cls.query if isinstance(actions, (list, tuple)): for a in actions: ret = ret.filter(cls.actions.any(a)) else: ret = ret.filter(cls.actions.any(actions)) if ret is None: ret = cls.query return ret def __str__(self): ret = '' if self.state == Enrollment.PENDING: ret = 'pending' elif self.state == Enrollment.LINKED: ret = f'linked to {self.enrolled_user.email}' elif self.state == Enrollment.ACCEPTED: ret = f'accepted by {self.enrolled_user.email}' elif self.state == Enrollment.REJECTED: ret = f'rejected by {self.enrolled_user.email}' elif self.state == Enrollment.SUCCESS: ret = f'successfully assigned to {self.enrolled_user.email}' elif self.state == Enrollment.FAILURE: ret = f'failed, enrolled user {self.enrolled_user.email if self.enrolled_user else self.enrolled_email}, ' \ f'error {self.failure_reason}' elif self.state == Enrollment.REVOKED: ret = f'revoked from {self.enrolled_user.email}' if self.external_key: ret = f'external key={self.external_key}, {ret}' return f'Enrollment[key={self.key}, {ret}' def process_dependent_enrollments(self): for enrollment in self.dependent_enrollments: self.process_dependent_enrollment(enrollment) def process_dependent_enrollment(self, enrollment): if self.state == Enrollment.LINKED: enrollment.attach_user(self.enrolled_user, self.user_attached_timestamp) elif self.state == Enrollment.ACCEPTED: enrollment.accept(self.accepted_timestamp) elif self.state == Enrollment.REJECTED: enrollment.reject(self.rejected_timestamp) elif self.state == Enrollment.SUCCESS: enrollment.enroll(self.enrolled_user, self.finalization_timestamp) elif self.state == Enrollment.FAILURE: # do nothing here ... pass elif self.state == Enrollment.REVOKED: enrollment.revoke(self.revoker, self.revocation_timestamp)
# This file is part of Happypanda. # Happypanda is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # any later version. # Happypanda is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Happypanda. If not, see <http://www.gnu.org/licenses/>. """Contains constants to be used by several modules""" from __future__ import annotations import enum import os import sys from typing import Set, TYPE_CHECKING import qtawesome as qta from PyQt5.QtGui import QIcon from . import settings from .database import db_constants if TYPE_CHECKING: from . import gallerydb # Version number vs = '1.1' DEBUG = False OS_NAME = '' if sys.platform.startswith('darwin'): OS_NAME = "darwin" elif os.name == 'nt': OS_NAME = "windows" elif os.name == 'posix': OS_NAME = "linux" APP_RESTART_CODE = 0 get = settings.get posix_program_dir = os.path.dirname(os.path.realpath(__file__)) if os.name == 'posix': static_dir = os.path.join(posix_program_dir, '../res') bin_dir = os.path.join(posix_program_dir, 'bin') temp_dir = os.path.join(posix_program_dir, 'temp') else: bin_dir = os.path.join(os.getcwd(), 'bin') static_dir = os.path.join(os.getcwd(), "res") temp_dir = os.path.join('temp') # path to unrar tool binary unrar_tool_path = get('', 'Application', 'unrar tool path') # type of download needed by download manager for each site parser # NOTE define here if any new type will be supported in the future. DOWNLOAD_TYPE_ARCHIVE = 0 DOWNLOAD_TYPE_TORRENT = 1 # Note: With this type, file will be sent to torrent program DOWNLOAD_TYPE_OTHER = 2 VALID_GALLERY_CATEGORY = ( 'Doujinshi', 'Manga', 'Artist CG', 'Game CG', 'Western', 'Non-H', 'Image Set', 'Cosplay', 'Miscellaneous', 'Private' ) # default stylesheet path default_stylesheet_path = os.path.join(static_dir, "style.css") user_stylesheet_path = "" INTERNAL_LEVEL = 8 FIRST_TIME_LEVEL = get(INTERNAL_LEVEL, 'Application', 'first time level', int) UPDATE_VERSION = get('0.30', 'Application', 'version', str) FORCE_HIGH_DPI_SUPPORT = get(False, 'Advanced', 'force high dpi support', bool) # sizes MAIN_W = 1061 # main window MAIN_H = 650 # main window SIZE_FACTOR = get(10, 'Visual', 'size factor', int) GRID_SPACING = get(15, 'Visual', 'grid spacing', int) LISTBOX_H_SIZE = 190 LISTBOX_W_SIZE = 950 GRIDBOX_LBL_H = 60 THUMB_H_SIZE = 190 + SIZE_FACTOR THUMB_W_SIZE = 133 + SIZE_FACTOR THUMB_DEFAULT = (THUMB_W_SIZE, THUMB_H_SIZE) THUMB_SMALL = (140, 93) # Columns COLUMNS = tuple(range(11)) TITLE = 0 ARTIST = 1 DESCR = 2 TAGS = 3 TYPE = 4 FAV = 5 CHAPTERS = 6 LANGUAGE = 7 LINK = 8 PUB_DATE = 9 DATE_ADDED = 10 @enum.unique class ViewType(enum.IntEnum): Default = 1 Addition = 2 Duplicate = 3 @enum.unique class ProfileType(enum.Enum): Default = 1 Small = 2 # Application SYSTEM_TRAY = None NOTIF_BAR = None NOTIF_BUBBLE = None STAT_MSG_METHOD = None GENERAL_THREAD = None WHEEL_SCROLL_EFFECT = 10 DOWNLOAD_MANAGER = None # ICONS G_LISTS_ICON_WH: QIcon G_LISTS_ICON: QIcon LIST_ICON: QIcon ARTISTS_ICON: QIcon ARTIST_ICON: QIcon NSTAGS_ICON: QIcon PLUS_ICON: QIcon ARROW_RIGHT_ICON: QIcon ARROW_LEFT_ICON: QIcon GRID_ICON: QIcon GRIDL_ICON: QIcon SEARCH_ICON: QIcon CROSS_ICON: QIcon CROSS_ICON_WH: QIcon MANAGER_ICON: QIcon DOWNLOAD_ICON: QIcon RANDOM_ICON: QIcon DUPLICATE_ICON: QIcon SORT_ICON_DESC: QIcon SORT_ICON_ASC: QIcon REFRESH_ICON: QIcon STAR_ICON: QIcon CIRCLE_ICON: QIcon INBOX_ICON: QIcon SPINNER_ICON: QIcon # IMPORTANT: Neccessary because qtawesome can't function without an instanced QApplication # IMPORTANT: called after instancing qApplication in main.py def load_icons(): global G_LISTS_ICON_WH global G_LISTS_ICON global LIST_ICON global ARTISTS_ICON global ARTIST_ICON global NSTAGS_ICON global PLUS_ICON global ARROW_RIGHT_ICON global ARROW_LEFT_ICON global GRID_ICON global GRIDL_ICON global SEARCH_ICON global CROSS_ICON global CROSS_ICON_WH global MANAGER_ICON global DOWNLOAD_ICON global RANDOM_ICON global DUPLICATE_ICON global SORT_ICON_DESC global SORT_ICON_ASC global REFRESH_ICON global STAR_ICON global CIRCLE_ICON global INBOX_ICON global SPINNER_ICON G_LISTS_ICON_WH = qta.icon("fa.bars", color="white") G_LISTS_ICON = qta.icon("fa.bars", color="black") LIST_ICON = qta.icon("fa.bars", color="white") ARTISTS_ICON = qta.icon("fa.users", color="white") ARTIST_ICON = qta.icon("fa.user", color="black") NSTAGS_ICON = qta.icon("fa.sitemap", color="white") PLUS_ICON = qta.icon("fa.plus", color="white") ARROW_RIGHT_ICON = qta.icon("fa.angle-double-right", color="white") ARROW_LEFT_ICON = qta.icon("fa.angle-double-left", color="white") GRID_ICON = qta.icon("fa.th", color="white") GRIDL_ICON = qta.icon("fa.th-large", color="white") SEARCH_ICON = qta.icon("fa.search", color="white") CROSS_ICON = qta.icon("fa.times", color="black") CROSS_ICON_WH = qta.icon("fa.times", color="white") MANAGER_ICON = qta.icon("fa.tasks", color="white") DOWNLOAD_ICON = qta.icon("fa.arrow-circle-o-down", color="white") RANDOM_ICON = qta.icon("fa.random", color="white") DUPLICATE_ICON = qta.icon("fa.files-o", color="white") SORT_ICON_DESC = qta.icon("fa.sort-amount-desc", color="white") SORT_ICON_ASC = qta.icon("fa.sort-amount-asc", color="white") REFRESH_ICON = qta.icon("fa.refresh", color="black") STAR_ICON = qta.icon("fa.star", color="white") CIRCLE_ICON = qta.icon("fa.circle", color="white") INBOX_ICON = qta.icon("fa.inbox", color="white") SPINNER_ICON = qta.icon("fa.spinner", color="white") # image paths GALLERY_DEF_ICO_PATH = os.path.join(static_dir, "gallery_def_ico.ico") GALLERY_EXT_ICO_PATH = os.path.join(static_dir, "gallery_ext_ico.ico") APP_ICO_PATH = os.path.join(static_dir, "happypanda.ico") SETTINGS_PATH = os.path.join(static_dir, "settings.png") NO_IMAGE_PATH = os.path.join(static_dir, "default.jpg") # Monitored Paths OVERRIDE_MONITOR = False # set true to make watchers to ignore next item (will be set to False) LOOK_NEW_GALLERY_STARTUP = get(True, 'Application', 'look new gallery startup', bool) ENABLE_MONITOR = get(True, 'Application', 'enable monitor', bool) MONITOR_PATHS = [p for p in get([], 'Application', 'monitor paths', list) if os.path.exists(p)] IGNORE_PATHS = get([], 'Application', 'ignore paths', list) IGNORE_EXTS = get([], 'Application', 'ignore exts', list) SCANNING_FOR_GALLERIES = False # if a scan for new galleries is being done TEMP_PATH_IGNORE = [] # GENERAL # set to true to make a fetch instance ignore moving files (will be set to false) OVERRIDE_MOVE_IMPORTED_IN_FETCH = False MOVE_IMPORTED_GALLERIES = get(False, 'Application', 'move imported galleries', bool) IMPORTED_GALLERY_DEF_PATH = get('', 'Application', 'imported gallery def path', str) OPEN_RANDOM_GALLERY_CHAPTERS = get(False, 'Application', 'open random gallery chapters', bool) # set to true to make a fetch instance treat subfolder as galleries (will be set to false) OVERRIDE_SUBFOLDER_AS_GALLERY = False SUBFOLDER_AS_GALLERY = get(False, 'Application', 'subfolder as gallery', bool) RENAME_GALLERY_SOURCE = get(False, 'Application', 'rename gallery source', bool) EXTRACT_CHAPTER_BEFORE_OPENING = get(True, 'Application', 'extract chapter before opening', bool) OPEN_GALLERIES_SEQUENTIALLY = get(False, 'Application', 'open galleries sequentially', bool) SEND_FILES_TO_TRASH = get(True, 'Application', 'send files to trash', bool) SHOW_SIDEBAR_WIDGET = get(False, 'Application', 'show sidebar widget', bool) # ADVANCED GALLERY_DATA_FIX_REGEX = get("", 'Advanced', 'gallery data fix regex', str) GALLERY_DATA_FIX_TITLE = get(True, 'Advanced', 'gallery data fix title', bool) GALLERY_DATA_FIX_ARTIST = get(True, 'Advanced', 'gallery data fix artist', bool) GALLERY_DATA_FIX_REPLACE = get("", 'Advanced', 'gallery data fix replace', str) EXTERNAL_VIEWER_ARGS = get("{$file}", 'Advanced', 'external viewer args', str) # Import/Export EXPORT_FORMAT = get(1, 'Advanced', 'export format', int) EXPORT_PATH = '' # HASH HASH_GALLERY_PAGES = get('all', 'Advanced', 'hash gallery pages', int, str) # WEB INCLUDE_EH_EXPUNGED = get(False, 'Web', 'include eh expunged', bool) GLOBAL_EHEN_TIME = get(5, 'Web', 'global ehen time offset', int) GLOBAL_EHEN_LOCK = False DEFAULT_EHEN_URL = get('https://e-hentai.org/', 'Web', 'default ehen url', str) REPLACE_METADATA = get(False, 'Web', 'replace metadata', bool) ALWAYS_CHOOSE_FIRST_HIT = get(False, 'Web', 'always choose first hit', bool) USE_GALLERY_LINK = get(True, 'Web', 'use gallery link', bool) USE_JPN_TITLE = get(False, 'Web', 'use jpn title', bool) CONTINUE_AUTO_METADATA_FETCHER = get(True, 'Web', 'continue auto metadata fetcher', bool) HEN_DOWNLOAD_TYPE = get(DOWNLOAD_TYPE_ARCHIVE, 'Web', 'hen download type', int) DOWNLOAD_DIRECTORY = get('downloads', 'Web', 'download directory', str) TORRENT_CLIENT = get('', 'Web', 'torrent client', str) HEN_LIST = get(['chaikahen'], 'Web', 'hen list', list) DOWNLOAD_GALLERY_TO_LIB = get(False, 'Web', 'download galleries to library', bool) # External Viewer EXTERNAL_VIEWER_SUPPORT = {'honeyview': ['Honeyview.exe']} USE_EXTERNAL_VIEWER = get(False, 'Application', 'use external viewer', bool) EXTERNAL_VIEWER_PATH = os.path.normcase(get('', 'Application', 'external viewer path', str)) _REFRESH_EXTERNAL_VIEWER = False # controls THUMBNAIL_CACHE_SIZE = (1024, get(200, 'Advanced', 'cache size', int)) # 1024 is 1mib PREFETCH_ITEM_AMOUNT = get(50, 'Advanced', 'prefetch item amount', int) # amount of items to prefetch SCROLL_SPEED = get(7, 'Advanced', 'scroll speed', int) # controls how many steps it takes when scrolling # POPUP POPUP_WIDTH = get(500, 'Visual', 'popup.w', int) POPUP_HEIGHT = get(300, 'Visual', 'popup.h', int) # Gallery APPEND_TAGS_GALLERIES = get(True, 'Application', 'append tags to gallery', bool) KEEP_ADDED_GALLERIES = get(True, 'Application', 'keep added galleries', bool) GALLERY_METAFILE_KEYWORDS = ('info.json', 'info.txt') CURRENT_SORT = get('title', 'General', 'current sort') HIGH_QUALITY_THUMBS = get(False, 'Visual', 'high quality thumbs', bool) DISPLAY_RATING = get(True, 'Visual', 'display gallery rating', bool) DISPLAY_GALLERY_TYPE = get(False, 'Visual', 'display gallery type', bool) if not sys.platform.startswith( 'darwin') else False DISPLAY_GALLERY_RIBBON = get(True, 'Visual', 'display gallery ribbon', bool) GALLERY_FONT = (get('Segoe UI', 'Visual', 'gallery font family', str), get(11, 'Visual', 'gallery font size', int)) GALLERY_FONT_ELIDE = get(True, 'Visual', 'gallery font elide', bool) G_DEF_LANGUAGE = get('English', 'General', 'gallery default language', str) G_CUSTOM_LANGUAGES = get([], 'General', 'gallery custom languages', list) G_DEF_STATUS = get('Completed', 'General', 'gallery default status', str) G_DEF_TYPE = get('Doujinshi', 'General', 'gallery default type', str) G_LANGUAGES = ["English", "Japanese", "Chinese", "Other"] G_STATUS = ["Ongoing", "Completed", "Unknown"] G_TYPES = ["Manga", "Doujinshi", "Artist CG Sets", "Game CG Sets", "Western", "Image Sets", "Non-H", "Cosplay", "Other"] @enum.unique class GalleryState(enum.Enum): Default = 1 New = 2 # Colors GRID_VIEW_TITLE_COLOR = get('#ffffff', 'Visual', 'grid view title color', str) GRID_VIEW_ARTIST_COLOR = get('#e2e2e2', 'Visual', 'grid view artist color', str) GRID_VIEW_LABEL_COLOR = get('#d64933', 'Visual', 'grid view label color', str) GRID_VIEW_T_MANGA_COLOR = get('#3498db', 'Visual', 'grid view t manga color', str) GRID_VIEW_T_DOUJIN_COLOR = get('#e74c3c', 'Visual', 'grid view t doujin color', str) GRID_VIEW_T_ARTIST_CG_COLOR = get('#16a085', 'Visual', 'grid view t artist cg color', str) GRID_VIEW_T_GAME_CG_COLOR = get('#2ecc71', 'Visual', 'grid view t game cg color', str) GRID_VIEW_T_WESTERN_COLOR = get('#ecf0f1', 'Visual', 'grid view t western color', str) GRID_VIEW_T_IMAGE_COLOR = get('#f39c12', 'Visual', 'grid view t image color', str) GRID_VIEW_T_NON_H_COLOR = get('#f1c40f', 'Visual', 'grid view t non-h color', str) GRID_VIEW_T_COSPLAY_COLOR = get('#9b59b6', 'Visual', 'grid view t cosplay color', str) GRID_VIEW_T_OTHER_COLOR = get('#34495e', 'Visual', 'grid view t other color', str) # Search SEARCH_AUTOCOMPLETE = get(True, 'Application', 'search autocomplete', bool) GALLERY_SEARCH_REGEX = get(False, 'Application', 'allow search regex', bool) SEARCH_ON_ENTER = get(False, 'Application', 'search on enter', bool) GALLERY_SEARCH_STRICT = get(False, 'Application', 'gallery search strict', bool) GALLERY_SEARCH_CASE = get(False, 'Application', 'gallery search case', bool) @enum.unique class Search(enum.Enum): Strict = 1 Case = 2 Regex = 3 # Grid Tooltip GRID_TOOLTIP = get(True, 'Visual', 'grid tooltip', bool) TOOLTIP_TITLE = get(False, 'Visual', 'tooltip title', bool) TOOLTIP_AUTHOR = get(False, 'Visual', 'tooltip author', bool) TOOLTIP_CHAPTERS = get(True, 'Visual', 'tooltip chapters', bool) TOOLTIP_STATUS = get(True, 'Visual', 'tooltip status', bool) TOOLTIP_TYPE = get(True, 'Visual', 'tooltip type', bool) TOOLTIP_LANG = get(False, 'Visual', 'tooltip lang', bool) TOOLTIP_DESCR = get(False, 'Visual', 'tooltip descr', bool) TOOLTIP_TAGS = get(False, 'Visual', 'tooltip tags', bool) TOOLTIP_LAST_READ = get(True, 'Visual', 'tooltip last read', bool) TOOLTIP_TIMES_READ = get(True, 'Visual', 'tooltip times read', bool) TOOLTIP_PUB_DATE = get(False, 'Visual', 'tooltip pub date', bool) TOOLTIP_DATE_ADDED = get(True, 'Visual', 'tooltip date added', bool) GALLERY_ADDITION_DATA = [] GALLERY_DATA = [] # contains the most up to date gallery data GALLERY_LISTS: Set[gallerydb.GalleryList] = set() # contains the most up to dat gallery lists # Exceptions class MetadataFetchFail(Exception): pass class InternalPagesMismatch(Exception): pass class ChapterExists(Exception): pass class ChapterWrongParentGallery(Exception): pass class CreateArchiveFail(Exception): pass class FileNotFoundInArchive(Exception): pass class WrongURL(Exception): pass class NeedLogin(Exception): pass class WrongLogin(Exception): pass class HTMLParsing(Exception): pass class GNotAvailable(Exception): pass class TitleParsingError(Exception): pass EXTERNAL_VIEWER_INFO = ( """{$folder} = path to folder {$file} = path to first image Tip: IrfanView uses {$file} """ ) WHAT_IS_FILTER = ( """[FILTER] Filters are basically predefined gallery search terms. Every time a gallery matches the specific filter it gets automatically added to the list! Filter works the same way a gallery search does so make sure to read the guide in Settings -> About -> Search Guide. You can write any valid gallery search term. [ENFORCE] With Enforce enabled the list will only allow galleries that match the specified filter into the list. """ ) SUPPORTED_DOWNLOAD_URLS = ( """Supported URLs: - exhentai/g.e-hentai/e-hentai gallery urls, e.g.: https://e-hentai.org/g/618395/0439fa3666/ - panda.chaika.moe gallery and archive urls http://panda.chaika.moe/[0]/[1]/ where [0] is 'gallery' or 'archive' and [1] are numbers - asmhentai.com gallery urls, e.g: http://asmhentai.com/g/102845/ """ ) SUPPORTED_METADATA_URLS = ( """Supported gallery URLs: - exhentai/g.e-hentai gallery urls, e.g.: http://g.e-hentai.org/g/618395/0439fa3666/ - panda.chaika.moe gallery and archive urls http://panda.chaika.moe/[0]/[1]/ where [0] is 'gallery' or 'archive' and [1] is numbers """ ) EXHEN_COOKIE_TUTORIAL = ( """ How do I find these two values? <br \> <b>All browsers</b> <br \> 1. Navigate to e-hentai.org (needs to be logged in) or exhentai.org <br \> 2. Right click on page --> Inspect element <br \> 3. Go on 'Console' tab <br \> 4. Write : 'document.cookie' <br \> 5. A line of values should appear that correspond to active cookies <br \> 6. Look for the 'ipb_member_id' and 'ipb_pass_hash' values <br \> """ ) REGEXCHEAT = ( """ <!DOCTYPE html><html><head><meta charset="utf-8"><title>Untitled Document.md</title><style>@import 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.2.0/katex.min.css';code{color:#c7254e;background-color:#f9f2f4;border-radius:4px}code,kbd{padding:2px 4px}kbd{color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;box-shadow:none}pre{display:block;margin:0 0 10px;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}fieldset{border:0;min-width:0}legend{display:block;width:100%;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type="radio"],input[type="checkbox"]{margin:1px 0 0;line-height:normal}input[type="file"]{display:block}input[type="range"]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{padding-top:7px}output,.form-control{display:block;font-size:14px;line-height:1.4285714;color:#555}.form-control{width:100%;height:34px;padding:6px 12px;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#777;opacity:1}.form-control:-ms-input-placeholder{color:#777}.form-control::-webkit-input-placeholder{color:#777}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type="date"],input[type="time"],input[type="datetime-local"],input[type="month"]{line-height:34px;line-height:1.4285714 \0}input[type="date"].input-sm,.form-horizontal .form-group-sm input[type="date"].form-control,.input-group-sm>input[type="date"].form-control,.input-group-sm>input[type="date"].input-group-addon,.input-group-sm>.input-group-btn>input[type="date"].btn,input[type="time"].input-sm,.form-horizontal .form-group-sm input[type="time"].form-control,.input-group-sm>input[type="time"].form-control,.input-group-sm>input[type="time"].input-group-addon,.input-group-sm>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-sm,.form-horizontal .form-group-sm input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].input-group-addon,.input-group-sm>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-sm,.form-horizontal .form-group-sm input[type="month"].form-control,.input-group-sm>input[type="month"].form-control,.input-group-sm>input[type="month"].input-group-addon,.input-group-sm>.input-group-btn>input[type="month"].btn{line-height:30px}input[type="date"].input-lg,.form-horizontal .form-group-lg input[type="date"].form-control,.input-group-lg>input[type="date"].form-control,.input-group-lg>input[type="date"].input-group-addon,.input-group-lg>.input-group-btn>input[type="date"].btn,input[type="time"].input-lg,.form-horizontal .form-group-lg input[type="time"].form-control,.input-group-lg>input[type="time"].form-control,.input-group-lg>input[type="time"].input-group-addon,.input-group-lg>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-lg,.form-horizontal .form-group-lg input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].input-group-addon,.input-group-lg>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-lg,.form-horizontal .form-group-lg input[type="month"].form-control,.input-group-lg>input[type="month"].form-control,.input-group-lg>input[type="month"].input-group-addon,.input-group-lg>.input-group-btn>input[type="month"].btn{line-height:46px}.form-group{margin-bottom:15px}.radio,.checkbox{position:relative;display:block;min-height:20px;margin-top:10px;margin-bottom:10px}.radio label,.checkbox label{padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{position:absolute;margin-left:-20px;margin-top:4px \9}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="radio"].disabled,fieldset[disabled] input[type="radio"],input[type="checkbox"][disabled],input[type="checkbox"].disabled,fieldset[disabled] input[type="checkbox"],.radio-inline.disabled,fieldset[disabled] .radio-inline,.checkbox-inline.disabled,fieldset[disabled] .checkbox-inline,.radio.disabled label,fieldset[disabled] .radio label,.checkbox.disabled label,fieldset[disabled] .checkbox label{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-horizontal .form-group-lg .form-control-static.form-control,.input-group-lg>.form-control-static.form-control,.input-group-lg>.form-control-static.input-group-addon,.input-group-lg>.input-group-btn>.form-control-static.btn,.form-control-static.input-sm,.form-horizontal .form-group-sm .form-control-static.form-control,.input-group-sm>.form-control-static.form-control,.input-group-sm>.form-control-static.input-group-addon,.input-group-sm>.input-group-btn>.form-control-static.btn{padding-left:0;padding-right:0}.input-sm,.form-horizontal .form-group-sm .form-control,.input-group-sm>.form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.input-group-sm>.input-group-addon{height:30px;line-height:1.5}.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm,.form-horizontal .form-group-sm select.form-control,.input-group-sm>select.form-control,.input-group-sm>select.input-group-addon,.input-group-sm>.input-group-btn>select.btn{height:30px;line-height:30px}textarea.input-sm,.form-horizontal .form-group-sm textarea.form-control,.input-group-sm>textarea.form-control,.input-group-sm>textarea.input-group-addon,.input-group-sm>.input-group-btn>textarea.btn,select[multiple].input-sm,.form-horizontal .form-group-sm select[multiple].form-control,.input-group-sm>select[multiple].form-control,.input-group-sm>select[multiple].input-group-addon,.input-group-sm>.input-group-btn>select[multiple].btn{height:auto}.input-lg,.form-horizontal .form-group-lg .form-control,.input-group-lg>.form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.input-group-lg>.input-group-addon{height:46px;line-height:1.33}.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg,.form-horizontal .form-group-lg select.form-control,.input-group-lg>select.form-control,.input-group-lg>select.input-group-addon,.input-group-lg>.input-group-btn>select.btn{height:46px;line-height:46px}textarea.input-lg,.form-horizontal .form-group-lg textarea.form-control,.input-group-lg>textarea.form-control,.input-group-lg>textarea.input-group-addon,.input-group-lg>.input-group-btn>textarea.btn,select[multiple].input-lg,.form-horizontal .form-group-lg select[multiple].form-control,.input-group-lg>select[multiple].form-control,.input-group-lg>select[multiple].input-group-addon,.input-group-lg>.input-group-btn>select[multiple].btn{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:25px;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center}.input-lg+.form-control-feedback,.form-horizontal .form-group-lg .form-control+.form-control-feedback,.input-group-lg>.form-control+.form-control-feedback,.input-group-lg>.input-group-addon+.form-control-feedback,.input-group-lg>.input-group-btn>.btn+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback,.form-horizontal .form-group-sm .form-control+.form-control-feedback,.input-group-sm>.form-control+.form-control-feedback,.input-group-sm>.input-group-addon+.form-control-feedback,.input-group-sm>.input-group-btn>.btn+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-group:before{content:" ";display:table}.form-horizontal .form-group:after{content:" ";display:table;clear:both}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}.btn{display:inline-block;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{outline:0;background-image:none;box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{background-image:none}.btn-default.disabled,.btn-default.disabled:hover,.btn-default.disabled:focus,.btn-default.disabled:active,.btn-default.disabled.active,.btn-default[disabled],.btn-default[disabled]:hover,.btn-default[disabled]:focus,.btn-default[disabled]:active,.btn-default[disabled].active,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default:hover,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{color:#fff;background-color:#3071a9;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{background-image:none}.btn-primary.disabled,.btn-primary.disabled:hover,.btn-primary.disabled:focus,.btn-primary.disabled:active,.btn-primary.disabled.active,.btn-primary[disabled],.btn-primary[disabled]:hover,.btn-primary[disabled]:focus,.btn-primary[disabled]:active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary:hover,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{color:#fff;background-color:#449d44;border-color:#398439}.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{background-image:none}.btn-success.disabled,.btn-success.disabled:hover,.btn-success.disabled:focus,.btn-success.disabled:active,.btn-success.disabled.active,.btn-success[disabled],.btn-success[disabled]:hover,.btn-success[disabled]:focus,.btn-success[disabled]:active,.btn-success[disabled].active,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success:hover,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{background-image:none}.btn-info.disabled,.btn-info.disabled:hover,.btn-info.disabled:focus,.btn-info.disabled:active,.btn-info.disabled.active,.btn-info[disabled],.btn-info[disabled]:hover,.btn-info[disabled]:focus,.btn-info[disabled]:active,.btn-info[disabled].active,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info:hover,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{background-image:none}.btn-warning.disabled,.btn-warning.disabled:hover,.btn-warning.disabled:focus,.btn-warning.disabled:active,.btn-warning.disabled.active,.btn-warning[disabled],.btn-warning[disabled]:hover,.btn-warning[disabled]:focus,.btn-warning[disabled]:active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning:hover,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{background-image:none}.btn-danger.disabled,.btn-danger.disabled:hover,.btn-danger.disabled:focus,.btn-danger.disabled:active,.btn-danger.disabled.active,.btn-danger[disabled],.btn-danger[disabled]:hover,.btn-danger[disabled]:focus,.btn-danger[disabled]:active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger:hover,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{color:#428bca;font-weight:400;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:hover,fieldset[disabled] .btn-link:focus{color:#777;text-decoration:none}.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm{padding:5px 10px}.btn-sm,.btn-xs{font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*="col-"]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon{white-space:nowrap}.input-group-addon,.input-group-btn{width:1%;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm,.form-horizontal .form-group-sm .input-group-addon.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.input-group-addon.btn{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg,.form-horizontal .form-group-lg .input-group-addon.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.input-group-addon.btn{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{font-size:0;white-space:nowrap}.input-group-btn,.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.4285714;text-decoration:none;color:#428bca;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>li>span:hover,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:hover,.pagination>.active>a:focus,.pagination>.active>span,.pagination>.active>span:hover,.pagination>.active>span:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca;cursor:default}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.modal-open,.modal{overflow:hidden}.modal{display:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate3d(0,-25%,0);transform:translate3d(0,-25%,0);-webkit-transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.4285714px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.4285714}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{content:" ";display:table}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.clearfix:before,.clearfix:after{content:" ";display:table}.clearfix:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.hljs{display:block;overflow-x:auto;padding:.5em;background:#002b36;color:#839496;-webkit-text-size-adjust:none}.hljs-comment,.hljs-template_comment,.diff .hljs-header,.hljs-doctype,.hljs-pi,.lisp .hljs-string,.hljs-javadoc{color:#586e75}.hljs-keyword,.hljs-winutils,.method,.hljs-addition,.css .hljs-tag,.hljs-request,.hljs-status,.nginx .hljs-title{color:#859900}.hljs-number,.hljs-command,.hljs-string,.hljs-tag .hljs-value,.hljs-rules .hljs-value,.hljs-phpdoc,.hljs-dartdoc,.tex .hljs-formula,.hljs-regexp,.hljs-hexcolor,.hljs-link_url{color:#2aa198}.hljs-title,.hljs-localvars,.hljs-chunk,.hljs-decorator,.hljs-built_in,.hljs-identifier,.vhdl .hljs-literal,.hljs-id,.css .hljs-function{color:#268bd2}.hljs-attribute,.hljs-variable,.lisp .hljs-body,.smalltalk .hljs-number,.hljs-constant,.hljs-class .hljs-title,.hljs-parent,.hljs-type,.hljs-link_reference{color:#b58900}.hljs-preprocessor,.hljs-preprocessor .hljs-keyword,.hljs-pragma,.hljs-shebang,.hljs-symbol,.hljs-symbol .hljs-string,.diff .hljs-change,.hljs-special,.hljs-attr_selector,.hljs-subst,.hljs-cdata,.css .hljs-pseudo,.hljs-header{color:#cb4b16}.hljs-deletion,.hljs-important{color:#dc322f}.hljs-link_label{color:#6c71c4}.tex .hljs-formula{background:#073642}*,*:before,*:after{box-sizing:border-box}html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}images{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{box-sizing:content-box;height:0}pre{overflow:auto}code,kbd{font-size:1em}code,kbd,pre,samp{font-family:monospace,monospace}samp{font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}.debug{background-color:#ffc0cb!important}.ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ir{background-color:transparent;border:0;overflow:hidden}.ir::before{content:'';display:block;height:150%;width:0}html{font-size:.875em;background:#fafafa;color:#373D49}html,body{font-family:Georgia,Cambria,serif;height:100%}body{font-size:1rem;font-weight:400;line-height:2rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}li{-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-left:1rem}li>ul,li>ol{margin-bottom:0}p{padding-top:.66001rem;-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-top:0}p,pre{margin-bottom:1.33999rem}pre{font-size:1rem;padding:.66001rem 9.5px 9.5px;line-height:2rem;background:-webkit-linear-gradient(top,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background:linear-gradient(to bottom,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background-size:100% 4rem;border-color:#D3DAEA}blockquote{margin:0}blockquote p{font-size:1rem;margin-bottom:.33999rem;font-style:italic;padding:.66001rem 1rem 1rem;border-left:3px solid #A0AABF}th,td{padding:12px}h1,h2,h3,h4,h5,h6{font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;-webkit-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;-moz-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-style:normal;font-weight:600;margin-top:0}h1{line-height:3rem;font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h2,h3{line-height:3rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}a{cursor:pointer;color:#35D7BB;text-decoration:none}a:hover,a:focus{border-bottom-color:#35D7BB;color:#dff9f4}img{height:auto;max-width:100%}.g{display:block}.g:after{clear:both;content:'';display:table}.g-b{float:left;margin:0;width:100%}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--center{display:block;float:none;margin:0 auto}.g-b--right{float:right}.g-b--1of1{width:100%}.g-b--1of2,.g-b--2of4,.g-b--3of6,.g-b--4of8,.g-b--5of10,.g-b--6of12{width:50%}.g-b--1of3,.g-b--2of6,.g-b--4of12{width:33.333%}.g-b--2of3,.g-b--4of6,.g-b--8of12{width:66.666%}.g-b--1of4,.g-b--2of8,.g-b--3of12{width:25%}.g-b--3of4,.g-b--6of8,.g-b--9of12{width:75%}.g-b--1of5,.g-b--2of10{width:20%}.g-b--2of5,.g-b--4of10{width:40%}.g-b--3of5,.g-b--6of10{width:60%}.g-b--4of5,.g-b--8of10{width:80%}.g-b--1of6,.g-b--2of12{width:16.666%}.g-b--5of6,.g-b--10of12{width:83.333%}.g-b--1of8{width:12.5%}.g-b--3of8{width:37.5%}.g-b--5of8{width:62.5%}.g-b--7of8{width:87.5%}.g-b--1of10{width:10%}.g-b--3of10{width:30%}.g-b--7of10{width:70%}.g-b--9of10{width:90%}.g-b--1of12{width:8.333%}.g-b--5of12{width:41.666%}.g-b--7of12{width:58.333%}.g-b--11of12{width:91.666%}.g-b--push--1of1{margin-left:100%}.g-b--push--1of2,.g-b--push--2of4,.g-b--push--3of6,.g-b--push--4of8,.g-b--push--5of10,.g-b--push--6of12{margin-left:50%}.g-b--push--1of3,.g-b--push--2of6,.g-b--push--4of12{margin-left:33.333%}.g-b--push--2of3,.g-b--push--4of6,.g-b--push--8of12{margin-left:66.666%}.g-b--push--1of4,.g-b--push--2of8,.g-b--push--3of12{margin-left:25%}.g-b--push--3of4,.g-b--push--6of8,.g-b--push--9of12{margin-left:75%}.g-b--push--1of5,.g-b--push--2of10{margin-left:20%}.g-b--push--2of5,.g-b--push--4of10{margin-left:40%}.g-b--push--3of5,.g-b--push--6of10{margin-left:60%}.g-b--push--4of5,.g-b--push--8of10{margin-left:80%}.g-b--push--1of6,.g-b--push--2of12{margin-left:16.666%}.g-b--push--5of6,.g-b--push--10of12{margin-left:83.333%}.g-b--push--1of8{margin-left:12.5%}.g-b--push--3of8{margin-left:37.5%}.g-b--push--5of8{margin-left:62.5%}.g-b--push--7of8{margin-left:87.5%}.g-b--push--1of10{margin-left:10%}.g-b--push--3of10{margin-left:30%}.g-b--push--7of10{margin-left:70%}.g-b--push--9of10{margin-left:90%}.g-b--push--1of12{margin-left:8.333%}.g-b--push--5of12{margin-left:41.666%}.g-b--push--7of12{margin-left:58.333%}.g-b--push--11of12{margin-left:91.666%}.g-b--pull--1of1{margin-right:100%}.g-b--pull--1of2,.g-b--pull--2of4,.g-b--pull--3of6,.g-b--pull--4of8,.g-b--pull--5of10,.g-b--pull--6of12{margin-right:50%}.g-b--pull--1of3,.g-b--pull--2of6,.g-b--pull--4of12{margin-right:33.333%}.g-b--pull--2of3,.g-b--pull--4of6,.g-b--pull--8of12{margin-right:66.666%}.g-b--pull--1of4,.g-b--pull--2of8,.g-b--pull--3of12{margin-right:25%}.g-b--pull--3of4,.g-b--pull--6of8,.g-b--pull--9of12{margin-right:75%}.g-b--pull--1of5,.g-b--pull--2of10{margin-right:20%}.g-b--pull--2of5,.g-b--pull--4of10{margin-right:40%}.g-b--pull--3of5,.g-b--pull--6of10{margin-right:60%}.g-b--pull--4of5,.g-b--pull--8of10{margin-right:80%}.g-b--pull--1of6,.g-b--pull--2of12{margin-right:16.666%}.g-b--pull--5of6,.g-b--pull--10of12{margin-right:83.333%}.g-b--pull--1of8{margin-right:12.5%}.g-b--pull--3of8{margin-right:37.5%}.g-b--pull--5of8{margin-right:62.5%}.g-b--pull--7of8{margin-right:87.5%}.g-b--pull--1of10{margin-right:10%}.g-b--pull--3of10{margin-right:30%}.g-b--pull--7of10{margin-right:70%}.g-b--pull--9of10{margin-right:90%}.g-b--pull--1of12{margin-right:8.333%}.g-b--pull--5of12{margin-right:41.666%}.g-b--pull--7of12{margin-right:58.333%}.g-b--pull--11of12{margin-right:91.666%}.splashscreen{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#373D49;z-index:22}.splashscreen-dillinger{width:260px;height:auto;display:block;margin:0 auto;padding-bottom:3rem}.splashscreen p{font-size:1.25rem;padding-top:.56251rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;text-align:center;max-width:500px;margin:0 auto;color:#FFF}.sp-center{position:relative;-webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%);top:50%}.open-menu>.wrapper{overflow-x:hidden}.page{margin:0 auto;position:relative;top:0;left:0;width:100%;height:100%;z-index:2;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;background-color:#fff;padding-top:51px;will-change:left}.open-menu .page{left:270px}.title{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;padding-left:16px;padding-right:16px;margin-top:1rem}.split-preview .title{padding-left:0}.title-document{line-height:1rem;font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem;font-weight:400;font-family:"Ubuntu Mono",Monaco;color:#373D49;padding-left:16px;padding-right:16px;width:80%;min-width:300px;outline:0;border:none}.icon{display:block;margin:0 auto;width:36px;height:36px;border-radius:3px;text-align:center}.icon svg{display:inline-block;margin-left:auto;margin-right:auto}.icon-preview{background-color:#373D49;line-height:40px}.icon-preview svg{width:19px;height:12px}.icon-settings{background-color:#373D49;line-height:44px}.icon-settings svg{width:18px;height:18px}.icon-link{width:16px;height:16px;line-height:1;margin-right:24px;text-align:right}.navbar{background-color:#373D49;height:51px;width:100%;position:fixed;top:0;left:0;z-index:6;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;will-change:left}.navbar:after{content:"";display:table;clear:both}.open-menu .navbar{left:270px}.navbar-brand{float:left;margin:0 0 0 24px;padding:0;line-height:42px}.navbar-brand svg{width:85px;height:11px}.nav-left{float:left}.nav-right{float:right}.nav-sidebar{width:100%}.menu{list-style:none;margin:0;padding:0}.menu a{border:0;color:#A0AABF;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;outline:none;text-transform:uppercase}.menu a:hover{color:#35D7BB}.menu .menu-item{border:0;display:none;float:left;margin:0;position:relative}.menu .menu-item>a{display:block;font-size:12px;height:51px;letter-spacing:1px;line-height:51px;padding:0 24px}.menu .menu-item--settings,.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar,.menu .menu-item--link-unlink.in-sidebar,.menu .menu-item--documents.in-sidebar{display:block}.menu .menu-item--documents{padding-bottom:1rem}.menu .menu-item.open>a{background-color:#1D212A}.menu .menu-item-icon>a{height:auto;padding:0}.menu .menu-item-icon:hover>a{background-color:transparent}.menu .menu-link.open i{background-color:#1D212A}.menu .menu-link.open g{fill:#35D7BB}.menu .menu-link-preview,.menu .menu-link-settings{margin-top:8px;width:51px}.menu-sidebar{width:100%}.menu-sidebar .menu-item{float:none;margin-bottom:1px;width:100%}.menu-sidebar .menu-item.open>a{background-color:#373D49}.menu-sidebar .open .caret{-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.menu-sidebar>.menu-item:hover .dropdown a,.menu-sidebar>.menu-item:hover .settings a{background-color:transparent}.menu-sidebar .menu-link{background-color:#373D49;font-weight:600}.menu-sidebar .menu-link:after{content:"";display:table;clear:both}.menu-sidebar .menu-link>span{float:left}.menu-sidebar .menu-link>.caret{float:right;text-align:right;top:22px}.menu-sidebar .dropdown,.menu-sidebar .settings{background-color:transparent;position:static;width:100%}.dropdown{position:absolute;right:0;top:51px;width:188px}.dropdown,.settings{display:none;background-color:#1D212A}.dropdown{padding:0}.dropdown,.settings,.sidebar-list{list-style:none;margin:0}.sidebar-list{padding:0}.dropdown li{margin:32px 0;padding:0 0 0 32px}.dropdown li,.settings li{line-height:1}.sidebar-list li{line-height:1;margin:32px 0;padding:0 0 0 32px}.dropdown a{color:#D0D6E2}.dropdown a,.settings a,.sidebar-list a{display:block;text-transform:none}.sidebar-list a{color:#D0D6E2}.dropdown a:after,.settings a:after,.sidebar-list a:after{content:"";display:table;clear:both}.dropdown .icon,.settings .icon,.sidebar-list .icon{float:right}.open .dropdown,.open .settings,.open .sidebar-list{display:block}.open .dropdown.collapse,.open .collapse.settings,.open .sidebar-list.collapse{display:none}.open .dropdown.collapse.in,.open .collapse.in.settings,.open .sidebar-list.collapse.in{display:block}.dropdown .unlinked .icon,.settings .unlinked .icon,.sidebar-list .unlinked .icon{opacity:.3}.dropdown.documents li,.documents.settings li,.sidebar-list.documents li{background-image:url("../img/icons/file.svg");background-position:240px center;background-repeat:no-repeat;background-size:14px 16px;padding:3px 32px}.dropdown.documents li.octocat,.documents.settings li.octocat,.sidebar-list.documents li.octocat{background-image:url("../img/icons/octocat.svg");background-position:234px center;background-size:24px 24px}.dropdown.documents li:last-child,.documents.settings li:last-child,.sidebar-list.documents li:last-child{margin-bottom:1rem}.dropdown.documents li.active a,.documents.settings li.active a,.sidebar-list.documents li.active a{color:#35D7BB}.settings{position:fixed;top:67px;right:16px;border-radius:3px;width:288px;background-color:#373D49;padding:16px;z-index:7}.show-settings .settings{display:block}.settings .has-checkbox{float:left}.settings a{font-size:1.25rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;-webkit-font-smoothing:antialiased;line-height:28px;color:#D0D6E2}.settings a:after{content:"";display:table;clear:both}.settings a:hover{color:#35D7BB}.settings li{border-bottom:1px solid #4F535B;margin:0;padding:16px 0}.settings li:last-child{border-bottom:none}.brand{border:none;display:block}.brand:hover g{fill:#35D7BB}.toggle{display:block;float:left;height:16px;padding:25px 16px 26px;width:40px}.toggle span:after,.toggle span:before{content:'';left:0;position:absolute;top:-6px}.toggle span:after{top:6px}.toggle span{display:block;position:relative}.toggle span,.toggle span:after,.toggle span:before{-webkit-backface-visibility:hidden;backface-visibility:hidden;background-color:#D3DAEA;height:2px;-webkit-transition:all .3s;transition:all .3s;width:20px}.open-menu .toggle span{background-color:transparent}.open-menu .toggle span:before{-webkit-transform:rotate(45deg)translate(3px,3px);-ms-transform:rotate(45deg)translate(3px,3px);transform:rotate(45deg)translate(3px,3px)}.open-menu .toggle span:after{-webkit-transform:rotate(-45deg)translate(5px,-6px);-ms-transform:rotate(-45deg)translate(5px,-6px);transform:rotate(-45deg)translate(5px,-6px)}.caret{display:inline-block;width:0;height:0;margin-left:6px;vertical-align:middle;position:relative;top:-1px;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.sidebar{overflow:auto;height:100%;padding-right:15px;padding-bottom:15px;width:285px}.sidebar-wrapper{-webkit-overflow-scrolling:touch;background-color:#2B2F36;left:0;height:100%;overflow-y:hidden;position:fixed;top:0;width:285px;z-index:1}.sidebar-branding{width:160px;padding:0;margin:16px auto}.header{border-bottom:1px solid #E8E8E8;position:relative}.words{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;z-index:5;position:absolute;right:16px;top:0}.words span{color:#000}.btn{text-align:center;display:inline-block;width:100%;text-transform:uppercase;font-weight:600;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;text-shadow:0 1px 0 #1b8b77;padding:16px 24px;background-color:#35D7BB;border-radius:3px;margin:0 auto 16px;line-height:1;color:#fff;-webkit-transition:all .15s linear;transition:all .15s linear;-webkit-font-smoothing:antialiased}.btn--new,.btn--save{display:block;width:238px}.btn--new:hover,.btn--new:focus,.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 3px #24b59c;text-shadow:0 1px 0 #24b59c}.btn--save{background-color:#4A5261;text-shadow:0 1px 1px #1e2127}.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 5px #08090a;text-shadow:none}.btn--delete{display:block;width:238px;background-color:transparent;font-size:12px;text-shadow:none}.btn--delete:hover,.btn--delete:focus{color:#fff;border-bottom-color:transparent;text-shadow:0 1px 0 #08090a;opacity:.8}.btn--ok,.btn--close{border-top:0;background-color:#4A5261;text-shadow:0 1px 0 #08090a;margin:0}.btn--ok:hover,.btn--ok:focus,.btn--close:hover,.btn--close:focus{color:#fff;background-color:#292d36;text-shadow:none}.overlay{position:absolute;top:0;left:0;width:100%;height:100%;background-color:rgba(55,61,73,.8);-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;-webkit-transition-timing-function:ease-out;transition-timing-function:ease-out;will-change:left,opacity,visibility;z-index:5;opacity:0;visibility:hidden}.show-settings .overlay{visibility:visible;opacity:1}.switch{float:right;line-height:1}.switch input{display:none}.switch small{display:inline-block;cursor:pointer;padding:0 24px 0 0;-webkit-transition:all ease .2s;transition:all ease .2s;background-color:#2B2F36;border-color:#2B2F36}.switch small,.switch small:before{border-radius:30px;box-shadow:inset 0 0 2px 0 #14171F}.switch small:before{display:block;content:'';width:28px;height:28px;background:#fff}.switch.checked small{padding-right:0;padding-left:24px;background-color:#35D7BB;box-shadow:none}.modal--dillinger.about .modal-dialog{font-size:1.25rem;max-width:500px}.modal--dillinger .modal-dialog{max-width:600px;width:auto;margin:5rem auto}.modal--dillinger .modal-content{background:#373D49;border-radius:3px;box-shadow:0 2px 5px 0 #2C3B59;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;padding:2rem}.modal--dillinger ul{list-style-type:disc;margin:1rem 0;padding:0 0 0 1rem}.modal--dillinger li{padding:0;margin:0}.modal--dillinger .modal-header{border:0;padding:0}.modal--dillinger .modal-body{padding:0}.modal--dillinger .modal-footer{border:0;padding:0}.modal--dillinger .close{color:#fff;opacity:1}.modal-backdrop{background-color:#373D49}.pagination--dillinger{padding:0!important;margin:1.5rem 0!important;-webkit-box-pack:justify;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;-webkit-align-content:stretch;-ms-flex-line-pack:stretch;align-content:stretch}.pagination--dillinger,.pagination--dillinger li{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex}.pagination--dillinger li{-webkit-box-flex:1;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;text-align:center}.pagination--dillinger li:first-child>a,.pagination--dillinger li.disabled>a,.pagination--dillinger li.disabled>a:hover,.pagination--dillinger li.disabled>a:focus,.pagination--dillinger li>a{background-color:transparent;border-color:#4F535B;border-right-color:transparent}.pagination--dillinger li.active>a,.pagination--dillinger li.active>a:hover,.pagination--dillinger li.active>a:focus{border-color:#4A5261;background-color:#4A5261;color:#fff}.pagination--dillinger li>a{float:none;color:#fff;width:100%;display:block;text-align:center;margin:0;border-right-color:transparent;padding:6px}.pagination--dillinger li>a:hover,.pagination--dillinger li>a:focus{border-color:#35D7BB;background-color:#35D7BB;color:#fff}.pagination--dillinger li:last-child a{border-color:#4F535B}.pagination--dillinger li:first-child a{border-right-color:transparent}.diNotify{position:absolute;z-index:9999;left:0;right:0;top:0;margin:0 auto;max-width:400px;text-align:center;-webkit-transition:top .5s ease-in-out,opacity .5s ease-in-out;transition:top .5s ease-in-out,opacity .5s ease-in-out;visibility:hidden}.diNotify-body{-webkit-font-smoothing:antialiased;background-color:#35D7BB;background:#666E7F;border-radius:3px;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;overflow:hidden;padding:1rem 2rem .5rem;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:baseline;-webkit-align-items:baseline;-ms-flex-align:baseline;align-items:baseline;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center}.diNotify-icon{display:block;width:16px;height:16px;line-height:16px;position:relative;top:3px}.diNotify-message{padding-left:1rem}.zen-wrapper{position:fixed;top:0;left:0;right:0;bottom:0;width:100%;height:100%;z-index:10;background-color:#FFF;opacity:0;-webkit-transition:opacity .25s ease-in-out;transition:opacity .25s ease-in-out}.zen-wrapper.on{opacity:1}.enter-zen-mode{background-image:url("../img/icons/enter-zen.svg");right:.5rem;top:.5rem;display:none}.enter-zen-mode,.close-zen-mode{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;background-repeat:no-repeat;width:32px;height:32px;display:block;position:absolute}.close-zen-mode{background-image:url("../img/icons/exit-zen.svg");right:1rem;top:1rem}.zen-page{position:relative;top:0;bottom:0;z-index:11;height:100%;width:100%}#zen{font-size:1.25rem;width:300px;height:80%;margin:0 auto;position:relative;top:10%}#zen:before,#zen:after{content:"";position:absolute;height:10%;width:100%;z-index:12;pointer-events:none}.split{overflow:scroll;padding:0!important}.split-editor{padding-left:0;padding-right:0;position:relative}.show-preview .split-editor{display:none}.split-preview{background-color:#fff;display:none;top:0;position:relative;z-index:4}.show-preview .split-preview{display:block}#editor{font-size:1rem;font-family:"Ubuntu Mono",Monaco;font-weight:400;line-height:2rem;width:100%;height:100%}#editor .ace_gutter{-webkit-font-smoothing:antialiased}#preview a{color:#A0AABF;text-decoration:underline}.sr-only{visibility:hidden;text-overflow:110%;overflow:hidden;top:-100px;position:absolute}.mnone{margin:0!important}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .radio label,.form-inline .checkbox label{padding-left:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}.form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}.form-horizontal .form-group-lg .control-label{padding-top:14.3px}.form-horizontal .form-group-sm .control-label{padding-top:6px}.modal-dialog{width:600px;margin:30px auto}.modal-content{box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}@media screen and (min-width:27.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--m1of1{width:100%}.g-b--m1of2,.g-b--m2of4,.g-b--m3of6,.g-b--m4of8,.g-b--m5of10,.g-b--m6of12{width:50%}.g-b--m1of3,.g-b--m2of6,.g-b--m4of12{width:33.333%}.g-b--m2of3,.g-b--m4of6,.g-b--m8of12{width:66.666%}.g-b--m1of4,.g-b--m2of8,.g-b--m3of12{width:25%}.g-b--m3of4,.g-b--m6of8,.g-b--m9of12{width:75%}.g-b--m1of5,.g-b--m2of10{width:20%}.g-b--m2of5,.g-b--m4of10{width:40%}.g-b--m3of5,.g-b--m6of10{width:60%}.g-b--m4of5,.g-b--m8of10{width:80%}.g-b--m1of6,.g-b--m2of12{width:16.666%}.g-b--m5of6,.g-b--m10of12{width:83.333%}.g-b--m1of8{width:12.5%}.g-b--m3of8{width:37.5%}.g-b--m5of8{width:62.5%}.g-b--m7of8{width:87.5%}.g-b--m1of10{width:10%}.g-b--m3of10{width:30%}.g-b--m7of10{width:70%}.g-b--m9of10{width:90%}.g-b--m1of12{width:8.333%}.g-b--m5of12{width:41.666%}.g-b--m7of12{width:58.333%}.g-b--m11of12{width:91.666%}.g-b--push--m1of1{margin-left:100%}.g-b--push--m1of2,.g-b--push--m2of4,.g-b--push--m3of6,.g-b--push--m4of8,.g-b--push--m5of10,.g-b--push--m6of12{margin-left:50%}.g-b--push--m1of3,.g-b--push--m2of6,.g-b--push--m4of12{margin-left:33.333%}.g-b--push--m2of3,.g-b--push--m4of6,.g-b--push--m8of12{margin-left:66.666%}.g-b--push--m1of4,.g-b--push--m2of8,.g-b--push--m3of12{margin-left:25%}.g-b--push--m3of4,.g-b--push--m6of8,.g-b--push--m9of12{margin-left:75%}.g-b--push--m1of5,.g-b--push--m2of10{margin-left:20%}.g-b--push--m2of5,.g-b--push--m4of10{margin-left:40%}.g-b--push--m3of5,.g-b--push--m6of10{margin-left:60%}.g-b--push--m4of5,.g-b--push--m8of10{margin-left:80%}.g-b--push--m1of6,.g-b--push--m2of12{margin-left:16.666%}.g-b--push--m5of6,.g-b--push--m10of12{margin-left:83.333%}.g-b--push--m1of8{margin-left:12.5%}.g-b--push--m3of8{margin-left:37.5%}.g-b--push--m5of8{margin-left:62.5%}.g-b--push--m7of8{margin-left:87.5%}.g-b--push--m1of10{margin-left:10%}.g-b--push--m3of10{margin-left:30%}.g-b--push--m7of10{margin-left:70%}.g-b--push--m9of10{margin-left:90%}.g-b--push--m1of12{margin-left:8.333%}.g-b--push--m5of12{margin-left:41.666%}.g-b--push--m7of12{margin-left:58.333%}.g-b--push--m11of12{margin-left:91.666%}.g-b--pull--m1of1{margin-right:100%}.g-b--pull--m1of2,.g-b--pull--m2of4,.g-b--pull--m3of6,.g-b--pull--m4of8,.g-b--pull--m5of10,.g-b--pull--m6of12{margin-right:50%}.g-b--pull--m1of3,.g-b--pull--m2of6,.g-b--pull--m4of12{margin-right:33.333%}.g-b--pull--m2of3,.g-b--pull--m4of6,.g-b--pull--m8of12{margin-right:66.666%}.g-b--pull--m1of4,.g-b--pull--m2of8,.g-b--pull--m3of12{margin-right:25%}.g-b--pull--m3of4,.g-b--pull--m6of8,.g-b--pull--m9of12{margin-right:75%}.g-b--pull--m1of5,.g-b--pull--m2of10{margin-right:20%}.g-b--pull--m2of5,.g-b--pull--m4of10{margin-right:40%}.g-b--pull--m3of5,.g-b--pull--m6of10{margin-right:60%}.g-b--pull--m4of5,.g-b--pull--m8of10{margin-right:80%}.g-b--pull--m1of6,.g-b--pull--m2of12{margin-right:16.666%}.g-b--pull--m5of6,.g-b--pull--m10of12{margin-right:83.333%}.g-b--pull--m1of8{margin-right:12.5%}.g-b--pull--m3of8{margin-right:37.5%}.g-b--pull--m5of8{margin-right:62.5%}.g-b--pull--m7of8{margin-right:87.5%}.g-b--pull--m1of10{margin-right:10%}.g-b--pull--m3of10{margin-right:30%}.g-b--pull--m7of10{margin-right:70%}.g-b--pull--m9of10{margin-right:90%}.g-b--pull--m1of12{margin-right:8.333%}.g-b--pull--m5of12{margin-right:41.666%}.g-b--pull--m7of12{margin-right:58.333%}.g-b--pull--m11of12{margin-right:91.666%}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:400px}#editor{font-size:1rem}}@media screen and (min-width:46.25em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--t1of1{width:100%}.g-b--t1of2,.g-b--t2of4,.g-b--t3of6,.g-b--t4of8,.g-b--t5of10,.g-b--t6of12{width:50%}.g-b--t1of3,.g-b--t2of6,.g-b--t4of12{width:33.333%}.g-b--t2of3,.g-b--t4of6,.g-b--t8of12{width:66.666%}.g-b--t1of4,.g-b--t2of8,.g-b--t3of12{width:25%}.g-b--t3of4,.g-b--t6of8,.g-b--t9of12{width:75%}.g-b--t1of5,.g-b--t2of10{width:20%}.g-b--t2of5,.g-b--t4of10{width:40%}.g-b--t3of5,.g-b--t6of10{width:60%}.g-b--t4of5,.g-b--t8of10{width:80%}.g-b--t1of6,.g-b--t2of12{width:16.666%}.g-b--t5of6,.g-b--t10of12{width:83.333%}.g-b--t1of8{width:12.5%}.g-b--t3of8{width:37.5%}.g-b--t5of8{width:62.5%}.g-b--t7of8{width:87.5%}.g-b--t1of10{width:10%}.g-b--t3of10{width:30%}.g-b--t7of10{width:70%}.g-b--t9of10{width:90%}.g-b--t1of12{width:8.333%}.g-b--t5of12{width:41.666%}.g-b--t7of12{width:58.333%}.g-b--t11of12{width:91.666%}.g-b--push--t1of1{margin-left:100%}.g-b--push--t1of2,.g-b--push--t2of4,.g-b--push--t3of6,.g-b--push--t4of8,.g-b--push--t5of10,.g-b--push--t6of12{margin-left:50%}.g-b--push--t1of3,.g-b--push--t2of6,.g-b--push--t4of12{margin-left:33.333%}.g-b--push--t2of3,.g-b--push--t4of6,.g-b--push--t8of12{margin-left:66.666%}.g-b--push--t1of4,.g-b--push--t2of8,.g-b--push--t3of12{margin-left:25%}.g-b--push--t3of4,.g-b--push--t6of8,.g-b--push--t9of12{margin-left:75%}.g-b--push--t1of5,.g-b--push--t2of10{margin-left:20%}.g-b--push--t2of5,.g-b--push--t4of10{margin-left:40%}.g-b--push--t3of5,.g-b--push--t6of10{margin-left:60%}.g-b--push--t4of5,.g-b--push--t8of10{margin-left:80%}.g-b--push--t1of6,.g-b--push--t2of12{margin-left:16.666%}.g-b--push--t5of6,.g-b--push--t10of12{margin-left:83.333%}.g-b--push--t1of8{margin-left:12.5%}.g-b--push--t3of8{margin-left:37.5%}.g-b--push--t5of8{margin-left:62.5%}.g-b--push--t7of8{margin-left:87.5%}.g-b--push--t1of10{margin-left:10%}.g-b--push--t3of10{margin-left:30%}.g-b--push--t7of10{margin-left:70%}.g-b--push--t9of10{margin-left:90%}.g-b--push--t1of12{margin-left:8.333%}.g-b--push--t5of12{margin-left:41.666%}.g-b--push--t7of12{margin-left:58.333%}.g-b--push--t11of12{margin-left:91.666%}.g-b--pull--t1of1{margin-right:100%}.g-b--pull--t1of2,.g-b--pull--t2of4,.g-b--pull--t3of6,.g-b--pull--t4of8,.g-b--pull--t5of10,.g-b--pull--t6of12{margin-right:50%}.g-b--pull--t1of3,.g-b--pull--t2of6,.g-b--pull--t4of12{margin-right:33.333%}.g-b--pull--t2of3,.g-b--pull--t4of6,.g-b--pull--t8of12{margin-right:66.666%}.g-b--pull--t1of4,.g-b--pull--t2of8,.g-b--pull--t3of12{margin-right:25%}.g-b--pull--t3of4,.g-b--pull--t6of8,.g-b--pull--t9of12{margin-right:75%}.g-b--pull--t1of5,.g-b--pull--t2of10{margin-right:20%}.g-b--pull--t2of5,.g-b--pull--t4of10{margin-right:40%}.g-b--pull--t3of5,.g-b--pull--t6of10{margin-right:60%}.g-b--pull--t4of5,.g-b--pull--t8of10{margin-right:80%}.g-b--pull--t1of6,.g-b--pull--t2of12{margin-right:16.666%}.g-b--pull--t5of6,.g-b--pull--t10of12{margin-right:83.333%}.g-b--pull--t1of8{margin-right:12.5%}.g-b--pull--t3of8{margin-right:37.5%}.g-b--pull--t5of8{margin-right:62.5%}.g-b--pull--t7of8{margin-right:87.5%}.g-b--pull--t1of10{margin-right:10%}.g-b--pull--t3of10{margin-right:30%}.g-b--pull--t7of10{margin-right:70%}.g-b--pull--t9of10{margin-right:90%}.g-b--pull--t1of12{margin-right:8.333%}.g-b--pull--t5of12{margin-right:41.666%}.g-b--pull--t7of12{margin-right:58.333%}.g-b--pull--t11of12{margin-right:91.666%}.splashscreen-dillinger{width:500px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--save-to,.menu .menu-item--import-from{display:block}.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog{font-size:1.25rem}.enter-zen-mode{display:block}.close-zen-mode{right:3rem;top:3rem}#zen{font-size:1.25rem;width:500px}.split-editor{border-right:1px solid #E8E8E8;float:left;height:calc(100vh - 130px);-webkit-overflow-scrolling:touch;padding-right:16px;width:50%}.show-preview .split-editor{display:block}.split-preview{display:block;float:right;height:calc(100vh - 130px);-webkit-overflow-scrolling:touch;position:relative;top:0;width:50%}#editor{font-size:1rem}}@media screen and (min-width:62.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--d1of1{width:100%}.g-b--d1of2,.g-b--d2of4,.g-b--d3of6,.g-b--d4of8,.g-b--d5of10,.g-b--d6of12{width:50%}.g-b--d1of3,.g-b--d2of6,.g-b--d4of12{width:33.333%}.g-b--d2of3,.g-b--d4of6,.g-b--d8of12{width:66.666%}.g-b--d1of4,.g-b--d2of8,.g-b--d3of12{width:25%}.g-b--d3of4,.g-b--d6of8,.g-b--d9of12{width:75%}.g-b--d1of5,.g-b--d2of10{width:20%}.g-b--d2of5,.g-b--d4of10{width:40%}.g-b--d3of5,.g-b--d6of10{width:60%}.g-b--d4of5,.g-b--d8of10{width:80%}.g-b--d1of6,.g-b--d2of12{width:16.666%}.g-b--d5of6,.g-b--d10of12{width:83.333%}.g-b--d1of8{width:12.5%}.g-b--d3of8{width:37.5%}.g-b--d5of8{width:62.5%}.g-b--d7of8{width:87.5%}.g-b--d1of10{width:10%}.g-b--d3of10{width:30%}.g-b--d7of10{width:70%}.g-b--d9of10{width:90%}.g-b--d1of12{width:8.333%}.g-b--d5of12{width:41.666%}.g-b--d7of12{width:58.333%}.g-b--d11of12{width:91.666%}.g-b--push--d1of1{margin-left:100%}.g-b--push--d1of2,.g-b--push--d2of4,.g-b--push--d3of6,.g-b--push--d4of8,.g-b--push--d5of10,.g-b--push--d6of12{margin-left:50%}.g-b--push--d1of3,.g-b--push--d2of6,.g-b--push--d4of12{margin-left:33.333%}.g-b--push--d2of3,.g-b--push--d4of6,.g-b--push--d8of12{margin-left:66.666%}.g-b--push--d1of4,.g-b--push--d2of8,.g-b--push--d3of12{margin-left:25%}.g-b--push--d3of4,.g-b--push--d6of8,.g-b--push--d9of12{margin-left:75%}.g-b--push--d1of5,.g-b--push--d2of10{margin-left:20%}.g-b--push--d2of5,.g-b--push--d4of10{margin-left:40%}.g-b--push--d3of5,.g-b--push--d6of10{margin-left:60%}.g-b--push--d4of5,.g-b--push--d8of10{margin-left:80%}.g-b--push--d1of6,.g-b--push--d2of12{margin-left:16.666%}.g-b--push--d5of6,.g-b--push--d10of12{margin-left:83.333%}.g-b--push--d1of8{margin-left:12.5%}.g-b--push--d3of8{margin-left:37.5%}.g-b--push--d5of8{margin-left:62.5%}.g-b--push--d7of8{margin-left:87.5%}.g-b--push--d1of10{margin-left:10%}.g-b--push--d3of10{margin-left:30%}.g-b--push--d7of10{margin-left:70%}.g-b--push--d9of10{margin-left:90%}.g-b--push--d1of12{margin-left:8.333%}.g-b--push--d5of12{margin-left:41.666%}.g-b--push--d7of12{margin-left:58.333%}.g-b--push--d11of12{margin-left:91.666%}.g-b--pull--d1of1{margin-right:100%}.g-b--pull--d1of2,.g-b--pull--d2of4,.g-b--pull--d3of6,.g-b--pull--d4of8,.g-b--pull--d5of10,.g-b--pull--d6of12{margin-right:50%}.g-b--pull--d1of3,.g-b--pull--d2of6,.g-b--pull--d4of12{margin-right:33.333%}.g-b--pull--d2of3,.g-b--pull--d4of6,.g-b--pull--d8of12{margin-right:66.666%}.g-b--pull--d1of4,.g-b--pull--d2of8,.g-b--pull--d3of12{margin-right:25%}.g-b--pull--d3of4,.g-b--pull--d6of8,.g-b--pull--d9of12{margin-right:75%}.g-b--pull--d1of5,.g-b--pull--d2of10{margin-right:20%}.g-b--pull--d2of5,.g-b--pull--d4of10{margin-right:40%}.g-b--pull--d3of5,.g-b--pull--d6of10{margin-right:60%}.g-b--pull--d4of5,.g-b--pull--d8of10{margin-right:80%}.g-b--pull--d1of6,.g-b--pull--d2of12{margin-right:16.666%}.g-b--pull--d5of6,.g-b--pull--d10of12{margin-right:83.333%}.g-b--pull--d1of8{margin-right:12.5%}.g-b--pull--d3of8{margin-right:37.5%}.g-b--pull--d5of8{margin-right:62.5%}.g-b--pull--d7of8{margin-right:87.5%}.g-b--pull--d1of10{margin-right:10%}.g-b--pull--d3of10{margin-right:30%}.g-b--pull--d7of10{margin-right:70%}.g-b--pull--d9of10{margin-right:90%}.g-b--pull--d1of12{margin-right:8.333%}.g-b--pull--d5of12{margin-right:41.666%}.g-b--pull--d7of12{margin-right:58.333%}.g-b--pull--d11of12{margin-right:91.666%}.splashscreen-dillinger{width:700px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--export-as{display:block}.menu .menu-item--preview{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:700px}#editor{font-size:1rem}}@media screen and (min-width:87.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.splashscreen-dillinger{width:800px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#editor{font-size:1rem}}</style></head><body id="preview"> <h4><a id="Characters_I_1"></a>Characters I</h4> <table> <thead> <tr> <th>Expression</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>.</td> <td>Match any character except newline</td> </tr> <tr> <td>^</td> <td>Match the start of the string</td> </tr> <tr> <td>$</td> <td>Match the end of the string</td> </tr> <tr> <td>*</td> <td>Match 0 or more repetitions</td> </tr> <tr> <td>+</td> <td>Match 1 or more repetitions</td> </tr> <tr> <td>?</td> <td>Match 0 or 1 repetitions</td> </tr> </tbody> </table> <h4><a id="Special_Sequences_I_12"></a>Special Sequences I</h4> <table> <thead> <tr> <th>Expression</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>\A</td> <td>Match only at start of string</td> </tr> <tr> <td>\\b</td> <td>Match empty string, only at beginning or end of a word</td> </tr> <tr> <td>\B</td> <td>Match empty string, only when it is not at beginning or end of word</td> </tr> <tr> <td>\d</td> <td>Match digits # same as [0-9]</td> </tr> <tr> <td>\D</td> <td>Match any non digit # same as [^0-9]</td> </tr> </tbody> </table> <h4><a id="Characters_II_22"></a>Characters II</h4> <table> <thead> <tr> <th>Expression</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>*?</td> <td>Match 0 or more repetitions non-greedy</td> </tr> <tr> <td>+?</td> <td>Match 1 or more repetitions non-greedy</td> </tr> <tr> <td>??</td> <td>Match 0 or 1 repetitions non-greedy</td> </tr> <tr> <td>\</td> <td>Escape special characters</td> </tr> <tr> <td>[]</td> <td>Match a set of characters</td> </tr> <tr> <td>[a-z]</td> <td>Match any lowercase ASCII letter</td> </tr> <tr> <td>[lower-upper]</td> <td>Match a set of characters from lower to upper</td> </tr> <tr> <td>[^]</td> <td>Match characters NOT in a set</td> </tr> <tr> <td>A|B</td> <td>Match either A or B regular expressions (non-greedy)</td> </tr> </tbody> </table> <h4><a id="Special_Sequences_II_36"></a>Special Sequences II</h4> <table> <thead> <tr> <th>Expression</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>\s</td> <td>Match whitespace characters # same as [ \t\n\r\f\v]</td> </tr> <tr> <td>\S</td> <td>Match non whitespace characters #same as [^ \t\n\r\f\v]</td> </tr> <tr> <td>\w</td> <td>Match unicode word characters # same as [a-zA-Z0-9_]</td> </tr> <tr> <td>\W</td> <td>Match any character not a Unicode word character # same as [^a-zA-Z0-9_]</td> </tr> <tr> <td>\Z</td> <td>Match only at end of string</td> </tr> </tbody> </table> <h4><a id="Characters_III_46"></a>Characters III</h4> <table> <thead> <tr> <th>Expression</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>{m}</td> <td>Match exactly m copies</td> </tr> <tr> <td>{m,n}</td> <td>Match from m to n repetitions</td> </tr> <tr> <td>{,n}</td> <td>Match from 0 to n repetitions</td> </tr> <tr> <td>{m,}</td> <td>Match from m to infinite repetitions</td> </tr> <tr> <td>{m,n}?</td> <td>Match from m to n repetitions non-greedy (as few as possible)</td> </tr> </tbody> </table> <h4><a id="Groups_I_56"></a>Groups I</h4> <table> <thead> <tr> <th>Expression</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>(match)</td> <td>Use to specify a group for which match can be retrieved later</td> </tr> <tr> <td>(?:match)</td> <td>Non-capturing version parenthesis (match cannot be retrieved later)</td> </tr> <tr> <td>(?P&lt;name&gt;)</td> <td>Capture group with name “name”</td> </tr> <tr> <td>(?P=name)</td> <td>Back reference group named “name” in same pattern</td> </tr> <tr> <td>(?#comment)</td> <td>Comment</td> </tr> </tbody> </table> <h4><a id="Lookahead__Behind_I_66"></a>Lookahead / Behind I</h4> <table> <thead> <tr> <th>Expression</th> <th>Meaning</th> </tr> </thead> <tbody> <tr> <td>(?=match)</td> <td>Lookahead assertion - match if contents matches next, but don’t consume any of the string.</td> </tr> <tr> <td>(?!match)</td> <td>Negative lookahead assertion - match if contents do not match next</td> </tr> <tr> <td>(?&lt;=match)</td> <td>Positive lookbehind assertion - match if current position in string is preceded by match</td> </tr> <tr> <td>(?&lt;!match)</td> <td>Negative lookbehind assertion - match if current position is not preceded by match</td> </tr> <tr> <td>(?(id/name)yes|no)</td> <td>Match “yes” pattern if id or name exists, otherwise match “no” pattern</td> </tr> </tbody> </table> </body></html> """ ) ABOUT = ( """ <!DOCTYPE html><html><head></head><body> <p><strong>Creator</strong>: <a href="https://github.com/Pewpews">Pewpews</a></p> <p>Twitter: <a href="https://twitter.com/pewspew">@pewspew</a></p> <p>Chat: <a href="https://gitter.im/Pewpews/happypanda">Gitter chat</a></p> <p>Email: <code>happypandabugs@gmail.com</code></p> <p><strong>Current version</strong>: {}</p> <p><strong>Current database version</strong>: {}</p> <p>License: <a href="https://www.gnu.org/licenses/gpl-2.0.txt"> GENERAL PUBLIC LICENSE, Version 2</a></p> <p>Happypanda was created using:</p> <ul> <li>Python 3.5</li> <li>The Qt5 Framework</li> <li>Various python libraries (see github repo)</li> </ul> <p>Contributors (github): rachmadaniHaryono (big thanks!), nonamethanks, ImoutoChan, Moshidesu, peaceanpizza, utterbull, LePearlo</p> </body></html> """ ).format(vs, db_constants.CURRENT_DB_VERSION) TROUBLE_GUIDE = ( """ <!DOCTYPE html><html><head><meta charset="utf-8"><title>Untitled Document.md</title><style>@import 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.2.0/katex.min.css';code{color:#c7254e;background-color:#f9f2f4;border-radius:4px}code,kbd{padding:2px 4px}kbd{color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;box-shadow:none}pre{display:block;margin:0 0 10px;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}fieldset{border:0;min-width:0}legend{display:block;width:100%;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type="radio"],input[type="checkbox"]{margin:1px 0 0;line-height:normal}input[type="file"]{display:block}input[type="range"]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{padding-top:7px}output,.form-control{display:block;font-size:14px;line-height:1.4285714;color:#555}.form-control{width:100%;height:34px;padding:6px 12px;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#777;opacity:1}.form-control:-ms-input-placeholder{color:#777}.form-control::-webkit-input-placeholder{color:#777}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type="date"],input[type="time"],input[type="datetime-local"],input[type="month"]{line-height:34px;line-height:1.4285714 \0}input[type="date"].input-sm,.form-horizontal .form-group-sm input[type="date"].form-control,.input-group-sm>input[type="date"].form-control,.input-group-sm>input[type="date"].input-group-addon,.input-group-sm>.input-group-btn>input[type="date"].btn,input[type="time"].input-sm,.form-horizontal .form-group-sm input[type="time"].form-control,.input-group-sm>input[type="time"].form-control,.input-group-sm>input[type="time"].input-group-addon,.input-group-sm>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-sm,.form-horizontal .form-group-sm input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].input-group-addon,.input-group-sm>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-sm,.form-horizontal .form-group-sm input[type="month"].form-control,.input-group-sm>input[type="month"].form-control,.input-group-sm>input[type="month"].input-group-addon,.input-group-sm>.input-group-btn>input[type="month"].btn{line-height:30px}input[type="date"].input-lg,.form-horizontal .form-group-lg input[type="date"].form-control,.input-group-lg>input[type="date"].form-control,.input-group-lg>input[type="date"].input-group-addon,.input-group-lg>.input-group-btn>input[type="date"].btn,input[type="time"].input-lg,.form-horizontal .form-group-lg input[type="time"].form-control,.input-group-lg>input[type="time"].form-control,.input-group-lg>input[type="time"].input-group-addon,.input-group-lg>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-lg,.form-horizontal .form-group-lg input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].input-group-addon,.input-group-lg>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-lg,.form-horizontal .form-group-lg input[type="month"].form-control,.input-group-lg>input[type="month"].form-control,.input-group-lg>input[type="month"].input-group-addon,.input-group-lg>.input-group-btn>input[type="month"].btn{line-height:46px}.form-group{margin-bottom:15px}.radio,.checkbox{position:relative;display:block;min-height:20px;margin-top:10px;margin-bottom:10px}.radio label,.checkbox label{padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{position:absolute;margin-left:-20px;margin-top:4px \9}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="radio"].disabled,fieldset[disabled] input[type="radio"],input[type="checkbox"][disabled],input[type="checkbox"].disabled,fieldset[disabled] input[type="checkbox"],.radio-inline.disabled,fieldset[disabled] .radio-inline,.checkbox-inline.disabled,fieldset[disabled] .checkbox-inline,.radio.disabled label,fieldset[disabled] .radio label,.checkbox.disabled label,fieldset[disabled] .checkbox label{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-horizontal .form-group-lg .form-control-static.form-control,.input-group-lg>.form-control-static.form-control,.input-group-lg>.form-control-static.input-group-addon,.input-group-lg>.input-group-btn>.form-control-static.btn,.form-control-static.input-sm,.form-horizontal .form-group-sm .form-control-static.form-control,.input-group-sm>.form-control-static.form-control,.input-group-sm>.form-control-static.input-group-addon,.input-group-sm>.input-group-btn>.form-control-static.btn{padding-left:0;padding-right:0}.input-sm,.form-horizontal .form-group-sm .form-control,.input-group-sm>.form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.input-group-sm>.input-group-addon{height:30px;line-height:1.5}.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm,.form-horizontal .form-group-sm select.form-control,.input-group-sm>select.form-control,.input-group-sm>select.input-group-addon,.input-group-sm>.input-group-btn>select.btn{height:30px;line-height:30px}textarea.input-sm,.form-horizontal .form-group-sm textarea.form-control,.input-group-sm>textarea.form-control,.input-group-sm>textarea.input-group-addon,.input-group-sm>.input-group-btn>textarea.btn,select[multiple].input-sm,.form-horizontal .form-group-sm select[multiple].form-control,.input-group-sm>select[multiple].form-control,.input-group-sm>select[multiple].input-group-addon,.input-group-sm>.input-group-btn>select[multiple].btn{height:auto}.input-lg,.form-horizontal .form-group-lg .form-control,.input-group-lg>.form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.input-group-lg>.input-group-addon{height:46px;line-height:1.33}.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg,.form-horizontal .form-group-lg select.form-control,.input-group-lg>select.form-control,.input-group-lg>select.input-group-addon,.input-group-lg>.input-group-btn>select.btn{height:46px;line-height:46px}textarea.input-lg,.form-horizontal .form-group-lg textarea.form-control,.input-group-lg>textarea.form-control,.input-group-lg>textarea.input-group-addon,.input-group-lg>.input-group-btn>textarea.btn,select[multiple].input-lg,.form-horizontal .form-group-lg select[multiple].form-control,.input-group-lg>select[multiple].form-control,.input-group-lg>select[multiple].input-group-addon,.input-group-lg>.input-group-btn>select[multiple].btn{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:25px;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center}.input-lg+.form-control-feedback,.form-horizontal .form-group-lg .form-control+.form-control-feedback,.input-group-lg>.form-control+.form-control-feedback,.input-group-lg>.input-group-addon+.form-control-feedback,.input-group-lg>.input-group-btn>.btn+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback,.form-horizontal .form-group-sm .form-control+.form-control-feedback,.input-group-sm>.form-control+.form-control-feedback,.input-group-sm>.input-group-addon+.form-control-feedback,.input-group-sm>.input-group-btn>.btn+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-group:before{content:" ";display:table}.form-horizontal .form-group:after{content:" ";display:table;clear:both}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}.btn{display:inline-block;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{outline:0;background-image:none;box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{background-image:none}.btn-default.disabled,.btn-default.disabled:hover,.btn-default.disabled:focus,.btn-default.disabled:active,.btn-default.disabled.active,.btn-default[disabled],.btn-default[disabled]:hover,.btn-default[disabled]:focus,.btn-default[disabled]:active,.btn-default[disabled].active,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default:hover,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{color:#fff;background-color:#3071a9;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{background-image:none}.btn-primary.disabled,.btn-primary.disabled:hover,.btn-primary.disabled:focus,.btn-primary.disabled:active,.btn-primary.disabled.active,.btn-primary[disabled],.btn-primary[disabled]:hover,.btn-primary[disabled]:focus,.btn-primary[disabled]:active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary:hover,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{color:#fff;background-color:#449d44;border-color:#398439}.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{background-image:none}.btn-success.disabled,.btn-success.disabled:hover,.btn-success.disabled:focus,.btn-success.disabled:active,.btn-success.disabled.active,.btn-success[disabled],.btn-success[disabled]:hover,.btn-success[disabled]:focus,.btn-success[disabled]:active,.btn-success[disabled].active,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success:hover,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{background-image:none}.btn-info.disabled,.btn-info.disabled:hover,.btn-info.disabled:focus,.btn-info.disabled:active,.btn-info.disabled.active,.btn-info[disabled],.btn-info[disabled]:hover,.btn-info[disabled]:focus,.btn-info[disabled]:active,.btn-info[disabled].active,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info:hover,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{background-image:none}.btn-warning.disabled,.btn-warning.disabled:hover,.btn-warning.disabled:focus,.btn-warning.disabled:active,.btn-warning.disabled.active,.btn-warning[disabled],.btn-warning[disabled]:hover,.btn-warning[disabled]:focus,.btn-warning[disabled]:active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning:hover,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{background-image:none}.btn-danger.disabled,.btn-danger.disabled:hover,.btn-danger.disabled:focus,.btn-danger.disabled:active,.btn-danger.disabled.active,.btn-danger[disabled],.btn-danger[disabled]:hover,.btn-danger[disabled]:focus,.btn-danger[disabled]:active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger:hover,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{color:#428bca;font-weight:400;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:hover,fieldset[disabled] .btn-link:focus{color:#777;text-decoration:none}.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm{padding:5px 10px}.btn-sm,.btn-xs{font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*="col-"]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon{white-space:nowrap}.input-group-addon,.input-group-btn{width:1%;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm,.form-horizontal .form-group-sm .input-group-addon.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.input-group-addon.btn{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg,.form-horizontal .form-group-lg .input-group-addon.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.input-group-addon.btn{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{font-size:0;white-space:nowrap}.input-group-btn,.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.4285714;text-decoration:none;color:#428bca;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>li>span:hover,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:hover,.pagination>.active>a:focus,.pagination>.active>span,.pagination>.active>span:hover,.pagination>.active>span:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca;cursor:default}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.modal-open,.modal{overflow:hidden}.modal{display:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate3d(0,-25%,0);transform:translate3d(0,-25%,0);-webkit-transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.4285714px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.4285714}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{content:" ";display:table}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.clearfix:before,.clearfix:after{content:" ";display:table}.clearfix:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.hljs{display:block;overflow-x:auto;padding:.5em;background:#002b36;color:#839496;-webkit-text-size-adjust:none}.hljs-comment,.hljs-template_comment,.diff .hljs-header,.hljs-doctype,.hljs-pi,.lisp .hljs-string,.hljs-javadoc{color:#586e75}.hljs-keyword,.hljs-winutils,.method,.hljs-addition,.css .hljs-tag,.hljs-request,.hljs-status,.nginx .hljs-title{color:#859900}.hljs-number,.hljs-command,.hljs-string,.hljs-tag .hljs-value,.hljs-rules .hljs-value,.hljs-phpdoc,.hljs-dartdoc,.tex .hljs-formula,.hljs-regexp,.hljs-hexcolor,.hljs-link_url{color:#2aa198}.hljs-title,.hljs-localvars,.hljs-chunk,.hljs-decorator,.hljs-built_in,.hljs-identifier,.vhdl .hljs-literal,.hljs-id,.css .hljs-function{color:#268bd2}.hljs-attribute,.hljs-variable,.lisp .hljs-body,.smalltalk .hljs-number,.hljs-constant,.hljs-class .hljs-title,.hljs-parent,.hljs-type,.hljs-link_reference{color:#b58900}.hljs-preprocessor,.hljs-preprocessor .hljs-keyword,.hljs-pragma,.hljs-shebang,.hljs-symbol,.hljs-symbol .hljs-string,.diff .hljs-change,.hljs-special,.hljs-attr_selector,.hljs-subst,.hljs-cdata,.css .hljs-pseudo,.hljs-header{color:#cb4b16}.hljs-deletion,.hljs-important{color:#dc322f}.hljs-link_label{color:#6c71c4}.tex .hljs-formula{background:#073642}*,*:before,*:after{box-sizing:border-box}html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}images{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{box-sizing:content-box;height:0}pre{overflow:auto}code,kbd{font-size:1em}code,kbd,pre,samp{font-family:monospace,monospace}samp{font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}.debug{background-color:#ffc0cb!important}.ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ir{background-color:transparent;border:0;overflow:hidden}.ir::before{content:'';display:block;height:150%;width:0}html{font-size:.875em;background:#fafafa;color:#373D49}html,body{font-family:Georgia,Cambria,serif;height:100%}body{font-size:1rem;font-weight:400;line-height:2rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}li{-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-left:1rem}li>ul,li>ol{margin-bottom:0}p{padding-top:.66001rem;-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-top:0}p,pre{margin-bottom:1.33999rem}pre{font-size:1rem;padding:.66001rem 9.5px 9.5px;line-height:2rem;background:-webkit-linear-gradient(top,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background:linear-gradient(to bottom,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background-size:100% 4rem;border-color:#D3DAEA}blockquote{margin:0}blockquote p{font-size:1rem;margin-bottom:.33999rem;font-style:italic;padding:.66001rem 1rem 1rem;border-left:3px solid #A0AABF}th,td{padding:12px}h1,h2,h3,h4,h5,h6{font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;-webkit-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;-moz-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-style:normal;font-weight:600;margin-top:0}h1{line-height:3rem;font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h2,h3{line-height:3rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}a{cursor:pointer;color:#35D7BB;text-decoration:none}a:hover,a:focus{border-bottom-color:#35D7BB;color:#dff9f4}img{height:auto;max-width:100%}.g{display:block}.g:after{clear:both;content:'';display:table}.g-b{float:left;margin:0;width:100%}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--center{display:block;float:none;margin:0 auto}.g-b--right{float:right}.g-b--1of1{width:100%}.g-b--1of2,.g-b--2of4,.g-b--3of6,.g-b--4of8,.g-b--5of10,.g-b--6of12{width:50%}.g-b--1of3,.g-b--2of6,.g-b--4of12{width:33.333%}.g-b--2of3,.g-b--4of6,.g-b--8of12{width:66.666%}.g-b--1of4,.g-b--2of8,.g-b--3of12{width:25%}.g-b--3of4,.g-b--6of8,.g-b--9of12{width:75%}.g-b--1of5,.g-b--2of10{width:20%}.g-b--2of5,.g-b--4of10{width:40%}.g-b--3of5,.g-b--6of10{width:60%}.g-b--4of5,.g-b--8of10{width:80%}.g-b--1of6,.g-b--2of12{width:16.666%}.g-b--5of6,.g-b--10of12{width:83.333%}.g-b--1of8{width:12.5%}.g-b--3of8{width:37.5%}.g-b--5of8{width:62.5%}.g-b--7of8{width:87.5%}.g-b--1of10{width:10%}.g-b--3of10{width:30%}.g-b--7of10{width:70%}.g-b--9of10{width:90%}.g-b--1of12{width:8.333%}.g-b--5of12{width:41.666%}.g-b--7of12{width:58.333%}.g-b--11of12{width:91.666%}.g-b--push--1of1{margin-left:100%}.g-b--push--1of2,.g-b--push--2of4,.g-b--push--3of6,.g-b--push--4of8,.g-b--push--5of10,.g-b--push--6of12{margin-left:50%}.g-b--push--1of3,.g-b--push--2of6,.g-b--push--4of12{margin-left:33.333%}.g-b--push--2of3,.g-b--push--4of6,.g-b--push--8of12{margin-left:66.666%}.g-b--push--1of4,.g-b--push--2of8,.g-b--push--3of12{margin-left:25%}.g-b--push--3of4,.g-b--push--6of8,.g-b--push--9of12{margin-left:75%}.g-b--push--1of5,.g-b--push--2of10{margin-left:20%}.g-b--push--2of5,.g-b--push--4of10{margin-left:40%}.g-b--push--3of5,.g-b--push--6of10{margin-left:60%}.g-b--push--4of5,.g-b--push--8of10{margin-left:80%}.g-b--push--1of6,.g-b--push--2of12{margin-left:16.666%}.g-b--push--5of6,.g-b--push--10of12{margin-left:83.333%}.g-b--push--1of8{margin-left:12.5%}.g-b--push--3of8{margin-left:37.5%}.g-b--push--5of8{margin-left:62.5%}.g-b--push--7of8{margin-left:87.5%}.g-b--push--1of10{margin-left:10%}.g-b--push--3of10{margin-left:30%}.g-b--push--7of10{margin-left:70%}.g-b--push--9of10{margin-left:90%}.g-b--push--1of12{margin-left:8.333%}.g-b--push--5of12{margin-left:41.666%}.g-b--push--7of12{margin-left:58.333%}.g-b--push--11of12{margin-left:91.666%}.g-b--pull--1of1{margin-right:100%}.g-b--pull--1of2,.g-b--pull--2of4,.g-b--pull--3of6,.g-b--pull--4of8,.g-b--pull--5of10,.g-b--pull--6of12{margin-right:50%}.g-b--pull--1of3,.g-b--pull--2of6,.g-b--pull--4of12{margin-right:33.333%}.g-b--pull--2of3,.g-b--pull--4of6,.g-b--pull--8of12{margin-right:66.666%}.g-b--pull--1of4,.g-b--pull--2of8,.g-b--pull--3of12{margin-right:25%}.g-b--pull--3of4,.g-b--pull--6of8,.g-b--pull--9of12{margin-right:75%}.g-b--pull--1of5,.g-b--pull--2of10{margin-right:20%}.g-b--pull--2of5,.g-b--pull--4of10{margin-right:40%}.g-b--pull--3of5,.g-b--pull--6of10{margin-right:60%}.g-b--pull--4of5,.g-b--pull--8of10{margin-right:80%}.g-b--pull--1of6,.g-b--pull--2of12{margin-right:16.666%}.g-b--pull--5of6,.g-b--pull--10of12{margin-right:83.333%}.g-b--pull--1of8{margin-right:12.5%}.g-b--pull--3of8{margin-right:37.5%}.g-b--pull--5of8{margin-right:62.5%}.g-b--pull--7of8{margin-right:87.5%}.g-b--pull--1of10{margin-right:10%}.g-b--pull--3of10{margin-right:30%}.g-b--pull--7of10{margin-right:70%}.g-b--pull--9of10{margin-right:90%}.g-b--pull--1of12{margin-right:8.333%}.g-b--pull--5of12{margin-right:41.666%}.g-b--pull--7of12{margin-right:58.333%}.g-b--pull--11of12{margin-right:91.666%}.splashscreen{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#373D49;z-index:22}.splashscreen-dillinger{width:260px;height:auto;display:block;margin:0 auto;padding-bottom:3rem}.splashscreen p{font-size:1.25rem;padding-top:.56251rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;text-align:center;max-width:500px;margin:0 auto;color:#FFF}.sp-center{position:relative;-webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%);top:50%}.open-menu>.wrapper{overflow-x:hidden}.page{margin:0 auto;position:relative;top:0;left:0;width:100%;height:100%;z-index:2;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;background-color:#fff;padding-top:51px;will-change:left}.open-menu .page{left:270px}.title{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;padding-left:16px;padding-right:16px;margin-top:1rem}.split-preview .title{padding-left:0}.title-document{line-height:1rem;font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem;font-weight:400;font-family:"Ubuntu Mono",Monaco;color:#373D49;padding-left:16px;padding-right:16px;width:80%;min-width:300px;outline:0;border:none}.icon{display:block;margin:0 auto;width:36px;height:36px;border-radius:3px;text-align:center}.icon svg{display:inline-block;margin-left:auto;margin-right:auto}.icon-preview{background-color:#373D49;line-height:40px}.icon-preview svg{width:19px;height:12px}.icon-settings{background-color:#373D49;line-height:44px}.icon-settings svg{width:18px;height:18px}.icon-link{width:16px;height:16px;line-height:1;margin-right:24px;text-align:right}.navbar{background-color:#373D49;height:51px;width:100%;position:fixed;top:0;left:0;z-index:6;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;will-change:left}.navbar:after{content:"";display:table;clear:both}.open-menu .navbar{left:270px}.navbar-brand{float:left;margin:0 0 0 24px;padding:0;line-height:42px}.navbar-brand svg{width:85px;height:11px}.nav-left{float:left}.nav-right{float:right}.nav-sidebar{width:100%}.menu{list-style:none;margin:0;padding:0}.menu a{border:0;color:#A0AABF;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;outline:none;text-transform:uppercase}.menu a:hover{color:#35D7BB}.menu .menu-item{border:0;display:none;float:left;margin:0;position:relative}.menu .menu-item>a{display:block;font-size:12px;height:51px;letter-spacing:1px;line-height:51px;padding:0 24px}.menu .menu-item--settings,.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar,.menu .menu-item--link-unlink.in-sidebar,.menu .menu-item--documents.in-sidebar{display:block}.menu .menu-item--documents{padding-bottom:1rem}.menu .menu-item.open>a{background-color:#1D212A}.menu .menu-item-icon>a{height:auto;padding:0}.menu .menu-item-icon:hover>a{background-color:transparent}.menu .menu-link.open i{background-color:#1D212A}.menu .menu-link.open g{fill:#35D7BB}.menu .menu-link-preview,.menu .menu-link-settings{margin-top:8px;width:51px}.menu-sidebar{width:100%}.menu-sidebar .menu-item{float:none;margin-bottom:1px;width:100%}.menu-sidebar .menu-item.open>a{background-color:#373D49}.menu-sidebar .open .caret{-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.menu-sidebar>.menu-item:hover .dropdown a,.menu-sidebar>.menu-item:hover .settings a{background-color:transparent}.menu-sidebar .menu-link{background-color:#373D49;font-weight:600}.menu-sidebar .menu-link:after{content:"";display:table;clear:both}.menu-sidebar .menu-link>span{float:left}.menu-sidebar .menu-link>.caret{float:right;text-align:right;top:22px}.menu-sidebar .dropdown,.menu-sidebar .settings{background-color:transparent;position:static;width:100%}.dropdown{position:absolute;right:0;top:51px;width:188px}.dropdown,.settings{display:none;background-color:#1D212A}.dropdown{padding:0}.dropdown,.settings,.sidebar-list{list-style:none;margin:0}.sidebar-list{padding:0}.dropdown li{margin:32px 0;padding:0 0 0 32px}.dropdown li,.settings li{line-height:1}.sidebar-list li{line-height:1;margin:32px 0;padding:0 0 0 32px}.dropdown a{color:#D0D6E2}.dropdown a,.settings a,.sidebar-list a{display:block;text-transform:none}.sidebar-list a{color:#D0D6E2}.dropdown a:after,.settings a:after,.sidebar-list a:after{content:"";display:table;clear:both}.dropdown .icon,.settings .icon,.sidebar-list .icon{float:right}.open .dropdown,.open .settings,.open .sidebar-list{display:block}.open .dropdown.collapse,.open .collapse.settings,.open .sidebar-list.collapse{display:none}.open .dropdown.collapse.in,.open .collapse.in.settings,.open .sidebar-list.collapse.in{display:block}.dropdown .unlinked .icon,.settings .unlinked .icon,.sidebar-list .unlinked .icon{opacity:.3}.dropdown.documents li,.documents.settings li,.sidebar-list.documents li{background-image:url("../img/icons/file.svg");background-position:240px center;background-repeat:no-repeat;background-size:14px 16px;padding:3px 32px}.dropdown.documents li.octocat,.documents.settings li.octocat,.sidebar-list.documents li.octocat{background-image:url("../img/icons/octocat.svg");background-position:234px center;background-size:24px 24px}.dropdown.documents li:last-child,.documents.settings li:last-child,.sidebar-list.documents li:last-child{margin-bottom:1rem}.dropdown.documents li.active a,.documents.settings li.active a,.sidebar-list.documents li.active a{color:#35D7BB}.settings{position:fixed;top:67px;right:16px;border-radius:3px;width:288px;background-color:#373D49;padding:16px;z-index:7}.show-settings .settings{display:block}.settings .has-checkbox{float:left}.settings a{font-size:1.25rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;-webkit-font-smoothing:antialiased;line-height:28px;color:#D0D6E2}.settings a:after{content:"";display:table;clear:both}.settings a:hover{color:#35D7BB}.settings li{border-bottom:1px solid #4F535B;margin:0;padding:16px 0}.settings li:last-child{border-bottom:none}.brand{border:none;display:block}.brand:hover g{fill:#35D7BB}.toggle{display:block;float:left;height:16px;padding:25px 16px 26px;width:40px}.toggle span:after,.toggle span:before{content:'';left:0;position:absolute;top:-6px}.toggle span:after{top:6px}.toggle span{display:block;position:relative}.toggle span,.toggle span:after,.toggle span:before{-webkit-backface-visibility:hidden;backface-visibility:hidden;background-color:#D3DAEA;height:2px;-webkit-transition:all .3s;transition:all .3s;width:20px}.open-menu .toggle span{background-color:transparent}.open-menu .toggle span:before{-webkit-transform:rotate(45deg)translate(3px,3px);-ms-transform:rotate(45deg)translate(3px,3px);transform:rotate(45deg)translate(3px,3px)}.open-menu .toggle span:after{-webkit-transform:rotate(-45deg)translate(5px,-6px);-ms-transform:rotate(-45deg)translate(5px,-6px);transform:rotate(-45deg)translate(5px,-6px)}.caret{display:inline-block;width:0;height:0;margin-left:6px;vertical-align:middle;position:relative;top:-1px;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.sidebar{overflow:auto;height:100%;padding-right:15px;padding-bottom:15px;width:285px}.sidebar-wrapper{-webkit-overflow-scrolling:touch;background-color:#2B2F36;left:0;height:100%;overflow-y:hidden;position:fixed;top:0;width:285px;z-index:1}.sidebar-branding{width:160px;padding:0;margin:16px auto}.header{border-bottom:1px solid #E8E8E8;position:relative}.words{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;z-index:5;position:absolute;right:16px;top:0}.words span{color:#000}.btn{text-align:center;display:inline-block;width:100%;text-transform:uppercase;font-weight:600;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;text-shadow:0 1px 0 #1b8b77;padding:16px 24px;background-color:#35D7BB;border-radius:3px;margin:0 auto 16px;line-height:1;color:#fff;-webkit-transition:all .15s linear;transition:all .15s linear;-webkit-font-smoothing:antialiased}.btn--new,.btn--save{display:block;width:238px}.btn--new:hover,.btn--new:focus,.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 3px #24b59c;text-shadow:0 1px 0 #24b59c}.btn--save{background-color:#4A5261;text-shadow:0 1px 1px #1e2127}.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 5px #08090a;text-shadow:none}.btn--delete{display:block;width:238px;background-color:transparent;font-size:12px;text-shadow:none}.btn--delete:hover,.btn--delete:focus{color:#fff;border-bottom-color:transparent;text-shadow:0 1px 0 #08090a;opacity:.8}.btn--ok,.btn--close{border-top:0;background-color:#4A5261;text-shadow:0 1px 0 #08090a;margin:0}.btn--ok:hover,.btn--ok:focus,.btn--close:hover,.btn--close:focus{color:#fff;background-color:#292d36;text-shadow:none}.overlay{position:absolute;top:0;left:0;width:100%;height:100%;background-color:rgba(55,61,73,.8);-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;-webkit-transition-timing-function:ease-out;transition-timing-function:ease-out;will-change:left,opacity,visibility;z-index:5;opacity:0;visibility:hidden}.show-settings .overlay{visibility:visible;opacity:1}.switch{float:right;line-height:1}.switch input{display:none}.switch small{display:inline-block;cursor:pointer;padding:0 24px 0 0;-webkit-transition:all ease .2s;transition:all ease .2s;background-color:#2B2F36;border-color:#2B2F36}.switch small,.switch small:before{border-radius:30px;box-shadow:inset 0 0 2px 0 #14171F}.switch small:before{display:block;content:'';width:28px;height:28px;background:#fff}.switch.checked small{padding-right:0;padding-left:24px;background-color:#35D7BB;box-shadow:none}.modal--dillinger.about .modal-dialog{font-size:1.25rem;max-width:500px}.modal--dillinger .modal-dialog{max-width:600px;width:auto;margin:5rem auto}.modal--dillinger .modal-content{background:#373D49;border-radius:3px;box-shadow:0 2px 5px 0 #2C3B59;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;padding:2rem}.modal--dillinger ul{list-style-type:disc;margin:1rem 0;padding:0 0 0 1rem}.modal--dillinger li{padding:0;margin:0}.modal--dillinger .modal-header{border:0;padding:0}.modal--dillinger .modal-body{padding:0}.modal--dillinger .modal-footer{border:0;padding:0}.modal--dillinger .close{color:#fff;opacity:1}.modal-backdrop{background-color:#373D49}.pagination--dillinger{padding:0!important;margin:1.5rem 0!important;-webkit-box-pack:justify;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;-webkit-align-content:stretch;-ms-flex-line-pack:stretch;align-content:stretch}.pagination--dillinger,.pagination--dillinger li{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex}.pagination--dillinger li{-webkit-box-flex:1;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;text-align:center}.pagination--dillinger li:first-child>a,.pagination--dillinger li.disabled>a,.pagination--dillinger li.disabled>a:hover,.pagination--dillinger li.disabled>a:focus,.pagination--dillinger li>a{background-color:transparent;border-color:#4F535B;border-right-color:transparent}.pagination--dillinger li.active>a,.pagination--dillinger li.active>a:hover,.pagination--dillinger li.active>a:focus{border-color:#4A5261;background-color:#4A5261;color:#fff}.pagination--dillinger li>a{float:none;color:#fff;width:100%;display:block;text-align:center;margin:0;border-right-color:transparent;padding:6px}.pagination--dillinger li>a:hover,.pagination--dillinger li>a:focus{border-color:#35D7BB;background-color:#35D7BB;color:#fff}.pagination--dillinger li:last-child a{border-color:#4F535B}.pagination--dillinger li:first-child a{border-right-color:transparent}.diNotify{position:absolute;z-index:9999;left:0;right:0;top:0;margin:0 auto;max-width:400px;text-align:center;-webkit-transition:top .5s ease-in-out,opacity .5s ease-in-out;transition:top .5s ease-in-out,opacity .5s ease-in-out;visibility:hidden}.diNotify-body{-webkit-font-smoothing:antialiased;background-color:#35D7BB;background:#666E7F;border-radius:3px;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;overflow:hidden;padding:1rem 2rem .5rem;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:baseline;-webkit-align-items:baseline;-ms-flex-align:baseline;align-items:baseline;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center}.diNotify-icon{display:block;width:16px;height:16px;line-height:16px;position:relative;top:3px}.diNotify-message{padding-left:1rem}.zen-wrapper{position:fixed;top:0;left:0;right:0;bottom:0;width:100%;height:100%;z-index:10;background-color:#FFF;opacity:0;-webkit-transition:opacity .25s ease-in-out;transition:opacity .25s ease-in-out}.zen-wrapper.on{opacity:1}.enter-zen-mode{background-image:url("../img/icons/enter-zen.svg");right:.5rem;top:.5rem;display:none}.enter-zen-mode,.close-zen-mode{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;background-repeat:no-repeat;width:32px;height:32px;display:block;position:absolute}.close-zen-mode{background-image:url("../img/icons/exit-zen.svg");right:1rem;top:1rem}.zen-page{position:relative;top:0;bottom:0;z-index:11;height:100%;width:100%}#zen{font-size:1.25rem;width:300px;height:80%;margin:0 auto;position:relative;top:10%}#zen:before,#zen:after{content:"";position:absolute;height:10%;width:100%;z-index:12;pointer-events:none}.split{overflow:scroll;padding:0!important}.split-editor{padding-left:0;padding-right:0;position:relative}.show-preview .split-editor{display:none}.split-preview{background-color:#fff;display:none;top:0;position:relative;z-index:4}.show-preview .split-preview{display:block}#editor{font-size:1rem;font-family:"Ubuntu Mono",Monaco;font-weight:400;line-height:2rem;width:100%;height:100%}#editor .ace_gutter{-webkit-font-smoothing:antialiased}#preview a{color:#A0AABF;text-decoration:underline}.sr-only{visibility:hidden;text-overflow:110%;overflow:hidden;top:-100px;position:absolute}.mnone{margin:0!important}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .radio label,.form-inline .checkbox label{padding-left:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}.form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}.form-horizontal .form-group-lg .control-label{padding-top:14.3px}.form-horizontal .form-group-sm .control-label{padding-top:6px}.modal-dialog{width:600px;margin:30px auto}.modal-content{box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}@media screen and (min-width:27.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--m1of1{width:100%}.g-b--m1of2,.g-b--m2of4,.g-b--m3of6,.g-b--m4of8,.g-b--m5of10,.g-b--m6of12{width:50%}.g-b--m1of3,.g-b--m2of6,.g-b--m4of12{width:33.333%}.g-b--m2of3,.g-b--m4of6,.g-b--m8of12{width:66.666%}.g-b--m1of4,.g-b--m2of8,.g-b--m3of12{width:25%}.g-b--m3of4,.g-b--m6of8,.g-b--m9of12{width:75%}.g-b--m1of5,.g-b--m2of10{width:20%}.g-b--m2of5,.g-b--m4of10{width:40%}.g-b--m3of5,.g-b--m6of10{width:60%}.g-b--m4of5,.g-b--m8of10{width:80%}.g-b--m1of6,.g-b--m2of12{width:16.666%}.g-b--m5of6,.g-b--m10of12{width:83.333%}.g-b--m1of8{width:12.5%}.g-b--m3of8{width:37.5%}.g-b--m5of8{width:62.5%}.g-b--m7of8{width:87.5%}.g-b--m1of10{width:10%}.g-b--m3of10{width:30%}.g-b--m7of10{width:70%}.g-b--m9of10{width:90%}.g-b--m1of12{width:8.333%}.g-b--m5of12{width:41.666%}.g-b--m7of12{width:58.333%}.g-b--m11of12{width:91.666%}.g-b--push--m1of1{margin-left:100%}.g-b--push--m1of2,.g-b--push--m2of4,.g-b--push--m3of6,.g-b--push--m4of8,.g-b--push--m5of10,.g-b--push--m6of12{margin-left:50%}.g-b--push--m1of3,.g-b--push--m2of6,.g-b--push--m4of12{margin-left:33.333%}.g-b--push--m2of3,.g-b--push--m4of6,.g-b--push--m8of12{margin-left:66.666%}.g-b--push--m1of4,.g-b--push--m2of8,.g-b--push--m3of12{margin-left:25%}.g-b--push--m3of4,.g-b--push--m6of8,.g-b--push--m9of12{margin-left:75%}.g-b--push--m1of5,.g-b--push--m2of10{margin-left:20%}.g-b--push--m2of5,.g-b--push--m4of10{margin-left:40%}.g-b--push--m3of5,.g-b--push--m6of10{margin-left:60%}.g-b--push--m4of5,.g-b--push--m8of10{margin-left:80%}.g-b--push--m1of6,.g-b--push--m2of12{margin-left:16.666%}.g-b--push--m5of6,.g-b--push--m10of12{margin-left:83.333%}.g-b--push--m1of8{margin-left:12.5%}.g-b--push--m3of8{margin-left:37.5%}.g-b--push--m5of8{margin-left:62.5%}.g-b--push--m7of8{margin-left:87.5%}.g-b--push--m1of10{margin-left:10%}.g-b--push--m3of10{margin-left:30%}.g-b--push--m7of10{margin-left:70%}.g-b--push--m9of10{margin-left:90%}.g-b--push--m1of12{margin-left:8.333%}.g-b--push--m5of12{margin-left:41.666%}.g-b--push--m7of12{margin-left:58.333%}.g-b--push--m11of12{margin-left:91.666%}.g-b--pull--m1of1{margin-right:100%}.g-b--pull--m1of2,.g-b--pull--m2of4,.g-b--pull--m3of6,.g-b--pull--m4of8,.g-b--pull--m5of10,.g-b--pull--m6of12{margin-right:50%}.g-b--pull--m1of3,.g-b--pull--m2of6,.g-b--pull--m4of12{margin-right:33.333%}.g-b--pull--m2of3,.g-b--pull--m4of6,.g-b--pull--m8of12{margin-right:66.666%}.g-b--pull--m1of4,.g-b--pull--m2of8,.g-b--pull--m3of12{margin-right:25%}.g-b--pull--m3of4,.g-b--pull--m6of8,.g-b--pull--m9of12{margin-right:75%}.g-b--pull--m1of5,.g-b--pull--m2of10{margin-right:20%}.g-b--pull--m2of5,.g-b--pull--m4of10{margin-right:40%}.g-b--pull--m3of5,.g-b--pull--m6of10{margin-right:60%}.g-b--pull--m4of5,.g-b--pull--m8of10{margin-right:80%}.g-b--pull--m1of6,.g-b--pull--m2of12{margin-right:16.666%}.g-b--pull--m5of6,.g-b--pull--m10of12{margin-right:83.333%}.g-b--pull--m1of8{margin-right:12.5%}.g-b--pull--m3of8{margin-right:37.5%}.g-b--pull--m5of8{margin-right:62.5%}.g-b--pull--m7of8{margin-right:87.5%}.g-b--pull--m1of10{margin-right:10%}.g-b--pull--m3of10{margin-right:30%}.g-b--pull--m7of10{margin-right:70%}.g-b--pull--m9of10{margin-right:90%}.g-b--pull--m1of12{margin-right:8.333%}.g-b--pull--m5of12{margin-right:41.666%}.g-b--pull--m7of12{margin-right:58.333%}.g-b--pull--m11of12{margin-right:91.666%}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:400px}#editor{font-size:1rem}}@media screen and (min-width:46.25em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--t1of1{width:100%}.g-b--t1of2,.g-b--t2of4,.g-b--t3of6,.g-b--t4of8,.g-b--t5of10,.g-b--t6of12{width:50%}.g-b--t1of3,.g-b--t2of6,.g-b--t4of12{width:33.333%}.g-b--t2of3,.g-b--t4of6,.g-b--t8of12{width:66.666%}.g-b--t1of4,.g-b--t2of8,.g-b--t3of12{width:25%}.g-b--t3of4,.g-b--t6of8,.g-b--t9of12{width:75%}.g-b--t1of5,.g-b--t2of10{width:20%}.g-b--t2of5,.g-b--t4of10{width:40%}.g-b--t3of5,.g-b--t6of10{width:60%}.g-b--t4of5,.g-b--t8of10{width:80%}.g-b--t1of6,.g-b--t2of12{width:16.666%}.g-b--t5of6,.g-b--t10of12{width:83.333%}.g-b--t1of8{width:12.5%}.g-b--t3of8{width:37.5%}.g-b--t5of8{width:62.5%}.g-b--t7of8{width:87.5%}.g-b--t1of10{width:10%}.g-b--t3of10{width:30%}.g-b--t7of10{width:70%}.g-b--t9of10{width:90%}.g-b--t1of12{width:8.333%}.g-b--t5of12{width:41.666%}.g-b--t7of12{width:58.333%}.g-b--t11of12{width:91.666%}.g-b--push--t1of1{margin-left:100%}.g-b--push--t1of2,.g-b--push--t2of4,.g-b--push--t3of6,.g-b--push--t4of8,.g-b--push--t5of10,.g-b--push--t6of12{margin-left:50%}.g-b--push--t1of3,.g-b--push--t2of6,.g-b--push--t4of12{margin-left:33.333%}.g-b--push--t2of3,.g-b--push--t4of6,.g-b--push--t8of12{margin-left:66.666%}.g-b--push--t1of4,.g-b--push--t2of8,.g-b--push--t3of12{margin-left:25%}.g-b--push--t3of4,.g-b--push--t6of8,.g-b--push--t9of12{margin-left:75%}.g-b--push--t1of5,.g-b--push--t2of10{margin-left:20%}.g-b--push--t2of5,.g-b--push--t4of10{margin-left:40%}.g-b--push--t3of5,.g-b--push--t6of10{margin-left:60%}.g-b--push--t4of5,.g-b--push--t8of10{margin-left:80%}.g-b--push--t1of6,.g-b--push--t2of12{margin-left:16.666%}.g-b--push--t5of6,.g-b--push--t10of12{margin-left:83.333%}.g-b--push--t1of8{margin-left:12.5%}.g-b--push--t3of8{margin-left:37.5%}.g-b--push--t5of8{margin-left:62.5%}.g-b--push--t7of8{margin-left:87.5%}.g-b--push--t1of10{margin-left:10%}.g-b--push--t3of10{margin-left:30%}.g-b--push--t7of10{margin-left:70%}.g-b--push--t9of10{margin-left:90%}.g-b--push--t1of12{margin-left:8.333%}.g-b--push--t5of12{margin-left:41.666%}.g-b--push--t7of12{margin-left:58.333%}.g-b--push--t11of12{margin-left:91.666%}.g-b--pull--t1of1{margin-right:100%}.g-b--pull--t1of2,.g-b--pull--t2of4,.g-b--pull--t3of6,.g-b--pull--t4of8,.g-b--pull--t5of10,.g-b--pull--t6of12{margin-right:50%}.g-b--pull--t1of3,.g-b--pull--t2of6,.g-b--pull--t4of12{margin-right:33.333%}.g-b--pull--t2of3,.g-b--pull--t4of6,.g-b--pull--t8of12{margin-right:66.666%}.g-b--pull--t1of4,.g-b--pull--t2of8,.g-b--pull--t3of12{margin-right:25%}.g-b--pull--t3of4,.g-b--pull--t6of8,.g-b--pull--t9of12{margin-right:75%}.g-b--pull--t1of5,.g-b--pull--t2of10{margin-right:20%}.g-b--pull--t2of5,.g-b--pull--t4of10{margin-right:40%}.g-b--pull--t3of5,.g-b--pull--t6of10{margin-right:60%}.g-b--pull--t4of5,.g-b--pull--t8of10{margin-right:80%}.g-b--pull--t1of6,.g-b--pull--t2of12{margin-right:16.666%}.g-b--pull--t5of6,.g-b--pull--t10of12{margin-right:83.333%}.g-b--pull--t1of8{margin-right:12.5%}.g-b--pull--t3of8{margin-right:37.5%}.g-b--pull--t5of8{margin-right:62.5%}.g-b--pull--t7of8{margin-right:87.5%}.g-b--pull--t1of10{margin-right:10%}.g-b--pull--t3of10{margin-right:30%}.g-b--pull--t7of10{margin-right:70%}.g-b--pull--t9of10{margin-right:90%}.g-b--pull--t1of12{margin-right:8.333%}.g-b--pull--t5of12{margin-right:41.666%}.g-b--pull--t7of12{margin-right:58.333%}.g-b--pull--t11of12{margin-right:91.666%}.splashscreen-dillinger{width:500px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--save-to,.menu .menu-item--import-from{display:block}.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog{font-size:1.25rem}.enter-zen-mode{display:block}.close-zen-mode{right:3rem;top:3rem}#zen{font-size:1.25rem;width:500px}.split-editor{border-right:1px solid #E8E8E8;float:left;height:calc(100vh - 130px);-webkit-overflow-scrolling:touch;padding-right:16px;width:50%}.show-preview .split-editor{display:block}.split-preview{display:block;float:right;height:calc(100vh - 130px);-webkit-overflow-scrolling:touch;position:relative;top:0;width:50%}#editor{font-size:1rem}}@media screen and (min-width:62.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--d1of1{width:100%}.g-b--d1of2,.g-b--d2of4,.g-b--d3of6,.g-b--d4of8,.g-b--d5of10,.g-b--d6of12{width:50%}.g-b--d1of3,.g-b--d2of6,.g-b--d4of12{width:33.333%}.g-b--d2of3,.g-b--d4of6,.g-b--d8of12{width:66.666%}.g-b--d1of4,.g-b--d2of8,.g-b--d3of12{width:25%}.g-b--d3of4,.g-b--d6of8,.g-b--d9of12{width:75%}.g-b--d1of5,.g-b--d2of10{width:20%}.g-b--d2of5,.g-b--d4of10{width:40%}.g-b--d3of5,.g-b--d6of10{width:60%}.g-b--d4of5,.g-b--d8of10{width:80%}.g-b--d1of6,.g-b--d2of12{width:16.666%}.g-b--d5of6,.g-b--d10of12{width:83.333%}.g-b--d1of8{width:12.5%}.g-b--d3of8{width:37.5%}.g-b--d5of8{width:62.5%}.g-b--d7of8{width:87.5%}.g-b--d1of10{width:10%}.g-b--d3of10{width:30%}.g-b--d7of10{width:70%}.g-b--d9of10{width:90%}.g-b--d1of12{width:8.333%}.g-b--d5of12{width:41.666%}.g-b--d7of12{width:58.333%}.g-b--d11of12{width:91.666%}.g-b--push--d1of1{margin-left:100%}.g-b--push--d1of2,.g-b--push--d2of4,.g-b--push--d3of6,.g-b--push--d4of8,.g-b--push--d5of10,.g-b--push--d6of12{margin-left:50%}.g-b--push--d1of3,.g-b--push--d2of6,.g-b--push--d4of12{margin-left:33.333%}.g-b--push--d2of3,.g-b--push--d4of6,.g-b--push--d8of12{margin-left:66.666%}.g-b--push--d1of4,.g-b--push--d2of8,.g-b--push--d3of12{margin-left:25%}.g-b--push--d3of4,.g-b--push--d6of8,.g-b--push--d9of12{margin-left:75%}.g-b--push--d1of5,.g-b--push--d2of10{margin-left:20%}.g-b--push--d2of5,.g-b--push--d4of10{margin-left:40%}.g-b--push--d3of5,.g-b--push--d6of10{margin-left:60%}.g-b--push--d4of5,.g-b--push--d8of10{margin-left:80%}.g-b--push--d1of6,.g-b--push--d2of12{margin-left:16.666%}.g-b--push--d5of6,.g-b--push--d10of12{margin-left:83.333%}.g-b--push--d1of8{margin-left:12.5%}.g-b--push--d3of8{margin-left:37.5%}.g-b--push--d5of8{margin-left:62.5%}.g-b--push--d7of8{margin-left:87.5%}.g-b--push--d1of10{margin-left:10%}.g-b--push--d3of10{margin-left:30%}.g-b--push--d7of10{margin-left:70%}.g-b--push--d9of10{margin-left:90%}.g-b--push--d1of12{margin-left:8.333%}.g-b--push--d5of12{margin-left:41.666%}.g-b--push--d7of12{margin-left:58.333%}.g-b--push--d11of12{margin-left:91.666%}.g-b--pull--d1of1{margin-right:100%}.g-b--pull--d1of2,.g-b--pull--d2of4,.g-b--pull--d3of6,.g-b--pull--d4of8,.g-b--pull--d5of10,.g-b--pull--d6of12{margin-right:50%}.g-b--pull--d1of3,.g-b--pull--d2of6,.g-b--pull--d4of12{margin-right:33.333%}.g-b--pull--d2of3,.g-b--pull--d4of6,.g-b--pull--d8of12{margin-right:66.666%}.g-b--pull--d1of4,.g-b--pull--d2of8,.g-b--pull--d3of12{margin-right:25%}.g-b--pull--d3of4,.g-b--pull--d6of8,.g-b--pull--d9of12{margin-right:75%}.g-b--pull--d1of5,.g-b--pull--d2of10{margin-right:20%}.g-b--pull--d2of5,.g-b--pull--d4of10{margin-right:40%}.g-b--pull--d3of5,.g-b--pull--d6of10{margin-right:60%}.g-b--pull--d4of5,.g-b--pull--d8of10{margin-right:80%}.g-b--pull--d1of6,.g-b--pull--d2of12{margin-right:16.666%}.g-b--pull--d5of6,.g-b--pull--d10of12{margin-right:83.333%}.g-b--pull--d1of8{margin-right:12.5%}.g-b--pull--d3of8{margin-right:37.5%}.g-b--pull--d5of8{margin-right:62.5%}.g-b--pull--d7of8{margin-right:87.5%}.g-b--pull--d1of10{margin-right:10%}.g-b--pull--d3of10{margin-right:30%}.g-b--pull--d7of10{margin-right:70%}.g-b--pull--d9of10{margin-right:90%}.g-b--pull--d1of12{margin-right:8.333%}.g-b--pull--d5of12{margin-right:41.666%}.g-b--pull--d7of12{margin-right:58.333%}.g-b--pull--d11of12{margin-right:91.666%}.splashscreen-dillinger{width:700px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--export-as{display:block}.menu .menu-item--preview{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:700px}#editor{font-size:1rem}}@media screen and (min-width:87.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.splashscreen-dillinger{width:800px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#editor{font-size:1rem}}</style></head><body id="preview"> <p>When you encounter a bug, I encourage you to follow these steps to make it easier for me to troubleshoot. <ol> <li>Can you start a new instance of Happypanda and reproduce the bug? <ul> <li>If that’s not the case then skip the steps below and go to <strong>How to report</strong> <ol> <li>First close all instances of Happypanda.</li> <li>Open a command prompt *(terminal in <em>nix)</em> and navigate to where Happypanda is installed. <em>Eg.: <code>cd path/to/happypanda</code></em></li> <li>Now type the name of the main executable with a <code>-d</code> following, <em>eg.: <code>happypanda.exe -d</code> or <code>main.py -d</code> if you’re running from source.</em></li> <li>The program will now open and create a new file named <code>happypanda_debug.log</code></li> <li>Now you try to reproduce the error/bug</li> </ol> </li> </ul> </li> </ol> <h3><a id="How_to_report_12"></a>How to report</h3> <p>If you completed the steps above, make sure to include the <code>happypanda_debug.log</code> file which was created and a description of how you reproduced the error/bug.</p> <ol> <li>Navigate to where you installed Happypanda with a file explorer and find <code>happypanda.log</code>. Send it to me with a description of the bug.</li> <li>You have 3 options of contacting me: <ul> <li>Go to the github repo <a href="https://github.com/Pewpews/happypanda/issues">issue page</a> and create a new issue</li> <li>Enter the gitter chat <a href="https://gitter.im/Pewpews/happypanda">here</a> and tell me about your issue</li> <li>If for some reason you don’t want anything to do with github, feel free to email me: <code>happypandabugs@gmail.com</code></li> </ul> </li> </ol> </body></html> """ ) SEARCH_TUTORIAL_TAGS = ( """ <!DOCTYPE html><html><head><meta charset="utf-8"><title>Untitled Document.md</title><style>@import 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.2.0/katex.min.css';code{color:#c7254e;background-color:#f9f2f4;border-radius:4px}code,kbd{padding:2px 4px}kbd{color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;box-shadow:none}pre{display:block;margin:0 0 10px;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}fieldset{border:0;min-width:0}legend{display:block;width:100%;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type="radio"],input[type="checkbox"]{margin:1px 0 0;line-height:normal}input[type="file"]{display:block}input[type="range"]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{padding-top:7px}output,.form-control{display:block;font-size:14px;line-height:1.4285714;color:#555}.form-control{width:100%;height:34px;padding:6px 12px;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#777;opacity:1}.form-control:-ms-input-placeholder{color:#777}.form-control::-webkit-input-placeholder{color:#777}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type="date"],input[type="time"],input[type="datetime-local"],input[type="month"]{line-height:34px;line-height:1.4285714 \0}input[type="date"].input-sm,.form-horizontal .form-group-sm input[type="date"].form-control,.input-group-sm>input[type="date"].form-control,.input-group-sm>input[type="date"].input-group-addon,.input-group-sm>.input-group-btn>input[type="date"].btn,input[type="time"].input-sm,.form-horizontal .form-group-sm input[type="time"].form-control,.input-group-sm>input[type="time"].form-control,.input-group-sm>input[type="time"].input-group-addon,.input-group-sm>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-sm,.form-horizontal .form-group-sm input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].input-group-addon,.input-group-sm>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-sm,.form-horizontal .form-group-sm input[type="month"].form-control,.input-group-sm>input[type="month"].form-control,.input-group-sm>input[type="month"].input-group-addon,.input-group-sm>.input-group-btn>input[type="month"].btn{line-height:30px}input[type="date"].input-lg,.form-horizontal .form-group-lg input[type="date"].form-control,.input-group-lg>input[type="date"].form-control,.input-group-lg>input[type="date"].input-group-addon,.input-group-lg>.input-group-btn>input[type="date"].btn,input[type="time"].input-lg,.form-horizontal .form-group-lg input[type="time"].form-control,.input-group-lg>input[type="time"].form-control,.input-group-lg>input[type="time"].input-group-addon,.input-group-lg>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-lg,.form-horizontal .form-group-lg input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].input-group-addon,.input-group-lg>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-lg,.form-horizontal .form-group-lg input[type="month"].form-control,.input-group-lg>input[type="month"].form-control,.input-group-lg>input[type="month"].input-group-addon,.input-group-lg>.input-group-btn>input[type="month"].btn{line-height:46px}.form-group{margin-bottom:15px}.radio,.checkbox{position:relative;display:block;min-height:20px;margin-top:10px;margin-bottom:10px}.radio label,.checkbox label{padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{position:absolute;margin-left:-20px;margin-top:4px \9}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="radio"].disabled,fieldset[disabled] input[type="radio"],input[type="checkbox"][disabled],input[type="checkbox"].disabled,fieldset[disabled] input[type="checkbox"],.radio-inline.disabled,fieldset[disabled] .radio-inline,.checkbox-inline.disabled,fieldset[disabled] .checkbox-inline,.radio.disabled label,fieldset[disabled] .radio label,.checkbox.disabled label,fieldset[disabled] .checkbox label{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-horizontal .form-group-lg .form-control-static.form-control,.input-group-lg>.form-control-static.form-control,.input-group-lg>.form-control-static.input-group-addon,.input-group-lg>.input-group-btn>.form-control-static.btn,.form-control-static.input-sm,.form-horizontal .form-group-sm .form-control-static.form-control,.input-group-sm>.form-control-static.form-control,.input-group-sm>.form-control-static.input-group-addon,.input-group-sm>.input-group-btn>.form-control-static.btn{padding-left:0;padding-right:0}.input-sm,.form-horizontal .form-group-sm .form-control,.input-group-sm>.form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.input-group-sm>.input-group-addon{height:30px;line-height:1.5}.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm,.form-horizontal .form-group-sm select.form-control,.input-group-sm>select.form-control,.input-group-sm>select.input-group-addon,.input-group-sm>.input-group-btn>select.btn{height:30px;line-height:30px}textarea.input-sm,.form-horizontal .form-group-sm textarea.form-control,.input-group-sm>textarea.form-control,.input-group-sm>textarea.input-group-addon,.input-group-sm>.input-group-btn>textarea.btn,select[multiple].input-sm,.form-horizontal .form-group-sm select[multiple].form-control,.input-group-sm>select[multiple].form-control,.input-group-sm>select[multiple].input-group-addon,.input-group-sm>.input-group-btn>select[multiple].btn{height:auto}.input-lg,.form-horizontal .form-group-lg .form-control,.input-group-lg>.form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.input-group-lg>.input-group-addon{height:46px;line-height:1.33}.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg,.form-horizontal .form-group-lg select.form-control,.input-group-lg>select.form-control,.input-group-lg>select.input-group-addon,.input-group-lg>.input-group-btn>select.btn{height:46px;line-height:46px}textarea.input-lg,.form-horizontal .form-group-lg textarea.form-control,.input-group-lg>textarea.form-control,.input-group-lg>textarea.input-group-addon,.input-group-lg>.input-group-btn>textarea.btn,select[multiple].input-lg,.form-horizontal .form-group-lg select[multiple].form-control,.input-group-lg>select[multiple].form-control,.input-group-lg>select[multiple].input-group-addon,.input-group-lg>.input-group-btn>select[multiple].btn{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:25px;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center}.input-lg+.form-control-feedback,.form-horizontal .form-group-lg .form-control+.form-control-feedback,.input-group-lg>.form-control+.form-control-feedback,.input-group-lg>.input-group-addon+.form-control-feedback,.input-group-lg>.input-group-btn>.btn+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback,.form-horizontal .form-group-sm .form-control+.form-control-feedback,.input-group-sm>.form-control+.form-control-feedback,.input-group-sm>.input-group-addon+.form-control-feedback,.input-group-sm>.input-group-btn>.btn+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-group:before{content:" ";display:table}.form-horizontal .form-group:after{content:" ";display:table;clear:both}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}.btn{display:inline-block;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{outline:0;background-image:none;box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{background-image:none}.btn-default.disabled,.btn-default.disabled:hover,.btn-default.disabled:focus,.btn-default.disabled:active,.btn-default.disabled.active,.btn-default[disabled],.btn-default[disabled]:hover,.btn-default[disabled]:focus,.btn-default[disabled]:active,.btn-default[disabled].active,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default:hover,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{color:#fff;background-color:#3071a9;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{background-image:none}.btn-primary.disabled,.btn-primary.disabled:hover,.btn-primary.disabled:focus,.btn-primary.disabled:active,.btn-primary.disabled.active,.btn-primary[disabled],.btn-primary[disabled]:hover,.btn-primary[disabled]:focus,.btn-primary[disabled]:active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary:hover,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{color:#fff;background-color:#449d44;border-color:#398439}.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{background-image:none}.btn-success.disabled,.btn-success.disabled:hover,.btn-success.disabled:focus,.btn-success.disabled:active,.btn-success.disabled.active,.btn-success[disabled],.btn-success[disabled]:hover,.btn-success[disabled]:focus,.btn-success[disabled]:active,.btn-success[disabled].active,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success:hover,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{background-image:none}.btn-info.disabled,.btn-info.disabled:hover,.btn-info.disabled:focus,.btn-info.disabled:active,.btn-info.disabled.active,.btn-info[disabled],.btn-info[disabled]:hover,.btn-info[disabled]:focus,.btn-info[disabled]:active,.btn-info[disabled].active,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info:hover,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{background-image:none}.btn-warning.disabled,.btn-warning.disabled:hover,.btn-warning.disabled:focus,.btn-warning.disabled:active,.btn-warning.disabled.active,.btn-warning[disabled],.btn-warning[disabled]:hover,.btn-warning[disabled]:focus,.btn-warning[disabled]:active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning:hover,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{background-image:none}.btn-danger.disabled,.btn-danger.disabled:hover,.btn-danger.disabled:focus,.btn-danger.disabled:active,.btn-danger.disabled.active,.btn-danger[disabled],.btn-danger[disabled]:hover,.btn-danger[disabled]:focus,.btn-danger[disabled]:active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger:hover,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{color:#428bca;font-weight:400;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:hover,fieldset[disabled] .btn-link:focus{color:#777;text-decoration:none}.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm{padding:5px 10px}.btn-sm,.btn-xs{font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*="col-"]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon{white-space:nowrap}.input-group-addon,.input-group-btn{width:1%;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm,.form-horizontal .form-group-sm .input-group-addon.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.input-group-addon.btn{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg,.form-horizontal .form-group-lg .input-group-addon.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.input-group-addon.btn{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{font-size:0;white-space:nowrap}.input-group-btn,.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.4285714;text-decoration:none;color:#428bca;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>li>span:hover,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:hover,.pagination>.active>a:focus,.pagination>.active>span,.pagination>.active>span:hover,.pagination>.active>span:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca;cursor:default}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.modal-open,.modal{overflow:hidden}.modal{display:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate3d(0,-25%,0);transform:translate3d(0,-25%,0);-webkit-transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.4285714px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.4285714}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{content:" ";display:table}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.clearfix:before,.clearfix:after{content:" ";display:table}.clearfix:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.hljs{display:block;overflow-x:auto;padding:.5em;background:#002b36;color:#839496;-webkit-text-size-adjust:none}.hljs-comment,.hljs-template_comment,.diff .hljs-header,.hljs-doctype,.hljs-pi,.lisp .hljs-string,.hljs-javadoc{color:#586e75}.hljs-keyword,.hljs-winutils,.method,.hljs-addition,.css .hljs-tag,.hljs-request,.hljs-status,.nginx .hljs-title{color:#859900}.hljs-number,.hljs-command,.hljs-string,.hljs-tag .hljs-value,.hljs-rules .hljs-value,.hljs-phpdoc,.hljs-dartdoc,.tex .hljs-formula,.hljs-regexp,.hljs-hexcolor,.hljs-link_url{color:#2aa198}.hljs-title,.hljs-localvars,.hljs-chunk,.hljs-decorator,.hljs-built_in,.hljs-identifier,.vhdl .hljs-literal,.hljs-id,.css .hljs-function{color:#268bd2}.hljs-attribute,.hljs-variable,.lisp .hljs-body,.smalltalk .hljs-number,.hljs-constant,.hljs-class .hljs-title,.hljs-parent,.hljs-type,.hljs-link_reference{color:#b58900}.hljs-preprocessor,.hljs-preprocessor .hljs-keyword,.hljs-pragma,.hljs-shebang,.hljs-symbol,.hljs-symbol .hljs-string,.diff .hljs-change,.hljs-special,.hljs-attr_selector,.hljs-subst,.hljs-cdata,.css .hljs-pseudo,.hljs-header{color:#cb4b16}.hljs-deletion,.hljs-important{color:#dc322f}.hljs-link_label{color:#6c71c4}.tex .hljs-formula{background:#073642}*,*:before,*:after{box-sizing:border-box}html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}images{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{box-sizing:content-box;height:0}pre{overflow:auto}code,kbd{font-size:1em}code,kbd,pre,samp{font-family:monospace,monospace}samp{font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}.debug{background-color:#ffc0cb!important}.ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ir{background-color:transparent;border:0;overflow:hidden}.ir::before{content:'';display:block;height:150%;width:0}html{font-size:.875em;background:#fafafa;color:#373D49}html,body{font-family:Georgia,Cambria,serif;height:100%}body{font-size:1rem;font-weight:400;line-height:2rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}li{-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-left:1rem}li>ul,li>ol{margin-bottom:0}p{padding-top:.66001rem;-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-top:0}p,pre{margin-bottom:1.33999rem}pre{font-size:1rem;padding:.66001rem 9.5px 9.5px;line-height:2rem;background:-webkit-linear-gradient(top,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background:linear-gradient(to bottom,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background-size:100% 4rem;border-color:#D3DAEA}blockquote{margin:0}blockquote p{font-size:1rem;margin-bottom:.33999rem;font-style:italic;padding:.66001rem 1rem 1rem;border-left:3px solid #A0AABF}th,td{padding:12px}h1,h2,h3,h4,h5,h6{font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;-webkit-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;-moz-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-style:normal;font-weight:600;margin-top:0}h1{line-height:3rem;font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h2,h3{line-height:3rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}a{cursor:pointer;color:#35D7BB;text-decoration:none}a:hover,a:focus{border-bottom-color:#35D7BB;color:#dff9f4}img{height:auto;max-width:100%}.g{display:block}.g:after{clear:both;content:'';display:table}.g-b{float:left;margin:0;width:100%}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--center{display:block;float:none;margin:0 auto}.g-b--right{float:right}.g-b--1of1{width:100%}.g-b--1of2,.g-b--2of4,.g-b--3of6,.g-b--4of8,.g-b--5of10,.g-b--6of12{width:50%}.g-b--1of3,.g-b--2of6,.g-b--4of12{width:33.333%}.g-b--2of3,.g-b--4of6,.g-b--8of12{width:66.666%}.g-b--1of4,.g-b--2of8,.g-b--3of12{width:25%}.g-b--3of4,.g-b--6of8,.g-b--9of12{width:75%}.g-b--1of5,.g-b--2of10{width:20%}.g-b--2of5,.g-b--4of10{width:40%}.g-b--3of5,.g-b--6of10{width:60%}.g-b--4of5,.g-b--8of10{width:80%}.g-b--1of6,.g-b--2of12{width:16.666%}.g-b--5of6,.g-b--10of12{width:83.333%}.g-b--1of8{width:12.5%}.g-b--3of8{width:37.5%}.g-b--5of8{width:62.5%}.g-b--7of8{width:87.5%}.g-b--1of10{width:10%}.g-b--3of10{width:30%}.g-b--7of10{width:70%}.g-b--9of10{width:90%}.g-b--1of12{width:8.333%}.g-b--5of12{width:41.666%}.g-b--7of12{width:58.333%}.g-b--11of12{width:91.666%}.g-b--push--1of1{margin-left:100%}.g-b--push--1of2,.g-b--push--2of4,.g-b--push--3of6,.g-b--push--4of8,.g-b--push--5of10,.g-b--push--6of12{margin-left:50%}.g-b--push--1of3,.g-b--push--2of6,.g-b--push--4of12{margin-left:33.333%}.g-b--push--2of3,.g-b--push--4of6,.g-b--push--8of12{margin-left:66.666%}.g-b--push--1of4,.g-b--push--2of8,.g-b--push--3of12{margin-left:25%}.g-b--push--3of4,.g-b--push--6of8,.g-b--push--9of12{margin-left:75%}.g-b--push--1of5,.g-b--push--2of10{margin-left:20%}.g-b--push--2of5,.g-b--push--4of10{margin-left:40%}.g-b--push--3of5,.g-b--push--6of10{margin-left:60%}.g-b--push--4of5,.g-b--push--8of10{margin-left:80%}.g-b--push--1of6,.g-b--push--2of12{margin-left:16.666%}.g-b--push--5of6,.g-b--push--10of12{margin-left:83.333%}.g-b--push--1of8{margin-left:12.5%}.g-b--push--3of8{margin-left:37.5%}.g-b--push--5of8{margin-left:62.5%}.g-b--push--7of8{margin-left:87.5%}.g-b--push--1of10{margin-left:10%}.g-b--push--3of10{margin-left:30%}.g-b--push--7of10{margin-left:70%}.g-b--push--9of10{margin-left:90%}.g-b--push--1of12{margin-left:8.333%}.g-b--push--5of12{margin-left:41.666%}.g-b--push--7of12{margin-left:58.333%}.g-b--push--11of12{margin-left:91.666%}.g-b--pull--1of1{margin-right:100%}.g-b--pull--1of2,.g-b--pull--2of4,.g-b--pull--3of6,.g-b--pull--4of8,.g-b--pull--5of10,.g-b--pull--6of12{margin-right:50%}.g-b--pull--1of3,.g-b--pull--2of6,.g-b--pull--4of12{margin-right:33.333%}.g-b--pull--2of3,.g-b--pull--4of6,.g-b--pull--8of12{margin-right:66.666%}.g-b--pull--1of4,.g-b--pull--2of8,.g-b--pull--3of12{margin-right:25%}.g-b--pull--3of4,.g-b--pull--6of8,.g-b--pull--9of12{margin-right:75%}.g-b--pull--1of5,.g-b--pull--2of10{margin-right:20%}.g-b--pull--2of5,.g-b--pull--4of10{margin-right:40%}.g-b--pull--3of5,.g-b--pull--6of10{margin-right:60%}.g-b--pull--4of5,.g-b--pull--8of10{margin-right:80%}.g-b--pull--1of6,.g-b--pull--2of12{margin-right:16.666%}.g-b--pull--5of6,.g-b--pull--10of12{margin-right:83.333%}.g-b--pull--1of8{margin-right:12.5%}.g-b--pull--3of8{margin-right:37.5%}.g-b--pull--5of8{margin-right:62.5%}.g-b--pull--7of8{margin-right:87.5%}.g-b--pull--1of10{margin-right:10%}.g-b--pull--3of10{margin-right:30%}.g-b--pull--7of10{margin-right:70%}.g-b--pull--9of10{margin-right:90%}.g-b--pull--1of12{margin-right:8.333%}.g-b--pull--5of12{margin-right:41.666%}.g-b--pull--7of12{margin-right:58.333%}.g-b--pull--11of12{margin-right:91.666%}.splashscreen{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#373D49;z-index:22}.splashscreen-dillinger{width:260px;height:auto;display:block;margin:0 auto;padding-bottom:3rem}.splashscreen p{font-size:1.25rem;padding-top:.56251rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;text-align:center;max-width:500px;margin:0 auto;color:#FFF}.sp-center{position:relative;-webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%);top:50%}.open-menu>.wrapper{overflow-x:hidden}.page{margin:0 auto;position:relative;top:0;left:0;width:100%;height:100%;z-index:2;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;background-color:#fff;padding-top:51px;will-change:left}.open-menu .page{left:270px}.title{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;padding-left:16px;padding-right:16px;margin-top:1rem}.split-preview .title{padding-left:0}.title-document{line-height:1rem;font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem;font-weight:400;font-family:"Ubuntu Mono",Monaco;color:#373D49;padding-left:16px;padding-right:16px;width:80%;min-width:300px;outline:0;border:none}.icon{display:block;margin:0 auto;width:36px;height:36px;border-radius:3px;text-align:center}.icon svg{display:inline-block;margin-left:auto;margin-right:auto}.icon-preview{background-color:#373D49;line-height:40px}.icon-preview svg{width:19px;height:12px}.icon-settings{background-color:#373D49;line-height:44px}.icon-settings svg{width:18px;height:18px}.icon-link{width:16px;height:16px;line-height:1;margin-right:24px;text-align:right}.navbar{background-color:#373D49;height:51px;width:100%;position:fixed;top:0;left:0;z-index:6;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;will-change:left}.navbar:after{content:"";display:table;clear:both}.open-menu .navbar{left:270px}.navbar-brand{float:left;margin:0 0 0 24px;padding:0;line-height:42px}.navbar-brand svg{width:85px;height:11px}.nav-left{float:left}.nav-right{float:right}.nav-sidebar{width:100%}.menu{list-style:none;margin:0;padding:0}.menu a{border:0;color:#A0AABF;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;outline:none;text-transform:uppercase}.menu a:hover{color:#35D7BB}.menu .menu-item{border:0;display:none;float:left;margin:0;position:relative}.menu .menu-item>a{display:block;font-size:12px;height:51px;letter-spacing:1px;line-height:51px;padding:0 24px}.menu .menu-item--settings,.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar,.menu .menu-item--link-unlink.in-sidebar,.menu .menu-item--documents.in-sidebar{display:block}.menu .menu-item--documents{padding-bottom:1rem}.menu .menu-item.open>a{background-color:#1D212A}.menu .menu-item-icon>a{height:auto;padding:0}.menu .menu-item-icon:hover>a{background-color:transparent}.menu .menu-link.open i{background-color:#1D212A}.menu .menu-link.open g{fill:#35D7BB}.menu .menu-link-preview,.menu .menu-link-settings{margin-top:8px;width:51px}.menu-sidebar{width:100%}.menu-sidebar .menu-item{float:none;margin-bottom:1px;width:100%}.menu-sidebar .menu-item.open>a{background-color:#373D49}.menu-sidebar .open .caret{-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.menu-sidebar>.menu-item:hover .dropdown a,.menu-sidebar>.menu-item:hover .settings a{background-color:transparent}.menu-sidebar .menu-link{background-color:#373D49;font-weight:600}.menu-sidebar .menu-link:after{content:"";display:table;clear:both}.menu-sidebar .menu-link>span{float:left}.menu-sidebar .menu-link>.caret{float:right;text-align:right;top:22px}.menu-sidebar .dropdown,.menu-sidebar .settings{background-color:transparent;position:static;width:100%}.dropdown{position:absolute;right:0;top:51px;width:188px}.dropdown,.settings{display:none;background-color:#1D212A}.dropdown{padding:0}.dropdown,.settings,.sidebar-list{list-style:none;margin:0}.sidebar-list{padding:0}.dropdown li{margin:32px 0;padding:0 0 0 32px}.dropdown li,.settings li{line-height:1}.sidebar-list li{line-height:1;margin:32px 0;padding:0 0 0 32px}.dropdown a{color:#D0D6E2}.dropdown a,.settings a,.sidebar-list a{display:block;text-transform:none}.sidebar-list a{color:#D0D6E2}.dropdown a:after,.settings a:after,.sidebar-list a:after{content:"";display:table;clear:both}.dropdown .icon,.settings .icon,.sidebar-list .icon{float:right}.open .dropdown,.open .settings,.open .sidebar-list{display:block}.open .dropdown.collapse,.open .collapse.settings,.open .sidebar-list.collapse{display:none}.open .dropdown.collapse.in,.open .collapse.in.settings,.open .sidebar-list.collapse.in{display:block}.dropdown .unlinked .icon,.settings .unlinked .icon,.sidebar-list .unlinked .icon{opacity:.3}.dropdown.documents li,.documents.settings li,.sidebar-list.documents li{background-image:url("../img/icons/file.svg");background-position:240px center;background-repeat:no-repeat;background-size:14px 16px;padding:3px 32px}.dropdown.documents li.octocat,.documents.settings li.octocat,.sidebar-list.documents li.octocat{background-image:url("../img/icons/octocat.svg");background-position:234px center;background-size:24px 24px}.dropdown.documents li:last-child,.documents.settings li:last-child,.sidebar-list.documents li:last-child{margin-bottom:1rem}.dropdown.documents li.active a,.documents.settings li.active a,.sidebar-list.documents li.active a{color:#35D7BB}.settings{position:fixed;top:67px;right:16px;border-radius:3px;width:288px;background-color:#373D49;padding:16px;z-index:7}.show-settings .settings{display:block}.settings .has-checkbox{float:left}.settings a{font-size:1.25rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;-webkit-font-smoothing:antialiased;line-height:28px;color:#D0D6E2}.settings a:after{content:"";display:table;clear:both}.settings a:hover{color:#35D7BB}.settings li{border-bottom:1px solid #4F535B;margin:0;padding:16px 0}.settings li:last-child{border-bottom:none}.brand{border:none;display:block}.brand:hover g{fill:#35D7BB}.toggle{display:block;float:left;height:16px;padding:25px 16px 26px;width:40px}.toggle span:after,.toggle span:before{content:'';left:0;position:absolute;top:-6px}.toggle span:after{top:6px}.toggle span{display:block;position:relative}.toggle span,.toggle span:after,.toggle span:before{-webkit-backface-visibility:hidden;backface-visibility:hidden;background-color:#D3DAEA;height:2px;-webkit-transition:all .3s;transition:all .3s;width:20px}.open-menu .toggle span{background-color:transparent}.open-menu .toggle span:before{-webkit-transform:rotate(45deg)translate(3px,3px);-ms-transform:rotate(45deg)translate(3px,3px);transform:rotate(45deg)translate(3px,3px)}.open-menu .toggle span:after{-webkit-transform:rotate(-45deg)translate(5px,-6px);-ms-transform:rotate(-45deg)translate(5px,-6px);transform:rotate(-45deg)translate(5px,-6px)}.caret{display:inline-block;width:0;height:0;margin-left:6px;vertical-align:middle;position:relative;top:-1px;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.sidebar{overflow:auto;height:100%;padding-right:15px;padding-bottom:15px;width:285px}.sidebar-wrapper{-webkit-overflow-scrolling:touch;background-color:#2B2F36;left:0;height:100%;overflow-y:hidden;position:fixed;top:0;width:285px;z-index:1}.sidebar-branding{width:160px;padding:0;margin:16px auto}.header{border-bottom:1px solid #E8E8E8;position:relative}.words{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;z-index:5;position:absolute;right:16px;top:0}.words span{color:#000}.btn{text-align:center;display:inline-block;width:100%;text-transform:uppercase;font-weight:600;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;text-shadow:0 1px 0 #1b8b77;padding:16px 24px;background-color:#35D7BB;border-radius:3px;margin:0 auto 16px;line-height:1;color:#fff;-webkit-transition:all .15s linear;transition:all .15s linear;-webkit-font-smoothing:antialiased}.btn--new,.btn--save{display:block;width:238px}.btn--new:hover,.btn--new:focus,.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 3px #24b59c;text-shadow:0 1px 0 #24b59c}.btn--save{background-color:#4A5261;text-shadow:0 1px 1px #1e2127}.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 5px #08090a;text-shadow:none}.btn--delete{display:block;width:238px;background-color:transparent;font-size:12px;text-shadow:none}.btn--delete:hover,.btn--delete:focus{color:#fff;border-bottom-color:transparent;text-shadow:0 1px 0 #08090a;opacity:.8}.btn--ok,.btn--close{border-top:0;background-color:#4A5261;text-shadow:0 1px 0 #08090a;margin:0}.btn--ok:hover,.btn--ok:focus,.btn--close:hover,.btn--close:focus{color:#fff;background-color:#292d36;text-shadow:none}.overlay{position:absolute;top:0;left:0;width:100%;height:100%;background-color:rgba(55,61,73,.8);-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;-webkit-transition-timing-function:ease-out;transition-timing-function:ease-out;will-change:left,opacity,visibility;z-index:5;opacity:0;visibility:hidden}.show-settings .overlay{visibility:visible;opacity:1}.switch{float:right;line-height:1}.switch input{display:none}.switch small{display:inline-block;cursor:pointer;padding:0 24px 0 0;-webkit-transition:all ease .2s;transition:all ease .2s;background-color:#2B2F36;border-color:#2B2F36}.switch small,.switch small:before{border-radius:30px;box-shadow:inset 0 0 2px 0 #14171F}.switch small:before{display:block;content:'';width:28px;height:28px;background:#fff}.switch.checked small{padding-right:0;padding-left:24px;background-color:#35D7BB;box-shadow:none}.modal--dillinger.about .modal-dialog{font-size:1.25rem;max-width:500px}.modal--dillinger .modal-dialog{max-width:600px;width:auto;margin:5rem auto}.modal--dillinger .modal-content{background:#373D49;border-radius:3px;box-shadow:0 2px 5px 0 #2C3B59;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;padding:2rem}.modal--dillinger ul{list-style-type:disc;margin:1rem 0;padding:0 0 0 1rem}.modal--dillinger li{padding:0;margin:0}.modal--dillinger .modal-header{border:0;padding:0}.modal--dillinger .modal-body{padding:0}.modal--dillinger .modal-footer{border:0;padding:0}.modal--dillinger .close{color:#fff;opacity:1}.modal-backdrop{background-color:#373D49}.pagination--dillinger{padding:0!important;margin:1.5rem 0!important;-webkit-box-pack:justify;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;-webkit-align-content:stretch;-ms-flex-line-pack:stretch;align-content:stretch}.pagination--dillinger,.pagination--dillinger li{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex}.pagination--dillinger li{-webkit-box-flex:1;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;text-align:center}.pagination--dillinger li:first-child>a,.pagination--dillinger li.disabled>a,.pagination--dillinger li.disabled>a:hover,.pagination--dillinger li.disabled>a:focus,.pagination--dillinger li>a{background-color:transparent;border-color:#4F535B;border-right-color:transparent}.pagination--dillinger li.active>a,.pagination--dillinger li.active>a:hover,.pagination--dillinger li.active>a:focus{border-color:#4A5261;background-color:#4A5261;color:#fff}.pagination--dillinger li>a{float:none;color:#fff;width:100%;display:block;text-align:center;margin:0;border-right-color:transparent;padding:6px}.pagination--dillinger li>a:hover,.pagination--dillinger li>a:focus{border-color:#35D7BB;background-color:#35D7BB;color:#fff}.pagination--dillinger li:last-child a{border-color:#4F535B}.pagination--dillinger li:first-child a{border-right-color:transparent}.diNotify{position:absolute;z-index:9999;left:0;right:0;top:0;margin:0 auto;max-width:400px;text-align:center;-webkit-transition:top .5s ease-in-out,opacity .5s ease-in-out;transition:top .5s ease-in-out,opacity .5s ease-in-out;visibility:hidden}.diNotify-body{-webkit-font-smoothing:antialiased;background-color:#35D7BB;background:#666E7F;border-radius:3px;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;overflow:hidden;padding:1rem 2rem .5rem;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:baseline;-webkit-align-items:baseline;-ms-flex-align:baseline;align-items:baseline;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center}.diNotify-icon{display:block;width:16px;height:16px;line-height:16px;position:relative;top:3px}.diNotify-message{padding-left:1rem}.zen-wrapper{position:fixed;top:0;left:0;right:0;bottom:0;width:100%;height:100%;z-index:10;background-color:#FFF;opacity:0;-webkit-transition:opacity .25s ease-in-out;transition:opacity .25s ease-in-out}.zen-wrapper.on{opacity:1}.enter-zen-mode{background-image:url("../img/icons/enter-zen.svg");right:.5rem;top:.5rem;display:none}.enter-zen-mode,.close-zen-mode{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;background-repeat:no-repeat;width:32px;height:32px;display:block;position:absolute}.close-zen-mode{background-image:url("../img/icons/exit-zen.svg");right:1rem;top:1rem}.zen-page{position:relative;top:0;bottom:0;z-index:11;height:100%;width:100%}#zen{font-size:1.25rem;width:300px;height:80%;margin:0 auto;position:relative;top:10%}#zen:before,#zen:after{content:"";position:absolute;height:10%;width:100%;z-index:12;pointer-events:none}.split{overflow:scroll;padding:0!important}.split-editor{padding-left:0;padding-right:0;position:relative}.show-preview .split-editor{display:none}.split-preview{background-color:#fff;display:none;top:0;position:relative;z-index:4}.show-preview .split-preview{display:block}#editor{font-size:1rem;font-family:"Ubuntu Mono",Monaco;font-weight:400;line-height:2rem;width:100%;height:100%}#editor .ace_gutter{-webkit-font-smoothing:antialiased}#preview a{color:#A0AABF;text-decoration:underline}.sr-only{visibility:hidden;text-overflow:110%;overflow:hidden;top:-100px;position:absolute}.mnone{margin:0!important}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .radio label,.form-inline .checkbox label{padding-left:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}.form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}.form-horizontal .form-group-lg .control-label{padding-top:14.3px}.form-horizontal .form-group-sm .control-label{padding-top:6px}.modal-dialog{width:600px;margin:30px auto}.modal-content{box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}@media screen and (min-width:27.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--m1of1{width:100%}.g-b--m1of2,.g-b--m2of4,.g-b--m3of6,.g-b--m4of8,.g-b--m5of10,.g-b--m6of12{width:50%}.g-b--m1of3,.g-b--m2of6,.g-b--m4of12{width:33.333%}.g-b--m2of3,.g-b--m4of6,.g-b--m8of12{width:66.666%}.g-b--m1of4,.g-b--m2of8,.g-b--m3of12{width:25%}.g-b--m3of4,.g-b--m6of8,.g-b--m9of12{width:75%}.g-b--m1of5,.g-b--m2of10{width:20%}.g-b--m2of5,.g-b--m4of10{width:40%}.g-b--m3of5,.g-b--m6of10{width:60%}.g-b--m4of5,.g-b--m8of10{width:80%}.g-b--m1of6,.g-b--m2of12{width:16.666%}.g-b--m5of6,.g-b--m10of12{width:83.333%}.g-b--m1of8{width:12.5%}.g-b--m3of8{width:37.5%}.g-b--m5of8{width:62.5%}.g-b--m7of8{width:87.5%}.g-b--m1of10{width:10%}.g-b--m3of10{width:30%}.g-b--m7of10{width:70%}.g-b--m9of10{width:90%}.g-b--m1of12{width:8.333%}.g-b--m5of12{width:41.666%}.g-b--m7of12{width:58.333%}.g-b--m11of12{width:91.666%}.g-b--push--m1of1{margin-left:100%}.g-b--push--m1of2,.g-b--push--m2of4,.g-b--push--m3of6,.g-b--push--m4of8,.g-b--push--m5of10,.g-b--push--m6of12{margin-left:50%}.g-b--push--m1of3,.g-b--push--m2of6,.g-b--push--m4of12{margin-left:33.333%}.g-b--push--m2of3,.g-b--push--m4of6,.g-b--push--m8of12{margin-left:66.666%}.g-b--push--m1of4,.g-b--push--m2of8,.g-b--push--m3of12{margin-left:25%}.g-b--push--m3of4,.g-b--push--m6of8,.g-b--push--m9of12{margin-left:75%}.g-b--push--m1of5,.g-b--push--m2of10{margin-left:20%}.g-b--push--m2of5,.g-b--push--m4of10{margin-left:40%}.g-b--push--m3of5,.g-b--push--m6of10{margin-left:60%}.g-b--push--m4of5,.g-b--push--m8of10{margin-left:80%}.g-b--push--m1of6,.g-b--push--m2of12{margin-left:16.666%}.g-b--push--m5of6,.g-b--push--m10of12{margin-left:83.333%}.g-b--push--m1of8{margin-left:12.5%}.g-b--push--m3of8{margin-left:37.5%}.g-b--push--m5of8{margin-left:62.5%}.g-b--push--m7of8{margin-left:87.5%}.g-b--push--m1of10{margin-left:10%}.g-b--push--m3of10{margin-left:30%}.g-b--push--m7of10{margin-left:70%}.g-b--push--m9of10{margin-left:90%}.g-b--push--m1of12{margin-left:8.333%}.g-b--push--m5of12{margin-left:41.666%}.g-b--push--m7of12{margin-left:58.333%}.g-b--push--m11of12{margin-left:91.666%}.g-b--pull--m1of1{margin-right:100%}.g-b--pull--m1of2,.g-b--pull--m2of4,.g-b--pull--m3of6,.g-b--pull--m4of8,.g-b--pull--m5of10,.g-b--pull--m6of12{margin-right:50%}.g-b--pull--m1of3,.g-b--pull--m2of6,.g-b--pull--m4of12{margin-right:33.333%}.g-b--pull--m2of3,.g-b--pull--m4of6,.g-b--pull--m8of12{margin-right:66.666%}.g-b--pull--m1of4,.g-b--pull--m2of8,.g-b--pull--m3of12{margin-right:25%}.g-b--pull--m3of4,.g-b--pull--m6of8,.g-b--pull--m9of12{margin-right:75%}.g-b--pull--m1of5,.g-b--pull--m2of10{margin-right:20%}.g-b--pull--m2of5,.g-b--pull--m4of10{margin-right:40%}.g-b--pull--m3of5,.g-b--pull--m6of10{margin-right:60%}.g-b--pull--m4of5,.g-b--pull--m8of10{margin-right:80%}.g-b--pull--m1of6,.g-b--pull--m2of12{margin-right:16.666%}.g-b--pull--m5of6,.g-b--pull--m10of12{margin-right:83.333%}.g-b--pull--m1of8{margin-right:12.5%}.g-b--pull--m3of8{margin-right:37.5%}.g-b--pull--m5of8{margin-right:62.5%}.g-b--pull--m7of8{margin-right:87.5%}.g-b--pull--m1of10{margin-right:10%}.g-b--pull--m3of10{margin-right:30%}.g-b--pull--m7of10{margin-right:70%}.g-b--pull--m9of10{margin-right:90%}.g-b--pull--m1of12{margin-right:8.333%}.g-b--pull--m5of12{margin-right:41.666%}.g-b--pull--m7of12{margin-right:58.333%}.g-b--pull--m11of12{margin-right:91.666%}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:400px}#editor{font-size:1rem}}@media screen and (min-width:46.25em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--t1of1{width:100%}.g-b--t1of2,.g-b--t2of4,.g-b--t3of6,.g-b--t4of8,.g-b--t5of10,.g-b--t6of12{width:50%}.g-b--t1of3,.g-b--t2of6,.g-b--t4of12{width:33.333%}.g-b--t2of3,.g-b--t4of6,.g-b--t8of12{width:66.666%}.g-b--t1of4,.g-b--t2of8,.g-b--t3of12{width:25%}.g-b--t3of4,.g-b--t6of8,.g-b--t9of12{width:75%}.g-b--t1of5,.g-b--t2of10{width:20%}.g-b--t2of5,.g-b--t4of10{width:40%}.g-b--t3of5,.g-b--t6of10{width:60%}.g-b--t4of5,.g-b--t8of10{width:80%}.g-b--t1of6,.g-b--t2of12{width:16.666%}.g-b--t5of6,.g-b--t10of12{width:83.333%}.g-b--t1of8{width:12.5%}.g-b--t3of8{width:37.5%}.g-b--t5of8{width:62.5%}.g-b--t7of8{width:87.5%}.g-b--t1of10{width:10%}.g-b--t3of10{width:30%}.g-b--t7of10{width:70%}.g-b--t9of10{width:90%}.g-b--t1of12{width:8.333%}.g-b--t5of12{width:41.666%}.g-b--t7of12{width:58.333%}.g-b--t11of12{width:91.666%}.g-b--push--t1of1{margin-left:100%}.g-b--push--t1of2,.g-b--push--t2of4,.g-b--push--t3of6,.g-b--push--t4of8,.g-b--push--t5of10,.g-b--push--t6of12{margin-left:50%}.g-b--push--t1of3,.g-b--push--t2of6,.g-b--push--t4of12{margin-left:33.333%}.g-b--push--t2of3,.g-b--push--t4of6,.g-b--push--t8of12{margin-left:66.666%}.g-b--push--t1of4,.g-b--push--t2of8,.g-b--push--t3of12{margin-left:25%}.g-b--push--t3of4,.g-b--push--t6of8,.g-b--push--t9of12{margin-left:75%}.g-b--push--t1of5,.g-b--push--t2of10{margin-left:20%}.g-b--push--t2of5,.g-b--push--t4of10{margin-left:40%}.g-b--push--t3of5,.g-b--push--t6of10{margin-left:60%}.g-b--push--t4of5,.g-b--push--t8of10{margin-left:80%}.g-b--push--t1of6,.g-b--push--t2of12{margin-left:16.666%}.g-b--push--t5of6,.g-b--push--t10of12{margin-left:83.333%}.g-b--push--t1of8{margin-left:12.5%}.g-b--push--t3of8{margin-left:37.5%}.g-b--push--t5of8{margin-left:62.5%}.g-b--push--t7of8{margin-left:87.5%}.g-b--push--t1of10{margin-left:10%}.g-b--push--t3of10{margin-left:30%}.g-b--push--t7of10{margin-left:70%}.g-b--push--t9of10{margin-left:90%}.g-b--push--t1of12{margin-left:8.333%}.g-b--push--t5of12{margin-left:41.666%}.g-b--push--t7of12{margin-left:58.333%}.g-b--push--t11of12{margin-left:91.666%}.g-b--pull--t1of1{margin-right:100%}.g-b--pull--t1of2,.g-b--pull--t2of4,.g-b--pull--t3of6,.g-b--pull--t4of8,.g-b--pull--t5of10,.g-b--pull--t6of12{margin-right:50%}.g-b--pull--t1of3,.g-b--pull--t2of6,.g-b--pull--t4of12{margin-right:33.333%}.g-b--pull--t2of3,.g-b--pull--t4of6,.g-b--pull--t8of12{margin-right:66.666%}.g-b--pull--t1of4,.g-b--pull--t2of8,.g-b--pull--t3of12{margin-right:25%}.g-b--pull--t3of4,.g-b--pull--t6of8,.g-b--pull--t9of12{margin-right:75%}.g-b--pull--t1of5,.g-b--pull--t2of10{margin-right:20%}.g-b--pull--t2of5,.g-b--pull--t4of10{margin-right:40%}.g-b--pull--t3of5,.g-b--pull--t6of10{margin-right:60%}.g-b--pull--t4of5,.g-b--pull--t8of10{margin-right:80%}.g-b--pull--t1of6,.g-b--pull--t2of12{margin-right:16.666%}.g-b--pull--t5of6,.g-b--pull--t10of12{margin-right:83.333%}.g-b--pull--t1of8{margin-right:12.5%}.g-b--pull--t3of8{margin-right:37.5%}.g-b--pull--t5of8{margin-right:62.5%}.g-b--pull--t7of8{margin-right:87.5%}.g-b--pull--t1of10{margin-right:10%}.g-b--pull--t3of10{margin-right:30%}.g-b--pull--t7of10{margin-right:70%}.g-b--pull--t9of10{margin-right:90%}.g-b--pull--t1of12{margin-right:8.333%}.g-b--pull--t5of12{margin-right:41.666%}.g-b--pull--t7of12{margin-right:58.333%}.g-b--pull--t11of12{margin-right:91.666%}.splashscreen-dillinger{width:500px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--save-to,.menu .menu-item--import-from{display:block}.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog{font-size:1.25rem}.enter-zen-mode{display:block}.close-zen-mode{right:3rem;top:3rem}#zen{font-size:1.25rem;width:500px}.split-editor{border-right:1px solid #E8E8E8;float:left;height:calc(100vh - 130px);-webkit-overflow-scrolling:touch;padding-right:16px;width:50%}.show-preview .split-editor{display:block}.split-preview{display:block;float:right;height:calc(100vh - 130px);-webkit-overflow-scrolling:touch;position:relative;top:0;width:50%}#editor{font-size:1rem}}@media screen and (min-width:62.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--d1of1{width:100%}.g-b--d1of2,.g-b--d2of4,.g-b--d3of6,.g-b--d4of8,.g-b--d5of10,.g-b--d6of12{width:50%}.g-b--d1of3,.g-b--d2of6,.g-b--d4of12{width:33.333%}.g-b--d2of3,.g-b--d4of6,.g-b--d8of12{width:66.666%}.g-b--d1of4,.g-b--d2of8,.g-b--d3of12{width:25%}.g-b--d3of4,.g-b--d6of8,.g-b--d9of12{width:75%}.g-b--d1of5,.g-b--d2of10{width:20%}.g-b--d2of5,.g-b--d4of10{width:40%}.g-b--d3of5,.g-b--d6of10{width:60%}.g-b--d4of5,.g-b--d8of10{width:80%}.g-b--d1of6,.g-b--d2of12{width:16.666%}.g-b--d5of6,.g-b--d10of12{width:83.333%}.g-b--d1of8{width:12.5%}.g-b--d3of8{width:37.5%}.g-b--d5of8{width:62.5%}.g-b--d7of8{width:87.5%}.g-b--d1of10{width:10%}.g-b--d3of10{width:30%}.g-b--d7of10{width:70%}.g-b--d9of10{width:90%}.g-b--d1of12{width:8.333%}.g-b--d5of12{width:41.666%}.g-b--d7of12{width:58.333%}.g-b--d11of12{width:91.666%}.g-b--push--d1of1{margin-left:100%}.g-b--push--d1of2,.g-b--push--d2of4,.g-b--push--d3of6,.g-b--push--d4of8,.g-b--push--d5of10,.g-b--push--d6of12{margin-left:50%}.g-b--push--d1of3,.g-b--push--d2of6,.g-b--push--d4of12{margin-left:33.333%}.g-b--push--d2of3,.g-b--push--d4of6,.g-b--push--d8of12{margin-left:66.666%}.g-b--push--d1of4,.g-b--push--d2of8,.g-b--push--d3of12{margin-left:25%}.g-b--push--d3of4,.g-b--push--d6of8,.g-b--push--d9of12{margin-left:75%}.g-b--push--d1of5,.g-b--push--d2of10{margin-left:20%}.g-b--push--d2of5,.g-b--push--d4of10{margin-left:40%}.g-b--push--d3of5,.g-b--push--d6of10{margin-left:60%}.g-b--push--d4of5,.g-b--push--d8of10{margin-left:80%}.g-b--push--d1of6,.g-b--push--d2of12{margin-left:16.666%}.g-b--push--d5of6,.g-b--push--d10of12{margin-left:83.333%}.g-b--push--d1of8{margin-left:12.5%}.g-b--push--d3of8{margin-left:37.5%}.g-b--push--d5of8{margin-left:62.5%}.g-b--push--d7of8{margin-left:87.5%}.g-b--push--d1of10{margin-left:10%}.g-b--push--d3of10{margin-left:30%}.g-b--push--d7of10{margin-left:70%}.g-b--push--d9of10{margin-left:90%}.g-b--push--d1of12{margin-left:8.333%}.g-b--push--d5of12{margin-left:41.666%}.g-b--push--d7of12{margin-left:58.333%}.g-b--push--d11of12{margin-left:91.666%}.g-b--pull--d1of1{margin-right:100%}.g-b--pull--d1of2,.g-b--pull--d2of4,.g-b--pull--d3of6,.g-b--pull--d4of8,.g-b--pull--d5of10,.g-b--pull--d6of12{margin-right:50%}.g-b--pull--d1of3,.g-b--pull--d2of6,.g-b--pull--d4of12{margin-right:33.333%}.g-b--pull--d2of3,.g-b--pull--d4of6,.g-b--pull--d8of12{margin-right:66.666%}.g-b--pull--d1of4,.g-b--pull--d2of8,.g-b--pull--d3of12{margin-right:25%}.g-b--pull--d3of4,.g-b--pull--d6of8,.g-b--pull--d9of12{margin-right:75%}.g-b--pull--d1of5,.g-b--pull--d2of10{margin-right:20%}.g-b--pull--d2of5,.g-b--pull--d4of10{margin-right:40%}.g-b--pull--d3of5,.g-b--pull--d6of10{margin-right:60%}.g-b--pull--d4of5,.g-b--pull--d8of10{margin-right:80%}.g-b--pull--d1of6,.g-b--pull--d2of12{margin-right:16.666%}.g-b--pull--d5of6,.g-b--pull--d10of12{margin-right:83.333%}.g-b--pull--d1of8{margin-right:12.5%}.g-b--pull--d3of8{margin-right:37.5%}.g-b--pull--d5of8{margin-right:62.5%}.g-b--pull--d7of8{margin-right:87.5%}.g-b--pull--d1of10{margin-right:10%}.g-b--pull--d3of10{margin-right:30%}.g-b--pull--d7of10{margin-right:70%}.g-b--pull--d9of10{margin-right:90%}.g-b--pull--d1of12{margin-right:8.333%}.g-b--pull--d5of12{margin-right:41.666%}.g-b--pull--d7of12{margin-right:58.333%}.g-b--pull--d11of12{margin-right:91.666%}.splashscreen-dillinger{width:700px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--export-as{display:block}.menu .menu-item--preview{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:700px}#editor{font-size:1rem}}@media screen and (min-width:87.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.splashscreen-dillinger{width:800px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#editor{font-size:1rem}}</style></head><body id="preview"> <h4><a id="Constraints_0"></a>Constraints</h4> <ul> <li><code>&quot; (quote)</code>, <code>(whitespace)</code>(unless in quotes), <code>, (comma)</code>, <code>: (semi-colon)</code>, <code>[ (starting bracket)</code> and <code>] (closing bracket)</code> are <strong>ignored</strong> and not included in the search</li> <li>terms and namespaces are separated by <code>(white space)</code> (if not in quotes) and/or a <code>, (comma)</code></li> <li>to include <em>whitespace</em> you must put the <em>term</em> in quotes: <code>&quot;this is a valid term&quot;</code></li> <li>to exclude a term, prefix the term with a <code>- (hyphen)</code>: <code>-&quot;i want to exclude this&quot;</code></li> </ul> <h4><a id="Searching_6"></a>Searching</h4> <p><code>-&gt;</code> points where the terms will be searched</p> <ul> <li><code>term</code> =&gt; show only galleries with <code>term</code> in them <code>-&gt;</code> (title, artist, language, namespace &amp; tags)</li> <li><code>-term</code> =&gt; exclude all galleries with <code>term</code> in them <code>-&gt;</code> (title, artist, language, namespace &amp; tags)</li> <li><code>ns:term</code> =&gt; show only galleries where <code>term</code> is in the <code>ns</code> namespace in them <code>-&gt;</code> (namespace &amp; tags)</li> <li><code>-ns:term</code> =&gt; exclude all galleries where <code>term</code> is in the <code>ns</code> namespace in them <code>-&gt;</code> (namespace &amp; tags)</li> <li><code>ns:[term1, term2, ...]</code> =&gt; equivalent to <code>ns:term1</code>, <code>ns:term2</code></li> <li><code>-ns:[term1, term2, ...]</code> =&gt; equivalent to <code>-ns:term1</code>, <code>-ns:term2</code></li> </ul> <h4><a id="Protips__warnings_16"></a>Protips &amp; warnings</h4> <ul> <li>When grouping tags under the same namespace in brackets, excluding tags (<code>-term</code>) and including tags (<code>term</code>) can both be used: <ul> <li><code>ns:[term, -term1, term2, ...]</code> -&gt; equivalent to <code>ns:term</code>, <code>-ns:term1</code>, <code>ns:term2</code></li> </ul> </li> <li><code>ns:-term</code> is <strong>NOT</strong> equivalent to <code>-ns:term</code></li> <li>You can enchance your search with regex. Regex can be used <em>anywhere</em> in your search terms <ul> <li>Enable <em>regex</em> in settings</li> </ul> </li> <li>Clicking on the search icon on the search bar will give you more options to search with</li> </ul> <h4><a id="Special_namespaced_tags_24"></a>Special namespaced tags</h4> <p>They work just like normal namespaced tags, meaning that the <em>constraints</em> above also apply to them!</p> <ul> <li><strong>Reserved</strong> means that it shouldn’t be used on your galleries. It <strong>won’t</strong> be searched for in your gallery.</li> <li><strong>Operator</strong> means that less than <code>&lt;</code> and greater than <code>&gt;</code> are supported. They should be used just like the exclude operator <code>-</code>. E.g.: <code>ns:&lt;term</code> or <code>ns:&gt;[term1, term2]</code>.</li> <li><code>term</code> means… well, your term… what you want to search for… any kind of characters not in <strong>Constraints</strong> above</li> <li><code>integer</code> means that only numbers are allowed</li> <li><code>date</code> means a date format. Most (if not all) date formats are supported (try it out yourself)</li> </ul> <hr> <table> <thead> <tr> <th>Namespaced tag(s)</th> <th>Reserved</th> <th>Filtered galleries</th> <th>Operator</th> </tr> </thead> <tbody> <tr> <td><code>tag:none</code>, <code>tag:null</code></td> <td>*</td> <td>Galleries with <strong>no</strong> namespace &amp; tags set</td> <td></td> </tr> <tr> <td><code>artist:none</code>, <code>artist:null</code></td> <td>*</td> <td>Galleries with <strong>no</strong> artist set</td> <td></td> </tr> <tr> <td><code>status:none</code>, <code>status:null</code></td> <td>*</td> <td>Galleries with <strong>no</strong> status set</td> <td></td> </tr> <tr> <td><code>language:none</code>, <code>language:null</code></td> <td>*</td> <td>Galleries with <strong>no</strong> language set</td> <td></td> </tr> <tr> <td><code>type:none</code>, <code>type:null</code></td> <td>*</td> <td>Galleries with <strong>no</strong> type set</td> <td></td> </tr> <tr> <td><code>path:none</code>, <code>path:null</code></td> <td>*</td> <td>Galleries that has been <strong>moved/deleted</strong> from the filesystem</td> <td></td> </tr> <tr> <td><code>descr:none</code>, <code>descr:null</code>, <code>description:none</code>, <code>description:null</code></td> <td>*</td> <td>Galleries with <strong>no</strong> description set</td> <td></td> </tr> <tr> <td><code>&quot;pub date&quot;:none</code>, <code>&quot;pub date&quot;:null</code>, <code>pub_date:none</code>, <code>pub_date:null</code>, <code>publication:none</code>, <code>publication:null</code></td> <td>*</td> <td>Galleries with <strong>no</strong> publication date set</td> <td></td> </tr> <tr> <td><code>title:term</code></td> <td></td> <td>Galleries with <code>term</code> in their title <strong>OR</strong> has matching namespace &amp; tag</td> <td></td> </tr> <tr> <td><code>artist:term</code></td> <td></td> <td>Galleries with <code>term</code> in their artist <strong>OR</strong> has matching namespace &amp; tag</td> <td></td> </tr> <tr> <td><code>language:term</code>, <code>lang:term</code></td> <td></td> <td>Galleries with <code>term</code> in their language <strong>OR</strong> has matching namespace &amp; tag</td> <td></td> </tr> <tr> <td><code>type:term</code></td> <td></td> <td>Galleries with <code>term</code> in their type <strong>OR</strong> has matching namespace &amp; tag</td> <td></td> </tr> <tr> <td><code>status:term</code></td> <td></td> <td>Galleries with <code>term</code> in their status <strong>OR</strong> has matching namespace &amp; tag</td> <td></td> </tr> <tr> <td><code>descr:term</code>, <code>description:term</code></td> <td></td> <td>Galleries with <code>term</code> in their description <strong>OR</strong> has matching namespace &amp; tag</td> <td></td> </tr> <tr> <td><code>chapter:integer</code>, <code>chapters:integer</code></td> <td></td> <td>Galleries with <code>integer</code> chapters <strong>OR</strong> has matching namespace &amp; tag</td> <td>*</td> </tr> <tr> <td><code>read_count:integer</code>, <code>&quot;read count&quot;:integer</code>, <code>times_read:integer</code>, <code>&quot;times read&quot;:integer</code></td> <td></td> <td>Galleries read <code>integer</code> times <strong>OR</strong> has matching namespace &amp; tag</td> <td>*</td> </tr> <tr> <td><code>date_added:date</code>, <code>&quot;date added&quot;:date</code></td> <td></td> <td>Galleries added on <code>date</code> <strong>OR</strong> has matching namespace &amp; tag</td> <td>*</td> </tr> <tr> <td><code>pub_date:date</code>, <code>&quot;pub date&quot;:date</code>, <code>publication:date</code></td> <td></td> <td>Galleries published on <code>date</code> <strong>OR</strong> has matching namespace &amp; tag</td> <td>*</td> </tr> <tr> <td><code>last_read:date</code>, <code>&quot;last read&quot;:date</code></td> <td></td> <td>Galleries last read on <code>date</code> <strong>OR</strong> has matching namespace &amp; tag</td> <td>*</td> </tr> <tr> <td><code>rating:integer</code>, <code>stars:integer</code></td> <td></td> <td>Galleries that has been rated <code>integer</code> <strong>OR</strong> has matching namespace &amp; tag</td> <td>*</td> </tr> </tbody> </table> </body></html> """ ) KEYBOARD_SHORTCUTS_INFO = ( """ <!DOCTYPE html><html><head><meta charset="utf-8"><title>Untitled Document.md</title><style>@import 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.2.0/katex.min.css';code{color:#c7254e;background-color:#f9f2f4;border-radius:4px}code,kbd{padding:2px 4px}kbd{color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;box-shadow:none}pre{display:block;margin:0 0 10px;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}fieldset{border:0;min-width:0}legend{display:block;width:100%;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type="radio"],input[type="checkbox"]{margin:1px 0 0;line-height:normal}input[type="file"]{display:block}input[type="range"]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{padding-top:7px}output,.form-control{display:block;font-size:14px;line-height:1.4285714;color:#555}.form-control{width:100%;height:34px;padding:6px 12px;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#777;opacity:1}.form-control:-ms-input-placeholder{color:#777}.form-control::-webkit-input-placeholder{color:#777}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type="date"],input[type="time"],input[type="datetime-local"],input[type="month"]{line-height:34px;line-height:1.4285714 \0}input[type="date"].input-sm,.form-horizontal .form-group-sm input[type="date"].form-control,.input-group-sm>input[type="date"].form-control,.input-group-sm>input[type="date"].input-group-addon,.input-group-sm>.input-group-btn>input[type="date"].btn,input[type="time"].input-sm,.form-horizontal .form-group-sm input[type="time"].form-control,.input-group-sm>input[type="time"].form-control,.input-group-sm>input[type="time"].input-group-addon,.input-group-sm>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-sm,.form-horizontal .form-group-sm input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].form-control,.input-group-sm>input[type="datetime-local"].input-group-addon,.input-group-sm>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-sm,.form-horizontal .form-group-sm input[type="month"].form-control,.input-group-sm>input[type="month"].form-control,.input-group-sm>input[type="month"].input-group-addon,.input-group-sm>.input-group-btn>input[type="month"].btn{line-height:30px}input[type="date"].input-lg,.form-horizontal .form-group-lg input[type="date"].form-control,.input-group-lg>input[type="date"].form-control,.input-group-lg>input[type="date"].input-group-addon,.input-group-lg>.input-group-btn>input[type="date"].btn,input[type="time"].input-lg,.form-horizontal .form-group-lg input[type="time"].form-control,.input-group-lg>input[type="time"].form-control,.input-group-lg>input[type="time"].input-group-addon,.input-group-lg>.input-group-btn>input[type="time"].btn,input[type="datetime-local"].input-lg,.form-horizontal .form-group-lg input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].form-control,.input-group-lg>input[type="datetime-local"].input-group-addon,.input-group-lg>.input-group-btn>input[type="datetime-local"].btn,input[type="month"].input-lg,.form-horizontal .form-group-lg input[type="month"].form-control,.input-group-lg>input[type="month"].form-control,.input-group-lg>input[type="month"].input-group-addon,.input-group-lg>.input-group-btn>input[type="month"].btn{line-height:46px}.form-group{margin-bottom:15px}.radio,.checkbox{position:relative;display:block;min-height:20px;margin-top:10px;margin-bottom:10px}.radio label,.checkbox label{padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"]{position:absolute;margin-left:-20px;margin-top:4px \9}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type="radio"][disabled],input[type="radio"].disabled,fieldset[disabled] input[type="radio"],input[type="checkbox"][disabled],input[type="checkbox"].disabled,fieldset[disabled] input[type="checkbox"],.radio-inline.disabled,fieldset[disabled] .radio-inline,.checkbox-inline.disabled,fieldset[disabled] .checkbox-inline,.radio.disabled label,fieldset[disabled] .radio label,.checkbox.disabled label,fieldset[disabled] .checkbox label{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-horizontal .form-group-lg .form-control-static.form-control,.input-group-lg>.form-control-static.form-control,.input-group-lg>.form-control-static.input-group-addon,.input-group-lg>.input-group-btn>.form-control-static.btn,.form-control-static.input-sm,.form-horizontal .form-group-sm .form-control-static.form-control,.input-group-sm>.form-control-static.form-control,.input-group-sm>.form-control-static.input-group-addon,.input-group-sm>.input-group-btn>.form-control-static.btn{padding-left:0;padding-right:0}.input-sm,.form-horizontal .form-group-sm .form-control,.input-group-sm>.form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.input-group-sm>.input-group-addon{height:30px;line-height:1.5}.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm,.form-horizontal .form-group-sm select.form-control,.input-group-sm>select.form-control,.input-group-sm>select.input-group-addon,.input-group-sm>.input-group-btn>select.btn{height:30px;line-height:30px}textarea.input-sm,.form-horizontal .form-group-sm textarea.form-control,.input-group-sm>textarea.form-control,.input-group-sm>textarea.input-group-addon,.input-group-sm>.input-group-btn>textarea.btn,select[multiple].input-sm,.form-horizontal .form-group-sm select[multiple].form-control,.input-group-sm>select[multiple].form-control,.input-group-sm>select[multiple].input-group-addon,.input-group-sm>.input-group-btn>select[multiple].btn{height:auto}.input-lg,.form-horizontal .form-group-lg .form-control,.input-group-lg>.form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.input-group-lg>.input-group-addon{height:46px;line-height:1.33}.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg,.form-horizontal .form-group-lg select.form-control,.input-group-lg>select.form-control,.input-group-lg>select.input-group-addon,.input-group-lg>.input-group-btn>select.btn{height:46px;line-height:46px}textarea.input-lg,.form-horizontal .form-group-lg textarea.form-control,.input-group-lg>textarea.form-control,.input-group-lg>textarea.input-group-addon,.input-group-lg>.input-group-btn>textarea.btn,select[multiple].input-lg,.form-horizontal .form-group-lg select[multiple].form-control,.input-group-lg>select[multiple].form-control,.input-group-lg>select[multiple].input-group-addon,.input-group-lg>.input-group-btn>select[multiple].btn{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:25px;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center}.input-lg+.form-control-feedback,.form-horizontal .form-group-lg .form-control+.form-control-feedback,.input-group-lg>.form-control+.form-control-feedback,.input-group-lg>.input-group-addon+.form-control-feedback,.input-group-lg>.input-group-btn>.btn+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback,.form-horizontal .form-group-sm .form-control+.form-control-feedback,.input-group-sm>.form-control+.form-control-feedback,.input-group-sm>.input-group-addon+.form-control-feedback,.input-group-sm>.input-group-btn>.btn+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-group:before{content:" ";display:table}.form-horizontal .form-group:after{content:" ";display:table;clear:both}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}.btn{display:inline-block;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{outline:0;background-image:none;box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;pointer-events:none;opacity:.65;filter:alpha(opacity=65);box-shadow:none}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default:active,.btn-default.active,.open>.btn-default.dropdown-toggle{background-image:none}.btn-default.disabled,.btn-default.disabled:hover,.btn-default.disabled:focus,.btn-default.disabled:active,.btn-default.disabled.active,.btn-default[disabled],.btn-default[disabled]:hover,.btn-default[disabled]:focus,.btn-default[disabled]:active,.btn-default[disabled].active,fieldset[disabled] .btn-default,fieldset[disabled] .btn-default:hover,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{color:#fff;background-color:#3071a9;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open>.btn-primary.dropdown-toggle{background-image:none}.btn-primary.disabled,.btn-primary.disabled:hover,.btn-primary.disabled:focus,.btn-primary.disabled:active,.btn-primary.disabled.active,.btn-primary[disabled],.btn-primary[disabled]:hover,.btn-primary[disabled]:focus,.btn-primary[disabled]:active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary,fieldset[disabled] .btn-primary:hover,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{color:#fff;background-color:#449d44;border-color:#398439}.btn-success:active,.btn-success.active,.open>.btn-success.dropdown-toggle{background-image:none}.btn-success.disabled,.btn-success.disabled:hover,.btn-success.disabled:focus,.btn-success.disabled:active,.btn-success.disabled.active,.btn-success[disabled],.btn-success[disabled]:hover,.btn-success[disabled]:focus,.btn-success[disabled]:active,.btn-success[disabled].active,fieldset[disabled] .btn-success,fieldset[disabled] .btn-success:hover,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info:active,.btn-info.active,.open>.btn-info.dropdown-toggle{background-image:none}.btn-info.disabled,.btn-info.disabled:hover,.btn-info.disabled:focus,.btn-info.disabled:active,.btn-info.disabled.active,.btn-info[disabled],.btn-info[disabled]:hover,.btn-info[disabled]:focus,.btn-info[disabled]:active,.btn-info[disabled].active,fieldset[disabled] .btn-info,fieldset[disabled] .btn-info:hover,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open>.btn-warning.dropdown-toggle{background-image:none}.btn-warning.disabled,.btn-warning.disabled:hover,.btn-warning.disabled:focus,.btn-warning.disabled:active,.btn-warning.disabled.active,.btn-warning[disabled],.btn-warning[disabled]:hover,.btn-warning[disabled]:focus,.btn-warning[disabled]:active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning,fieldset[disabled] .btn-warning:hover,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open>.btn-danger.dropdown-toggle{background-image:none}.btn-danger.disabled,.btn-danger.disabled:hover,.btn-danger.disabled:focus,.btn-danger.disabled:active,.btn-danger.disabled.active,.btn-danger[disabled],.btn-danger[disabled]:hover,.btn-danger[disabled]:focus,.btn-danger[disabled]:active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger,fieldset[disabled] .btn-danger:hover,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{color:#428bca;font-weight:400;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:hover,fieldset[disabled] .btn-link:focus{color:#777;text-decoration:none}.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm{padding:5px 10px}.btn-sm,.btn-xs{font-size:12px;line-height:1.5;border-radius:3px}.btn-xs{padding:1px 5px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;transition:height .35s ease}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*="col-"]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon{white-space:nowrap}.input-group-addon,.input-group-btn{width:1%;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm,.form-horizontal .form-group-sm .input-group-addon.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.input-group-addon.btn{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg,.form-horizontal .form-group-lg .input-group-addon.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.input-group-addon.btn{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type="radio"],.input-group-addon input[type="checkbox"]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{font-size:0;white-space:nowrap}.input-group-btn,.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.4285714;text-decoration:none;color:#428bca;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:hover,.pagination>li>a:focus,.pagination>li>span:hover,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:hover,.pagination>.active>a:focus,.pagination>.active>span,.pagination>.active>span:hover,.pagination>.active>span:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca;cursor:default}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:0 0;border:0;-webkit-appearance:none}.modal-open,.modal{overflow:hidden}.modal{display:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate3d(0,-25%,0);transform:translate3d(0,-25%,0);-webkit-transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5;min-height:16.4285714px}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.4285714}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:before,.modal-footer:after{content:" ";display:table}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.clearfix:before,.clearfix:after{content:" ";display:table}.clearfix:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.hljs{display:block;overflow-x:auto;padding:.5em;background:#002b36;color:#839496;-webkit-text-size-adjust:none}.hljs-comment,.hljs-template_comment,.diff .hljs-header,.hljs-doctype,.hljs-pi,.lisp .hljs-string,.hljs-javadoc{color:#586e75}.hljs-keyword,.hljs-winutils,.method,.hljs-addition,.css .hljs-tag,.hljs-request,.hljs-status,.nginx .hljs-title{color:#859900}.hljs-number,.hljs-command,.hljs-string,.hljs-tag .hljs-value,.hljs-rules .hljs-value,.hljs-phpdoc,.hljs-dartdoc,.tex .hljs-formula,.hljs-regexp,.hljs-hexcolor,.hljs-link_url{color:#2aa198}.hljs-title,.hljs-localvars,.hljs-chunk,.hljs-decorator,.hljs-built_in,.hljs-identifier,.vhdl .hljs-literal,.hljs-id,.css .hljs-function{color:#268bd2}.hljs-attribute,.hljs-variable,.lisp .hljs-body,.smalltalk .hljs-number,.hljs-constant,.hljs-class .hljs-title,.hljs-parent,.hljs-type,.hljs-link_reference{color:#b58900}.hljs-preprocessor,.hljs-preprocessor .hljs-keyword,.hljs-pragma,.hljs-shebang,.hljs-symbol,.hljs-symbol .hljs-string,.diff .hljs-change,.hljs-special,.hljs-attr_selector,.hljs-subst,.hljs-cdata,.css .hljs-pseudo,.hljs-header{color:#cb4b16}.hljs-deletion,.hljs-important{color:#dc322f}.hljs-link_label{color:#6c71c4}.tex .hljs-formula{background:#073642}*,*:before,*:after{box-sizing:border-box}html{-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}images{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{box-sizing:content-box;height:0}pre{overflow:auto}code,kbd{font-size:1em}code,kbd,pre,samp{font-family:monospace,monospace}samp{font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}input[type="number"]::-webkit-inner-spin-button,input[type="number"]::-webkit-outer-spin-button{height:auto}input[type="search"]{-webkit-appearance:textfield;box-sizing:content-box}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}.debug{background-color:#ffc0cb!important}.ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ir{background-color:transparent;border:0;overflow:hidden}.ir::before{content:'';display:block;height:150%;width:0}html{font-size:.875em;background:#fafafa;color:#373D49}html,body{font-family:Georgia,Cambria,serif;height:100%}body{font-size:1rem;font-weight:400;line-height:2rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}li{-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-left:1rem}li>ul,li>ol{margin-bottom:0}p{padding-top:.66001rem;-webkit-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;-moz-font-feature-settings:'kern' 1,'onum' 1,'liga' 1;font-feature-settings:'kern' 1,'onum' 1,'liga' 1;margin-top:0}p,pre{margin-bottom:1.33999rem}pre{font-size:1rem;padding:.66001rem 9.5px 9.5px;line-height:2rem;background:-webkit-linear-gradient(top,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background:linear-gradient(to bottom,#fff 0,#fff .75rem,#f5f7fa .75rem,#f5f7fa 2.75rem,#fff 2.75rem,#fff 4rem);background-size:100% 4rem;border-color:#D3DAEA}blockquote{margin:0}blockquote p{font-size:1rem;margin-bottom:.33999rem;font-style:italic;padding:.66001rem 1rem 1rem;border-left:3px solid #A0AABF}th,td{padding:12px}h1,h2,h3,h4,h5,h6{font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;-webkit-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;-moz-font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-feature-settings:'dlig' 1,'liga' 1,'lnum' 1,'kern' 1;font-style:normal;font-weight:600;margin-top:0}h1{line-height:3rem;font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h2,h3{line-height:3rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}a{cursor:pointer;color:#35D7BB;text-decoration:none}a:hover,a:focus{border-bottom-color:#35D7BB;color:#dff9f4}img{height:auto;max-width:100%}.g{display:block}.g:after{clear:both;content:'';display:table}.g-b{float:left;margin:0;width:100%}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--center{display:block;float:none;margin:0 auto}.g-b--right{float:right}.g-b--1of1{width:100%}.g-b--1of2,.g-b--2of4,.g-b--3of6,.g-b--4of8,.g-b--5of10,.g-b--6of12{width:50%}.g-b--1of3,.g-b--2of6,.g-b--4of12{width:33.333%}.g-b--2of3,.g-b--4of6,.g-b--8of12{width:66.666%}.g-b--1of4,.g-b--2of8,.g-b--3of12{width:25%}.g-b--3of4,.g-b--6of8,.g-b--9of12{width:75%}.g-b--1of5,.g-b--2of10{width:20%}.g-b--2of5,.g-b--4of10{width:40%}.g-b--3of5,.g-b--6of10{width:60%}.g-b--4of5,.g-b--8of10{width:80%}.g-b--1of6,.g-b--2of12{width:16.666%}.g-b--5of6,.g-b--10of12{width:83.333%}.g-b--1of8{width:12.5%}.g-b--3of8{width:37.5%}.g-b--5of8{width:62.5%}.g-b--7of8{width:87.5%}.g-b--1of10{width:10%}.g-b--3of10{width:30%}.g-b--7of10{width:70%}.g-b--9of10{width:90%}.g-b--1of12{width:8.333%}.g-b--5of12{width:41.666%}.g-b--7of12{width:58.333%}.g-b--11of12{width:91.666%}.g-b--push--1of1{margin-left:100%}.g-b--push--1of2,.g-b--push--2of4,.g-b--push--3of6,.g-b--push--4of8,.g-b--push--5of10,.g-b--push--6of12{margin-left:50%}.g-b--push--1of3,.g-b--push--2of6,.g-b--push--4of12{margin-left:33.333%}.g-b--push--2of3,.g-b--push--4of6,.g-b--push--8of12{margin-left:66.666%}.g-b--push--1of4,.g-b--push--2of8,.g-b--push--3of12{margin-left:25%}.g-b--push--3of4,.g-b--push--6of8,.g-b--push--9of12{margin-left:75%}.g-b--push--1of5,.g-b--push--2of10{margin-left:20%}.g-b--push--2of5,.g-b--push--4of10{margin-left:40%}.g-b--push--3of5,.g-b--push--6of10{margin-left:60%}.g-b--push--4of5,.g-b--push--8of10{margin-left:80%}.g-b--push--1of6,.g-b--push--2of12{margin-left:16.666%}.g-b--push--5of6,.g-b--push--10of12{margin-left:83.333%}.g-b--push--1of8{margin-left:12.5%}.g-b--push--3of8{margin-left:37.5%}.g-b--push--5of8{margin-left:62.5%}.g-b--push--7of8{margin-left:87.5%}.g-b--push--1of10{margin-left:10%}.g-b--push--3of10{margin-left:30%}.g-b--push--7of10{margin-left:70%}.g-b--push--9of10{margin-left:90%}.g-b--push--1of12{margin-left:8.333%}.g-b--push--5of12{margin-left:41.666%}.g-b--push--7of12{margin-left:58.333%}.g-b--push--11of12{margin-left:91.666%}.g-b--pull--1of1{margin-right:100%}.g-b--pull--1of2,.g-b--pull--2of4,.g-b--pull--3of6,.g-b--pull--4of8,.g-b--pull--5of10,.g-b--pull--6of12{margin-right:50%}.g-b--pull--1of3,.g-b--pull--2of6,.g-b--pull--4of12{margin-right:33.333%}.g-b--pull--2of3,.g-b--pull--4of6,.g-b--pull--8of12{margin-right:66.666%}.g-b--pull--1of4,.g-b--pull--2of8,.g-b--pull--3of12{margin-right:25%}.g-b--pull--3of4,.g-b--pull--6of8,.g-b--pull--9of12{margin-right:75%}.g-b--pull--1of5,.g-b--pull--2of10{margin-right:20%}.g-b--pull--2of5,.g-b--pull--4of10{margin-right:40%}.g-b--pull--3of5,.g-b--pull--6of10{margin-right:60%}.g-b--pull--4of5,.g-b--pull--8of10{margin-right:80%}.g-b--pull--1of6,.g-b--pull--2of12{margin-right:16.666%}.g-b--pull--5of6,.g-b--pull--10of12{margin-right:83.333%}.g-b--pull--1of8{margin-right:12.5%}.g-b--pull--3of8{margin-right:37.5%}.g-b--pull--5of8{margin-right:62.5%}.g-b--pull--7of8{margin-right:87.5%}.g-b--pull--1of10{margin-right:10%}.g-b--pull--3of10{margin-right:30%}.g-b--pull--7of10{margin-right:70%}.g-b--pull--9of10{margin-right:90%}.g-b--pull--1of12{margin-right:8.333%}.g-b--pull--5of12{margin-right:41.666%}.g-b--pull--7of12{margin-right:58.333%}.g-b--pull--11of12{margin-right:91.666%}.splashscreen{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#373D49;z-index:22}.splashscreen-dillinger{width:260px;height:auto;display:block;margin:0 auto;padding-bottom:3rem}.splashscreen p{font-size:1.25rem;padding-top:.56251rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;text-align:center;max-width:500px;margin:0 auto;color:#FFF}.sp-center{position:relative;-webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%);top:50%}.open-menu>.wrapper{overflow-x:hidden}.page{margin:0 auto;position:relative;top:0;left:0;width:100%;height:100%;z-index:2;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;background-color:#fff;padding-top:51px;will-change:left}.open-menu .page{left:270px}.title{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;padding-left:16px;padding-right:16px;margin-top:1rem}.split-preview .title{padding-left:0}.title-document{line-height:1rem;font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem;font-weight:400;font-family:"Ubuntu Mono",Monaco;color:#373D49;padding-left:16px;padding-right:16px;width:80%;min-width:300px;outline:0;border:none}.icon{display:block;margin:0 auto;width:36px;height:36px;border-radius:3px;text-align:center}.icon svg{display:inline-block;margin-left:auto;margin-right:auto}.icon-preview{background-color:#373D49;line-height:40px}.icon-preview svg{width:19px;height:12px}.icon-settings{background-color:#373D49;line-height:44px}.icon-settings svg{width:18px;height:18px}.icon-link{width:16px;height:16px;line-height:1;margin-right:24px;text-align:right}.navbar{background-color:#373D49;height:51px;width:100%;position:fixed;top:0;left:0;z-index:6;-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;will-change:left}.navbar:after{content:"";display:table;clear:both}.open-menu .navbar{left:270px}.navbar-brand{float:left;margin:0 0 0 24px;padding:0;line-height:42px}.navbar-brand svg{width:85px;height:11px}.nav-left{float:left}.nav-right{float:right}.nav-sidebar{width:100%}.menu{list-style:none;margin:0;padding:0}.menu a{border:0;color:#A0AABF;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;outline:none;text-transform:uppercase}.menu a:hover{color:#35D7BB}.menu .menu-item{border:0;display:none;float:left;margin:0;position:relative}.menu .menu-item>a{display:block;font-size:12px;height:51px;letter-spacing:1px;line-height:51px;padding:0 24px}.menu .menu-item--settings,.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar,.menu .menu-item--link-unlink.in-sidebar,.menu .menu-item--documents.in-sidebar{display:block}.menu .menu-item--documents{padding-bottom:1rem}.menu .menu-item.open>a{background-color:#1D212A}.menu .menu-item-icon>a{height:auto;padding:0}.menu .menu-item-icon:hover>a{background-color:transparent}.menu .menu-link.open i{background-color:#1D212A}.menu .menu-link.open g{fill:#35D7BB}.menu .menu-link-preview,.menu .menu-link-settings{margin-top:8px;width:51px}.menu-sidebar{width:100%}.menu-sidebar .menu-item{float:none;margin-bottom:1px;width:100%}.menu-sidebar .menu-item.open>a{background-color:#373D49}.menu-sidebar .open .caret{-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg)}.menu-sidebar>.menu-item:hover .dropdown a,.menu-sidebar>.menu-item:hover .settings a{background-color:transparent}.menu-sidebar .menu-link{background-color:#373D49;font-weight:600}.menu-sidebar .menu-link:after{content:"";display:table;clear:both}.menu-sidebar .menu-link>span{float:left}.menu-sidebar .menu-link>.caret{float:right;text-align:right;top:22px}.menu-sidebar .dropdown,.menu-sidebar .settings{background-color:transparent;position:static;width:100%}.dropdown{position:absolute;right:0;top:51px;width:188px}.dropdown,.settings{display:none;background-color:#1D212A}.dropdown{padding:0}.dropdown,.settings,.sidebar-list{list-style:none;margin:0}.sidebar-list{padding:0}.dropdown li{margin:32px 0;padding:0 0 0 32px}.dropdown li,.settings li{line-height:1}.sidebar-list li{line-height:1;margin:32px 0;padding:0 0 0 32px}.dropdown a{color:#D0D6E2}.dropdown a,.settings a,.sidebar-list a{display:block;text-transform:none}.sidebar-list a{color:#D0D6E2}.dropdown a:after,.settings a:after,.sidebar-list a:after{content:"";display:table;clear:both}.dropdown .icon,.settings .icon,.sidebar-list .icon{float:right}.open .dropdown,.open .settings,.open .sidebar-list{display:block}.open .dropdown.collapse,.open .collapse.settings,.open .sidebar-list.collapse{display:none}.open .dropdown.collapse.in,.open .collapse.in.settings,.open .sidebar-list.collapse.in{display:block}.dropdown .unlinked .icon,.settings .unlinked .icon,.sidebar-list .unlinked .icon{opacity:.3}.dropdown.documents li,.documents.settings li,.sidebar-list.documents li{background-image:url("../img/icons/file.svg");background-position:240px center;background-repeat:no-repeat;background-size:14px 16px;padding:3px 32px}.dropdown.documents li.octocat,.documents.settings li.octocat,.sidebar-list.documents li.octocat{background-image:url("../img/icons/octocat.svg");background-position:234px center;background-size:24px 24px}.dropdown.documents li:last-child,.documents.settings li:last-child,.sidebar-list.documents li:last-child{margin-bottom:1rem}.dropdown.documents li.active a,.documents.settings li.active a,.sidebar-list.documents li.active a{color:#35D7BB}.settings{position:fixed;top:67px;right:16px;border-radius:3px;width:288px;background-color:#373D49;padding:16px;z-index:7}.show-settings .settings{display:block}.settings .has-checkbox{float:left}.settings a{font-size:1.25rem;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;-webkit-font-smoothing:antialiased;line-height:28px;color:#D0D6E2}.settings a:after{content:"";display:table;clear:both}.settings a:hover{color:#35D7BB}.settings li{border-bottom:1px solid #4F535B;margin:0;padding:16px 0}.settings li:last-child{border-bottom:none}.brand{border:none;display:block}.brand:hover g{fill:#35D7BB}.toggle{display:block;float:left;height:16px;padding:25px 16px 26px;width:40px}.toggle span:after,.toggle span:before{content:'';left:0;position:absolute;top:-6px}.toggle span:after{top:6px}.toggle span{display:block;position:relative}.toggle span,.toggle span:after,.toggle span:before{-webkit-backface-visibility:hidden;backface-visibility:hidden;background-color:#D3DAEA;height:2px;-webkit-transition:all .3s;transition:all .3s;width:20px}.open-menu .toggle span{background-color:transparent}.open-menu .toggle span:before{-webkit-transform:rotate(45deg)translate(3px,3px);-ms-transform:rotate(45deg)translate(3px,3px);transform:rotate(45deg)translate(3px,3px)}.open-menu .toggle span:after{-webkit-transform:rotate(-45deg)translate(5px,-6px);-ms-transform:rotate(-45deg)translate(5px,-6px);transform:rotate(-45deg)translate(5px,-6px)}.caret{display:inline-block;width:0;height:0;margin-left:6px;vertical-align:middle;position:relative;top:-1px;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.sidebar{overflow:auto;height:100%;padding-right:15px;padding-bottom:15px;width:285px}.sidebar-wrapper{-webkit-overflow-scrolling:touch;background-color:#2B2F36;left:0;height:100%;overflow-y:hidden;position:fixed;top:0;width:285px;z-index:1}.sidebar-branding{width:160px;padding:0;margin:16px auto}.header{border-bottom:1px solid #E8E8E8;position:relative}.words{line-height:1rem;font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem;font-weight:500;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;color:#A0AABF;letter-spacing:1px;text-transform:uppercase;z-index:5;position:absolute;right:16px;top:0}.words span{color:#000}.btn{text-align:center;display:inline-block;width:100%;text-transform:uppercase;font-weight:600;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;text-shadow:0 1px 0 #1b8b77;padding:16px 24px;background-color:#35D7BB;border-radius:3px;margin:0 auto 16px;line-height:1;color:#fff;-webkit-transition:all .15s linear;transition:all .15s linear;-webkit-font-smoothing:antialiased}.btn--new,.btn--save{display:block;width:238px}.btn--new:hover,.btn--new:focus,.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 3px #24b59c;text-shadow:0 1px 0 #24b59c}.btn--save{background-color:#4A5261;text-shadow:0 1px 1px #1e2127}.btn--save:hover,.btn--save:focus{color:#fff;border-bottom-color:transparent;box-shadow:0 1px 5px #08090a;text-shadow:none}.btn--delete{display:block;width:238px;background-color:transparent;font-size:12px;text-shadow:none}.btn--delete:hover,.btn--delete:focus{color:#fff;border-bottom-color:transparent;text-shadow:0 1px 0 #08090a;opacity:.8}.btn--ok,.btn--close{border-top:0;background-color:#4A5261;text-shadow:0 1px 0 #08090a;margin:0}.btn--ok:hover,.btn--ok:focus,.btn--close:hover,.btn--close:focus{color:#fff;background-color:#292d36;text-shadow:none}.overlay{position:absolute;top:0;left:0;width:100%;height:100%;background-color:rgba(55,61,73,.8);-webkit-transition:all .25s ease-in-out;transition:all .25s ease-in-out;-webkit-transition-timing-function:ease-out;transition-timing-function:ease-out;will-change:left,opacity,visibility;z-index:5;opacity:0;visibility:hidden}.show-settings .overlay{visibility:visible;opacity:1}.switch{float:right;line-height:1}.switch input{display:none}.switch small{display:inline-block;cursor:pointer;padding:0 24px 0 0;-webkit-transition:all ease .2s;transition:all ease .2s;background-color:#2B2F36;border-color:#2B2F36}.switch small,.switch small:before{border-radius:30px;box-shadow:inset 0 0 2px 0 #14171F}.switch small:before{display:block;content:'';width:28px;height:28px;background:#fff}.switch.checked small{padding-right:0;padding-left:24px;background-color:#35D7BB;box-shadow:none}.modal--dillinger.about .modal-dialog{font-size:1.25rem;max-width:500px}.modal--dillinger .modal-dialog{max-width:600px;width:auto;margin:5rem auto}.modal--dillinger .modal-content{background:#373D49;border-radius:3px;box-shadow:0 2px 5px 0 #2C3B59;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;padding:2rem}.modal--dillinger ul{list-style-type:disc;margin:1rem 0;padding:0 0 0 1rem}.modal--dillinger li{padding:0;margin:0}.modal--dillinger .modal-header{border:0;padding:0}.modal--dillinger .modal-body{padding:0}.modal--dillinger .modal-footer{border:0;padding:0}.modal--dillinger .close{color:#fff;opacity:1}.modal-backdrop{background-color:#373D49}.pagination--dillinger{padding:0!important;margin:1.5rem 0!important;-webkit-box-pack:justify;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;-webkit-align-content:stretch;-ms-flex-line-pack:stretch;align-content:stretch}.pagination--dillinger,.pagination--dillinger li{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex}.pagination--dillinger li{-webkit-box-flex:1;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;text-align:center}.pagination--dillinger li:first-child>a,.pagination--dillinger li.disabled>a,.pagination--dillinger li.disabled>a:hover,.pagination--dillinger li.disabled>a:focus,.pagination--dillinger li>a{background-color:transparent;border-color:#4F535B;border-right-color:transparent}.pagination--dillinger li.active>a,.pagination--dillinger li.active>a:hover,.pagination--dillinger li.active>a:focus{border-color:#4A5261;background-color:#4A5261;color:#fff}.pagination--dillinger li>a{float:none;color:#fff;width:100%;display:block;text-align:center;margin:0;border-right-color:transparent;padding:6px}.pagination--dillinger li>a:hover,.pagination--dillinger li>a:focus{border-color:#35D7BB;background-color:#35D7BB;color:#fff}.pagination--dillinger li:last-child a{border-color:#4F535B}.pagination--dillinger li:first-child a{border-right-color:transparent}.diNotify{position:absolute;z-index:9999;left:0;right:0;top:0;margin:0 auto;max-width:400px;text-align:center;-webkit-transition:top .5s ease-in-out,opacity .5s ease-in-out;transition:top .5s ease-in-out,opacity .5s ease-in-out;visibility:hidden}.diNotify-body{-webkit-font-smoothing:antialiased;background-color:#35D7BB;background:#666E7F;border-radius:3px;color:#fff;font-family:"Source Sans Pro","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:400;overflow:hidden;padding:1rem 2rem .5rem;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:baseline;-webkit-align-items:baseline;-ms-flex-align:baseline;align-items:baseline;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center}.diNotify-icon{display:block;width:16px;height:16px;line-height:16px;position:relative;top:3px}.diNotify-message{padding-left:1rem}.zen-wrapper{position:fixed;top:0;left:0;right:0;bottom:0;width:100%;height:100%;z-index:10;background-color:#FFF;opacity:0;-webkit-transition:opacity .25s ease-in-out;transition:opacity .25s ease-in-out}.zen-wrapper.on{opacity:1}.enter-zen-mode{background-image:url("../img/icons/enter-zen.svg");right:.5rem;top:.313rem;display:none}.enter-zen-mode,.close-zen-mode{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;background-repeat:no-repeat;width:32px;height:32px;display:block;position:absolute}.close-zen-mode{background-image:url("../img/icons/exit-zen.svg");right:1rem;top:1rem}.zen-page{position:relative;top:0;bottom:0;z-index:11;height:100%;width:100%}#zen{font-size:1.25rem;width:300px;height:80%;margin:0 auto;position:relative;top:10%}#zen:before,#zen:after{content:"";position:absolute;height:10%;width:100%;z-index:12;pointer-events:none}.split{overflow:scroll;padding:0!important}.split-editor{padding-left:0;padding-right:0;position:relative}.show-preview .split-editor{display:none}.split-preview{background-color:#fff;display:none;top:0;position:relative;z-index:4}.show-preview .split-preview{display:block}#editor{font-size:1rem;font-family:"Ubuntu Mono",Monaco;font-weight:400;line-height:2rem;width:100%;height:100%}#editor .ace_gutter{-webkit-font-smoothing:antialiased}.editor-header{width:50%;float:left;border-bottom:1px solid #E8E8E8;position:relative}.editor-header--first{border-right:1px solid #E8E8E8}.editor-header .title{display:inline-block}#preview{padding:10px}#preview a{color:#A0AABF;text-decoration:underline}.sr-only{visibility:hidden;text-overflow:110%;overflow:hidden;top:-100px;position:absolute}.mnone{margin:0!important}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .radio label,.form-inline .checkbox label{padding-left:0}.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}.form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}.form-horizontal .form-group-lg .control-label{padding-top:14.3px}.form-horizontal .form-group-sm .control-label{padding-top:6px}.modal-dialog{width:600px;margin:30px auto}.modal-content{box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}@media screen and (min-width:27.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--m1of1{width:100%}.g-b--m1of2,.g-b--m2of4,.g-b--m3of6,.g-b--m4of8,.g-b--m5of10,.g-b--m6of12{width:50%}.g-b--m1of3,.g-b--m2of6,.g-b--m4of12{width:33.333%}.g-b--m2of3,.g-b--m4of6,.g-b--m8of12{width:66.666%}.g-b--m1of4,.g-b--m2of8,.g-b--m3of12{width:25%}.g-b--m3of4,.g-b--m6of8,.g-b--m9of12{width:75%}.g-b--m1of5,.g-b--m2of10{width:20%}.g-b--m2of5,.g-b--m4of10{width:40%}.g-b--m3of5,.g-b--m6of10{width:60%}.g-b--m4of5,.g-b--m8of10{width:80%}.g-b--m1of6,.g-b--m2of12{width:16.666%}.g-b--m5of6,.g-b--m10of12{width:83.333%}.g-b--m1of8{width:12.5%}.g-b--m3of8{width:37.5%}.g-b--m5of8{width:62.5%}.g-b--m7of8{width:87.5%}.g-b--m1of10{width:10%}.g-b--m3of10{width:30%}.g-b--m7of10{width:70%}.g-b--m9of10{width:90%}.g-b--m1of12{width:8.333%}.g-b--m5of12{width:41.666%}.g-b--m7of12{width:58.333%}.g-b--m11of12{width:91.666%}.g-b--push--m1of1{margin-left:100%}.g-b--push--m1of2,.g-b--push--m2of4,.g-b--push--m3of6,.g-b--push--m4of8,.g-b--push--m5of10,.g-b--push--m6of12{margin-left:50%}.g-b--push--m1of3,.g-b--push--m2of6,.g-b--push--m4of12{margin-left:33.333%}.g-b--push--m2of3,.g-b--push--m4of6,.g-b--push--m8of12{margin-left:66.666%}.g-b--push--m1of4,.g-b--push--m2of8,.g-b--push--m3of12{margin-left:25%}.g-b--push--m3of4,.g-b--push--m6of8,.g-b--push--m9of12{margin-left:75%}.g-b--push--m1of5,.g-b--push--m2of10{margin-left:20%}.g-b--push--m2of5,.g-b--push--m4of10{margin-left:40%}.g-b--push--m3of5,.g-b--push--m6of10{margin-left:60%}.g-b--push--m4of5,.g-b--push--m8of10{margin-left:80%}.g-b--push--m1of6,.g-b--push--m2of12{margin-left:16.666%}.g-b--push--m5of6,.g-b--push--m10of12{margin-left:83.333%}.g-b--push--m1of8{margin-left:12.5%}.g-b--push--m3of8{margin-left:37.5%}.g-b--push--m5of8{margin-left:62.5%}.g-b--push--m7of8{margin-left:87.5%}.g-b--push--m1of10{margin-left:10%}.g-b--push--m3of10{margin-left:30%}.g-b--push--m7of10{margin-left:70%}.g-b--push--m9of10{margin-left:90%}.g-b--push--m1of12{margin-left:8.333%}.g-b--push--m5of12{margin-left:41.666%}.g-b--push--m7of12{margin-left:58.333%}.g-b--push--m11of12{margin-left:91.666%}.g-b--pull--m1of1{margin-right:100%}.g-b--pull--m1of2,.g-b--pull--m2of4,.g-b--pull--m3of6,.g-b--pull--m4of8,.g-b--pull--m5of10,.g-b--pull--m6of12{margin-right:50%}.g-b--pull--m1of3,.g-b--pull--m2of6,.g-b--pull--m4of12{margin-right:33.333%}.g-b--pull--m2of3,.g-b--pull--m4of6,.g-b--pull--m8of12{margin-right:66.666%}.g-b--pull--m1of4,.g-b--pull--m2of8,.g-b--pull--m3of12{margin-right:25%}.g-b--pull--m3of4,.g-b--pull--m6of8,.g-b--pull--m9of12{margin-right:75%}.g-b--pull--m1of5,.g-b--pull--m2of10{margin-right:20%}.g-b--pull--m2of5,.g-b--pull--m4of10{margin-right:40%}.g-b--pull--m3of5,.g-b--pull--m6of10{margin-right:60%}.g-b--pull--m4of5,.g-b--pull--m8of10{margin-right:80%}.g-b--pull--m1of6,.g-b--pull--m2of12{margin-right:16.666%}.g-b--pull--m5of6,.g-b--pull--m10of12{margin-right:83.333%}.g-b--pull--m1of8{margin-right:12.5%}.g-b--pull--m3of8{margin-right:37.5%}.g-b--pull--m5of8{margin-right:62.5%}.g-b--pull--m7of8{margin-right:87.5%}.g-b--pull--m1of10{margin-right:10%}.g-b--pull--m3of10{margin-right:30%}.g-b--pull--m7of10{margin-right:70%}.g-b--pull--m9of10{margin-right:90%}.g-b--pull--m1of12{margin-right:8.333%}.g-b--pull--m5of12{margin-right:41.666%}.g-b--pull--m7of12{margin-right:58.333%}.g-b--pull--m11of12{margin-right:91.666%}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:400px}#editor{font-size:1rem}}@media screen and (min-width:46.25em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--t1of1{width:100%}.g-b--t1of2,.g-b--t2of4,.g-b--t3of6,.g-b--t4of8,.g-b--t5of10,.g-b--t6of12{width:50%}.g-b--t1of3,.g-b--t2of6,.g-b--t4of12{width:33.333%}.g-b--t2of3,.g-b--t4of6,.g-b--t8of12{width:66.666%}.g-b--t1of4,.g-b--t2of8,.g-b--t3of12{width:25%}.g-b--t3of4,.g-b--t6of8,.g-b--t9of12{width:75%}.g-b--t1of5,.g-b--t2of10{width:20%}.g-b--t2of5,.g-b--t4of10{width:40%}.g-b--t3of5,.g-b--t6of10{width:60%}.g-b--t4of5,.g-b--t8of10{width:80%}.g-b--t1of6,.g-b--t2of12{width:16.666%}.g-b--t5of6,.g-b--t10of12{width:83.333%}.g-b--t1of8{width:12.5%}.g-b--t3of8{width:37.5%}.g-b--t5of8{width:62.5%}.g-b--t7of8{width:87.5%}.g-b--t1of10{width:10%}.g-b--t3of10{width:30%}.g-b--t7of10{width:70%}.g-b--t9of10{width:90%}.g-b--t1of12{width:8.333%}.g-b--t5of12{width:41.666%}.g-b--t7of12{width:58.333%}.g-b--t11of12{width:91.666%}.g-b--push--t1of1{margin-left:100%}.g-b--push--t1of2,.g-b--push--t2of4,.g-b--push--t3of6,.g-b--push--t4of8,.g-b--push--t5of10,.g-b--push--t6of12{margin-left:50%}.g-b--push--t1of3,.g-b--push--t2of6,.g-b--push--t4of12{margin-left:33.333%}.g-b--push--t2of3,.g-b--push--t4of6,.g-b--push--t8of12{margin-left:66.666%}.g-b--push--t1of4,.g-b--push--t2of8,.g-b--push--t3of12{margin-left:25%}.g-b--push--t3of4,.g-b--push--t6of8,.g-b--push--t9of12{margin-left:75%}.g-b--push--t1of5,.g-b--push--t2of10{margin-left:20%}.g-b--push--t2of5,.g-b--push--t4of10{margin-left:40%}.g-b--push--t3of5,.g-b--push--t6of10{margin-left:60%}.g-b--push--t4of5,.g-b--push--t8of10{margin-left:80%}.g-b--push--t1of6,.g-b--push--t2of12{margin-left:16.666%}.g-b--push--t5of6,.g-b--push--t10of12{margin-left:83.333%}.g-b--push--t1of8{margin-left:12.5%}.g-b--push--t3of8{margin-left:37.5%}.g-b--push--t5of8{margin-left:62.5%}.g-b--push--t7of8{margin-left:87.5%}.g-b--push--t1of10{margin-left:10%}.g-b--push--t3of10{margin-left:30%}.g-b--push--t7of10{margin-left:70%}.g-b--push--t9of10{margin-left:90%}.g-b--push--t1of12{margin-left:8.333%}.g-b--push--t5of12{margin-left:41.666%}.g-b--push--t7of12{margin-left:58.333%}.g-b--push--t11of12{margin-left:91.666%}.g-b--pull--t1of1{margin-right:100%}.g-b--pull--t1of2,.g-b--pull--t2of4,.g-b--pull--t3of6,.g-b--pull--t4of8,.g-b--pull--t5of10,.g-b--pull--t6of12{margin-right:50%}.g-b--pull--t1of3,.g-b--pull--t2of6,.g-b--pull--t4of12{margin-right:33.333%}.g-b--pull--t2of3,.g-b--pull--t4of6,.g-b--pull--t8of12{margin-right:66.666%}.g-b--pull--t1of4,.g-b--pull--t2of8,.g-b--pull--t3of12{margin-right:25%}.g-b--pull--t3of4,.g-b--pull--t6of8,.g-b--pull--t9of12{margin-right:75%}.g-b--pull--t1of5,.g-b--pull--t2of10{margin-right:20%}.g-b--pull--t2of5,.g-b--pull--t4of10{margin-right:40%}.g-b--pull--t3of5,.g-b--pull--t6of10{margin-right:60%}.g-b--pull--t4of5,.g-b--pull--t8of10{margin-right:80%}.g-b--pull--t1of6,.g-b--pull--t2of12{margin-right:16.666%}.g-b--pull--t5of6,.g-b--pull--t10of12{margin-right:83.333%}.g-b--pull--t1of8{margin-right:12.5%}.g-b--pull--t3of8{margin-right:37.5%}.g-b--pull--t5of8{margin-right:62.5%}.g-b--pull--t7of8{margin-right:87.5%}.g-b--pull--t1of10{margin-right:10%}.g-b--pull--t3of10{margin-right:30%}.g-b--pull--t7of10{margin-right:70%}.g-b--pull--t9of10{margin-right:90%}.g-b--pull--t1of12{margin-right:8.333%}.g-b--pull--t5of12{margin-right:41.666%}.g-b--pull--t7of12{margin-right:58.333%}.g-b--pull--t11of12{margin-right:91.666%}.splashscreen-dillinger{width:500px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--save-to,.menu .menu-item--import-from{display:block}.menu .menu-item--preview,.menu .menu-item--save-to.in-sidebar,.menu .menu-item--import-from.in-sidebar{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog{font-size:1.25rem}.enter-zen-mode{display:block}.close-zen-mode{right:3rem;top:3rem}#zen{font-size:1.25rem;width:500px}.split-editor{border-right:1px solid #E8E8E8;float:left;height:calc(100vh - 172px);-webkit-overflow-scrolling:touch;padding-right:16px;width:50%}.show-preview .split-editor{display:block}.split-preview{display:block;float:right;height:calc(100vh - 172px);-webkit-overflow-scrolling:touch;position:relative;top:0;width:50%}#editor{font-size:1rem}}@media screen and (min-width:62.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.g{margin-left:-16px;margin-right:-16px}.g-b{padding-left:16px;padding-right:16px}.g-b--d1of1{width:100%}.g-b--d1of2,.g-b--d2of4,.g-b--d3of6,.g-b--d4of8,.g-b--d5of10,.g-b--d6of12{width:50%}.g-b--d1of3,.g-b--d2of6,.g-b--d4of12{width:33.333%}.g-b--d2of3,.g-b--d4of6,.g-b--d8of12{width:66.666%}.g-b--d1of4,.g-b--d2of8,.g-b--d3of12{width:25%}.g-b--d3of4,.g-b--d6of8,.g-b--d9of12{width:75%}.g-b--d1of5,.g-b--d2of10{width:20%}.g-b--d2of5,.g-b--d4of10{width:40%}.g-b--d3of5,.g-b--d6of10{width:60%}.g-b--d4of5,.g-b--d8of10{width:80%}.g-b--d1of6,.g-b--d2of12{width:16.666%}.g-b--d5of6,.g-b--d10of12{width:83.333%}.g-b--d1of8{width:12.5%}.g-b--d3of8{width:37.5%}.g-b--d5of8{width:62.5%}.g-b--d7of8{width:87.5%}.g-b--d1of10{width:10%}.g-b--d3of10{width:30%}.g-b--d7of10{width:70%}.g-b--d9of10{width:90%}.g-b--d1of12{width:8.333%}.g-b--d5of12{width:41.666%}.g-b--d7of12{width:58.333%}.g-b--d11of12{width:91.666%}.g-b--push--d1of1{margin-left:100%}.g-b--push--d1of2,.g-b--push--d2of4,.g-b--push--d3of6,.g-b--push--d4of8,.g-b--push--d5of10,.g-b--push--d6of12{margin-left:50%}.g-b--push--d1of3,.g-b--push--d2of6,.g-b--push--d4of12{margin-left:33.333%}.g-b--push--d2of3,.g-b--push--d4of6,.g-b--push--d8of12{margin-left:66.666%}.g-b--push--d1of4,.g-b--push--d2of8,.g-b--push--d3of12{margin-left:25%}.g-b--push--d3of4,.g-b--push--d6of8,.g-b--push--d9of12{margin-left:75%}.g-b--push--d1of5,.g-b--push--d2of10{margin-left:20%}.g-b--push--d2of5,.g-b--push--d4of10{margin-left:40%}.g-b--push--d3of5,.g-b--push--d6of10{margin-left:60%}.g-b--push--d4of5,.g-b--push--d8of10{margin-left:80%}.g-b--push--d1of6,.g-b--push--d2of12{margin-left:16.666%}.g-b--push--d5of6,.g-b--push--d10of12{margin-left:83.333%}.g-b--push--d1of8{margin-left:12.5%}.g-b--push--d3of8{margin-left:37.5%}.g-b--push--d5of8{margin-left:62.5%}.g-b--push--d7of8{margin-left:87.5%}.g-b--push--d1of10{margin-left:10%}.g-b--push--d3of10{margin-left:30%}.g-b--push--d7of10{margin-left:70%}.g-b--push--d9of10{margin-left:90%}.g-b--push--d1of12{margin-left:8.333%}.g-b--push--d5of12{margin-left:41.666%}.g-b--push--d7of12{margin-left:58.333%}.g-b--push--d11of12{margin-left:91.666%}.g-b--pull--d1of1{margin-right:100%}.g-b--pull--d1of2,.g-b--pull--d2of4,.g-b--pull--d3of6,.g-b--pull--d4of8,.g-b--pull--d5of10,.g-b--pull--d6of12{margin-right:50%}.g-b--pull--d1of3,.g-b--pull--d2of6,.g-b--pull--d4of12{margin-right:33.333%}.g-b--pull--d2of3,.g-b--pull--d4of6,.g-b--pull--d8of12{margin-right:66.666%}.g-b--pull--d1of4,.g-b--pull--d2of8,.g-b--pull--d3of12{margin-right:25%}.g-b--pull--d3of4,.g-b--pull--d6of8,.g-b--pull--d9of12{margin-right:75%}.g-b--pull--d1of5,.g-b--pull--d2of10{margin-right:20%}.g-b--pull--d2of5,.g-b--pull--d4of10{margin-right:40%}.g-b--pull--d3of5,.g-b--pull--d6of10{margin-right:60%}.g-b--pull--d4of5,.g-b--pull--d8of10{margin-right:80%}.g-b--pull--d1of6,.g-b--pull--d2of12{margin-right:16.666%}.g-b--pull--d5of6,.g-b--pull--d10of12{margin-right:83.333%}.g-b--pull--d1of8{margin-right:12.5%}.g-b--pull--d3of8{margin-right:37.5%}.g-b--pull--d5of8{margin-right:62.5%}.g-b--pull--d7of8{margin-right:87.5%}.g-b--pull--d1of10{margin-right:10%}.g-b--pull--d3of10{margin-right:30%}.g-b--pull--d7of10{margin-right:70%}.g-b--pull--d9of10{margin-right:90%}.g-b--pull--d1of12{margin-right:8.333%}.g-b--pull--d5of12{margin-right:41.666%}.g-b--pull--d7of12{margin-right:58.333%}.g-b--pull--d11of12{margin-right:91.666%}.splashscreen-dillinger{width:700px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{font-size:1.25rem;margin-bottom:.89999rem;padding-top:.10001rem}.menu .menu-item--export-as{display:block}.menu .menu-item--preview{display:none}.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#zen{width:700px}#editor{font-size:1rem}}@media screen and (min-width:87.5em){html{font-size:.875em}body{font-size:1rem}ul,ol{margin-bottom:.83999rem;padding-top:.16001rem}p{padding-top:.66001rem}p,pre{margin-bottom:1.33999rem}pre,blockquote p{font-size:1rem;padding-top:.66001rem}blockquote p{margin-bottom:.33999rem}h1{font-size:2.0571429rem;margin-bottom:.21999rem;padding-top:.78001rem}h2{font-size:1.953125rem;margin-bottom:.1835837rem;padding-top:.8164163rem}h3{font-size:1.6457143rem;margin-bottom:.07599rem;padding-top:.92401rem}h4{font-size:1.5625rem;margin-bottom:.546865rem;padding-top:.453135rem}h5{font-size:1.25rem;margin-bottom:-.56251rem;padding-top:.56251rem}h6{font-size:1rem;margin-bottom:-.65001rem;padding-top:.65001rem}.splashscreen-dillinger{width:800px}.splashscreen p{font-size:1.25rem;margin-bottom:1.43749rem;padding-top:.56251rem}.title{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.title-document{margin-bottom:.89999rem;padding-top:.10001rem}.title-document,.settings a{font-size:1.25rem}.words{font-size:.8rem;margin-bottom:.77999rem;padding-top:.22001rem}.modal--dillinger.about .modal-dialog,#zen{font-size:1.25rem}#editor{font-size:1rem}}@media screen and (max-width:46.1875em){.editor-header{display:none}.editor-header--first{display:block;width:100%}}</style></head><body id="preview"> <p>The not so obvious keyboard shortcuts:</p> <hr> <table> <thead> <tr> <th>Action</th> <th>Windows</th> <th>Mac</th> <th>KDE</th> <th>Gnome</th> </tr> </thead> <tbody> <tr> <td>Quit</td> <td><code>Ctrl+Q</code></td> <td>same</td> <td>same</td> <td>same</td> </tr> <tr> <td>Focus search bar</td> <td><code>Ctrl+F</code></td> <td>same</td> <td>same</td> <td>same</td> </tr> <tr> <td>Next view</td> <td><code>Ctrl+Tab</code>, <code>Forward</code>, <code>Ctrl+F6</code></td> <td><code>Ctrl+}</code>, <code>Forward</code>, <code>Ctrl+Tab</code></td> <td><code>Ctrl+Tab</code>, <code>Forward</code>, <code>Ctrl+Comma</code></td> <td><code>Ctrl+Tab</code>, <code>Forward</code></td> </tr> <tr> <td>Previous view</td> <td><code>Ctrl+Shift+Tab</code>, <code>Back</code>, <code>Ctrl+Shift+F6</code></td> <td><code>Ctrl+{</code>, <code>Back</code>, <code>Ctrl+Shift+Tab</code></td> <td><code>Ctrl+Shift+Tab</code>, <code>Back</code>, <code>Ctrl+Period</code></td> <td><code>Ctrl+Shift+Tab</code>, <code>Back</code></td> </tr> <tr> <td>Next in search history</td> <td><code>Alt+Right</code>, <code>Shift+Backspace</code></td> <td><code>Ctrl+]</code></td> <td><code>Alt+Right</code></td> <td><code>Alt+Right</code></td> </tr> <tr> <td>Previous in search history</td> <td><code>Alt+Left</code>, <code>Backspace</code></td> <td><code>Ctrl+[</code></td> <td><code>Alt+Left</code></td> <td><code>Alt+Left</code></td> </tr> <tr> <td>Help</td> <td><code>F1</code></td> <td><code>Ctrl+?</code></td> <td><code>F1</code></td> <td><code>F1</code></td> </tr> <tr> <td>Toggle gallery menu</td> <td><code>Alt+G</code></td> <td>same</td> <td>same</td> <td>same</td> </tr> <tr> <td>Toggle view mode</td> <td><code>Alt+Space</code></td> <td>same</td> <td>same</td> <td>same</td> </tr> <tr> <td>Settings</td> <td><code>Ctrl+P</code></td> <td>same</td> <td>same</td> <td>same</td> </tr> </tbody> </table> </body></html> """ )
from django.conf import settings from django.conf.urls.static import static from django.urls import path, re_path,include from django.contrib.auth import views from rest_framework.routers import DefaultRouter, SimpleRouter from mpesa.api.views import MakeC2BPayment, MakeLNMPayment router = SimpleRouter() router.register('LNMPayment', MakeLNMPayment) router.register('C2BPayment', MakeC2BPayment) urlpatterns = [ path('auth/', include('rest_auth.urls')), path('registration/', include('rest_auth.registration.urls')), path('', include(router.urls)), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
import numpy as np from functools import partial from bokeh.layouts import column, row, layout from bokeh.models import ColumnDataSource, Slider, Button from bokeh.themes import Theme from bokeh.io import show from bokeh.plotting import figure, output_file, Column from bokeh.models import DataTable, TableColumn, PointDrawTool, ColumnDataSource, CrosshairTool, CDSView, BooleanFilter from bokeh.events import DoubleTap from bokeh.models.widgets import TextInput from bokeh.palettes import viridis import segmentation import bootcamp_utils def _check_ims(ims): if not segmentation._check_array_like(ims): raise RuntimeError("The given ims object is not array like, it is " + str(type(ims))) [segmentation._check_image_input(im) for im in ims] def point_label(ims, point_size=3, table_height=200, crosshair_tool_alpha=0.5, point_tool_color='white'): _check_ims(ims) ims = np.array(ims) max_height = max(np.array([b.shape for b in ims])[:, 0]) max_width = max(np.array([b.shape for b in ims])[:, 1]) point_labels = ColumnDataSource({'x': [], 'y': [], 'frame': []}) def modify_doc(doc): im_num = [0,] images = [np.pad(im, ((max_height-im.shape[0], 0), (0, max_width-im.shape[1])), 'constant') for im in ims] plot, source = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1]], return_im=True) source = source.data_source booleans = [True if frame == im_num[-1] else False for frame in point_labels.data['frame']] view = CDSView(source=point_labels, filters=[BooleanFilter(booleans)]) renderer = plot.scatter(x='x', y='y', source=point_labels, view=view, color=point_tool_color, size=point_size) columns = [TableColumn(field="x", title="x"), TableColumn(field="y", title="y"), TableColumn(field='frame', title='frame')] table = DataTable(source=point_labels, columns=columns, editable=True, height=table_height) draw_tool = PointDrawTool(renderers=[renderer], empty_value=im_num[-1]) plot.add_tools(draw_tool) plot.add_tools(CrosshairTool(line_alpha=crosshair_tool_alpha)) plot.toolbar.active_tap = draw_tool def update_image(new_ind): _, data = bootcamp_utils.viz.bokeh_imshow(images[new_ind], return_im=True) data = data.data_source source.data = data.data def callback_point_view(event): booleans = [True if frame == im_num[-1] else False for frame in point_labels.data['frame']] view = CDSView(source=point_labels, filters=[BooleanFilter(booleans)]) renderer.view = view def callback_slider(attr, old, new): update_image(new) im_num.append(int(new)) draw_tool.empty_value = im_num[-1] callback_point_view('tap') def callback_button(direction): new = im_num[-1]+direction if (((len(images) - 1) < new and direction == 1) or (new == -1 and direction == -1)): return None update_image(new) im_num.append(new) draw_tool.empty_value = im_num[-1] callback_point_view('tap') slider = Slider(start=0, end=len(images), value=0, step=1, title="Frame Number") slider.on_change('value', callback_slider) button_back = Button(label='back',button_type="success") button_back.on_click(partial(callback_button, direction=-1)) button_forward = Button(label='forward',button_type="success") button_forward.on_click(partial(callback_button, direction=1)) plot.on_event('tap', callback_point_view) doc.add_root(column(row(slider), plot, row(button_back, button_forward), table)) show(modify_doc) return point_labels def button_label(ims, button_values=('beetle', 'ant')): _check_ims(ims) ims = np.array(ims) max_height = max(np.array([b.shape for b in ims])[:, 0]) max_width = max(np.array([b.shape for b in ims])[:, 1]) frame_labels = ColumnDataSource({'type': [], 'frame': []}) def modify_doc(doc): im_num = [0,] images = [np.pad(im, ((max_height-im.shape[0],0), (0, max_width-im.shape[1])), 'constant') for im in ims] plot, source = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1]], return_im=True) source = source.data_source columns = [TableColumn(field='type', title='type'), TableColumn(field='frame', title='frame')] table = DataTable(source=frame_labels, columns=columns, editable=True, height=200) plot.add_tools(CrosshairTool(line_alpha=0.5)) def callback(attr, old, new): im_num.append(int(new)) temp_plot, data = bootcamp_utils.viz.bokeh_imshow(images[int(new)], return_im=True) data = data.data_source source.data = data.data plot.x_range.end = temp_plot.x_range.end #plot.plot_width = temp_plot.plot_width #layout.children[1] = plot def callback_button(direction): if (((len(images) - 2) < im_num[-1] and direction == 1) or (im_num[-1] == 0 and direction == -1)): return None _, data = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1]+direction], return_im=True) im_num.append(im_num[-1]+direction) data = data.data_source source.data = data.data callback_point_view('tap') def callback_label_button(value): new_data = {'type': [value], 'frame': [im_num[-1]]} frame_labels.stream(new_data) if (len(images) - 2) < im_num[-1]: return None _, data = bootcamp_utils.viz.bokeh_imshow(images[im_num[-1]+1], return_im=True) im_num.append(im_num[-1]+1) data = data.data_source source.data = data.data slider = Slider(start=0, end=len(images)-1, value=0, step=1, title="Frame Number") slider.on_change('value', callback) button_back = Button(label='back',button_type="success") button_back.on_click(partial(callback_button, direction=-1)) button_forward = Button(label='forward',button_type="success") button_forward.on_click(partial(callback_button, direction=1)) label_buttons = [Button(label=value, button_type='success') for value in button_values] [button.on_click(partial(callback_label_button, value=value)) for button, value in zip(label_buttons, button_values)] #for a grid layout of the buttons, we need to pad the list with an empty spot if the button count is not even if not np.isclose(len(label_buttons) % 2, 0): label_buttons.append(Button(label='')) buttons = np.reshape(label_buttons, (-1,2)) buttons = buttons.tolist() layout_list = [[slider], [plot], [button_back, button_forward]] [layout_list.append(button) for button in buttons] layout_list.append([table]) doc.add_root(layout(layout_list)) show(modify_doc) return frame_labels
def str2bool(s): if s.lower() == "true": return True elif s.lower() == "false": return False else: raise BooleanConversionException("can not convert %s to boolean" % s) class BooleanConversionException(Exception): pass
from matplotlib import pyplot as plt source_data = 'day7/input.txt' with open(source_data, 'r') as f: initial_state = [x.replace('\n', '').split(',') for x in f.readlines()] initial_list = [int(item) for sublist in initial_state for item in sublist] initial_state = {x:0 for x in range(max(initial_list) + 1)} for value in initial_list: initial_state[value] += 1 costs = {} for final_location in range(max(initial_list) + 1): cost = 0 for key, value in initial_state.items(): cost += (abs(key - final_location) + 1) / 2 * abs(key - final_location) * value costs[final_location] = cost # plt.plot([x for x in costs.values()]) # plt.savefig('day7/debug2_input.png', dpi=500) print(min(costs.values()))
# # The Python Imaging Library. # $Id$ # # GD file handling # # History: # 1996-04-12 fl Created # # Copyright (c) 1997 by Secret Labs AB. # Copyright (c) 1996 by Fredrik Lundh. # # See the README file for information on usage and redistribution. # # NOTE: This format cannot be automatically recognized, so the # class is not registered for use with Image.open(). To open a # gd file, use the GdImageFile.open() function instead. # THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This # implementation is provided for convenience and demonstrational # purposes only. from . import ImageFile, ImagePalette from ._binary import i8, i16be as i16, i32be as i32 __version__ = "0.1" ## # Image plugin for the GD uncompressed format. Note that this format # is not supported by the standard <b>Image.open</b> function. To use # this plugin, you have to import the <b>GdImageFile</b> module and # use the <b>GdImageFile.open</b> function. class GdImageFile(ImageFile.ImageFile): format = "GD" format_description = "GD uncompressed images" def _open(self): # Header s = self.fp.read(1037) if not i16(s[:2]) in [65534, 65535]: raise SyntaxError("Not a valid GD 2.x .gd file") self.mode = "L" # FIXME: "P" self._size = i16(s[2:4]), i16(s[4:6]) trueColor = i8(s[6]) trueColorOffset = 2 if trueColor else 0 # transparency index tindex = i32(s[7+trueColorOffset:7+trueColorOffset+4]) if tindex < 256: self.info["transparency"] = tindex self.palette = ImagePalette.raw("XBGR", s[7+trueColorOffset+4:7+trueColorOffset+4+256*4]) self.tile = [("raw", (0, 0)+self.size, 7+trueColorOffset+4+256*4, ("L", 0, 1))] def open(fp, mode="r"): """ Load texture from a GD image file. :param filename: GD file name, or an opened file handle. :param mode: Optional mode. In this version, if the mode argument is given, it must be "r". :returns: An image instance. :raises IOError: If the image could not be read. """ if mode != "r": raise ValueError("bad mode") try: return GdImageFile(fp) except SyntaxError: raise IOError("cannot identify this image file")
import logging from rest_framework import status from rest_framework import permissions from rest_framework import renderers as rf_renderers from rest_framework.decorators import api_view from rest_framework.decorators import permission_classes from rest_framework.decorators import renderer_classes from rest_framework.response import Response from rest_framework import viewsets import ozpcenter.model_access as model_access import ozpiwc.hal as hal import ozpiwc.renderers as renderers logger = logging.getLogger('ozp-iwc.' + str(__name__)) class RootApiViewSet(viewsets.ViewSet): """ IWC Root """ permission_classes = (permissions.IsAuthenticated,) renderer_classes = (renderers.RootResourceRenderer, rf_renderers.JSONRenderer) def list(self, request): if not hal.validate_version(request.META.get('HTTP_ACCEPT')): return Response('Invalid version requested', status=status.HTTP_406_NOT_ACCEPTABLE) root_url = request.build_absolute_uri('/') profile = model_access.get_profile(request.user.username) data = hal.create_base_structure(request, hal.generate_content_type(request.accepted_media_type)) data['_links'][hal.APPLICATION_REL] = { "href": '{0!s}self/application/'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type( renderers.ApplicationListResourceRenderer.media_type) } data['_links'][hal.INTENT_REL] = { "href": '{0!s}self/intent/'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type( renderers.IntentListResourceRenderer.media_type) } data['_links'][hal.SYSTEM_REL] = { "href": '{0!s}iwc-api/system/'.format((root_url)), "type": hal.generate_content_type( renderers.SystemResourceRenderer.media_type) } data['_links'][hal.USER_REL] = { "href": '{0!s}self/'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type( renderers.UserResourceRenderer.media_type) } data['_links'][hal.USER_DATA_REL] = { "href": '{0!s}self/data/'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type( renderers.DataObjectListResourceRenderer.media_type) } data['_links'][hal.DATA_ITEM_REL] = { "href": '{0!s}self/data/{{+resource}}'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type(renderers.DataObjectResourceRenderer.media_type), "templated": True } data['_links'][hal.APPLICATION_ITEM_REL] = { "href": '{0!s}listing/{{+resource}}/'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type(renderers.ApplicationResourceRenderer.media_type), "templated": True } # add embedded data data["_embedded"][hal.USER_REL] = { "username": profile.user.username, "name": profile.display_name, "_links": { "self": { "href": '{0!s}self/'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type( renderers.UserResourceRenderer.media_type) } } } data["_embedded"][hal.SYSTEM_REL] = { "version": '1.0', "name": 'TBD', "_links": { "self": { "href": '{0!s}system/'.format((hal.get_abs_url_for_iwc(request))), "type": hal.generate_content_type( renderers.SystemResourceRenderer.media_type) } } } return Response(data) class UserViewSet(viewsets.ViewSet): """ User info """ permission_classes = (permissions.IsAuthenticated,) renderer_classes = (renderers.RootResourceRenderer, rf_renderers.JSONRenderer) def list(self, request): if not hal.validate_version(request.META.get('HTTP_ACCEPT')): return Response('Invalid version requested', status=status.HTTP_406_NOT_ACCEPTABLE) profile = model_access.get_profile(request.user.username) data = {'username': profile.user.username, 'id': profile.id, 'display_name': profile.display_name} data = hal.add_hal_structure(data, request, hal.generate_content_type( request.accepted_media_type)) return Response(data)
#!/usr/bin/env pnpython4 # # Rename nodal fcnt file names to RL_S.0.x.rg16 filename format. # # Input: List of files to rename in a file (one per line), # output directory for links # # Usage: unsimpleton list_of_files_to_link out_directory # # Steve Azevedo, August 2016 # import argparse import sys import os import logging from ph5.core import segdreader PROG_VERSION = '2018.268' LOGGER = logging.getLogger(__name__) def get_args(): ''' Get inputs ''' global ARGS parser = argparse.ArgumentParser() parser.description = ("A command line utility to link fairfield SEG-D " "file names that expose information about the " "contents of the file, ie. makes file names for " "carbon units. v{0}" .format(PROG_VERSION)) parser.add_argument("-f", "--filelist", dest="segdfilelist", help="The list of SEG-D files to link.", required=True) parser.add_argument("-d", "--linkdir", dest="linkdirectory", help="Name directory to place renamed links.", required=True) parser.add_argument("--hardlinks", dest="hardlinks", action="store_true", help="Create hard links inplace of soft links.") ARGS = parser.parse_args() if not os.path.exists(ARGS.segdfilelist): LOGGER.error("Can not read {0}!".format(ARGS.segdfilelist)) sys.exit() if not os.path.exists(ARGS.linkdirectory): try: os.mkdir(ARGS.linkdirectory) except Exception as e: LOGGER.error(e.message) sys.exit() def print_container(container): keys = container.keys() for k in keys: print k, container[k] print '-' * 80 def general_headers(sd): sd.process_general_headers() def channel_set_descriptors(sd): sd.process_channel_set_descriptors() def extended_headers(sd): sd.process_extended_headers() def external_header(sd): sd.process_external_headers() def trace_headers(sd): n = 1 print "*** Trace Header ***", n sd.process_trace_headers() print_container(sd.trace_headers.trace_header) i = 1 for c in sd.trace_headers.trace_header_N: print i i += 1 print_container(c) sd.read_trace(sd.samples) while True: if sd.isEOF(): break print "*** Trace Header ***", n sd.process_trace_headers() print_container(sd.trace_headers.trace_header) i = 1 for c in sd.trace_headers.trace_header_N: print i i += 1 print_container(c) n += 1 sd.read_trace(sd.samples) print "There were {0} traces.".format(n) def main(): global RH, TH TH = [] get_args() outpath = ARGS.linkdirectory with open(ARGS.segdfilelist) as fh: lh = open("unsimpleton.log", 'a+') while True: line = fh.readline() if not line: break filename = line.strip() if not os.path.exists(filename): LOGGER.warning("Can't find: {0}".format(filename)) continue RH = segdreader.ReelHeaders() try: sd = segdreader.Reader(infile=filename) except BaseException: LOGGER.error( "Failed to properly read {0}.".format(filename)) sys.exit() general_headers(sd) channel_set_descriptors(sd) extended_headers(sd) external_header(sd) line_number = sd.reel_headers.extended_header_3['line_number'] receiver_point = sd.reel_headers.extended_header_3[ 'receiver_point'] sd.reel_headers.general_header_block_2['file_version_number'] id_number = sd.reel_headers.extended_header_1['id_number'] outfile = "PIC_{0}_{1}_{3}.0.0.rg{2}".format( line_number, receiver_point, 16, id_number) linkname = os.path.join(outpath, outfile) i = 0 while os.path.exists(linkname): i += 1 outfile = "PIC_{0}_{1}_{4}.0.{3}.rg{2}".format( line_number, receiver_point, 16, i, id_number) linkname = os.path.join(outpath, outfile) try: if ARGS.hardlinks is True: print filename, 'hard->', linkname try: os.link(filename, linkname) except Exception as e: LOGGER.error( "Failed to create HARD link:\n{0}" .format(e.message)) sys.exit() else: print filename, 'soft->', linkname try: os.symlink(filename, linkname) except Exception as e: LOGGER.error( "Failed to create soft link:\n{0}" .format(e.message)) sys.exit() lh.write("{0} -> {1}\n".format(filename, linkname)) except Exception as e: print e.message lh.close() if __name__ == '__main__': main()
# This sample tests the type analyzer's handling of a variant # of the TypedDict "alternate syntax" defined in the Python docs. from typing import TypedDict Movie = TypedDict("Movie", name=str, year=int) def get_movie_name(movie: Movie): return movie["name"] name2 = get_movie_name({"name": "ET", "year": 1982}) movie1: Movie = {"name": "Blade Runner", "year": 1982} movie2: Movie = { "name": "Blade Runner", # This should generate an error because # the type is incorrect. "year": "1982", } movie3: Movie = { # This should generate an error because # all keys are required. "name": "Blade Runner" } movie4: Movie = { # This should generate an error because # the key name is not supported. "name2": "Blade Runner" }
#!/usr/bin/env python # # Public Domain 2014-2016 MongoDB, Inc. # Public Domain 2008-2014 WiredTiger, Inc. # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the public domain. We make this dedication for the benefit # of the public at large and to the detriment of our heirs and # successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import os, struct from suite_subprocess import suite_subprocess import wiredtiger, wttest # test_util11.py # Utilities: wt list class test_util11(wttest.WiredTigerTestCase, suite_subprocess): tablenamepfx = 'test_util11.' session_params = 'key_format=S,value_format=S' def populate(self, tablename): """ Insert some simple entries into the table """ cursor = self.session.open_cursor('table:' + tablename, None, None) cursor['SOMEKEY'] = 'SOMEVALUE' cursor.close() def test_list_none(self): """ Test list in a 'wt' process, with no tables """ # Construct what we think we'll find filelist = '' outfile = "listout.txt" self.runWt(["list"], outfilename=outfile) self.check_file_content(outfile, filelist) def test_list(self): """ Test list in a 'wt' process, with a mix of populated and empty tables """ pfx = self.tablenamepfx params = self.session_params self.session.create('table:' + pfx + '5', params) self.session.create('table:' + pfx + '3', params) self.session.create('table:' + pfx + '1', params) self.session.create('table:' + pfx + '2', params) self.session.create('table:' + pfx + '4', params) self.populate(pfx + '2') self.populate(pfx + '3') # Construct what we think we'll find tablelist = '' for i in range(1, 6): tablelist += 'table:' + pfx + str(i) + '\n' outfile = "listout.txt" self.runWt(["list", "table:"], outfilename=outfile) self.check_file_content(outfile, tablelist) def test_list_drop(self): """ Test list in a 'wt' process, with a mix of populated and empty tables, after some tables have been dropped. """ pfx = self.tablenamepfx params = self.session_params self.session.create('table:' + pfx + '5', params) self.session.create('table:' + pfx + '3', params) self.session.create('table:' + pfx + '1', params) self.session.create('table:' + pfx + '2', params) self.session.create('table:' + pfx + '4', params) self.populate(pfx + '2') self.populate(pfx + '3') self.session.drop('table:' + pfx + '2', None) self.session.drop('table:' + pfx + '4', None) # Construct what we think we'll find tablelist = ''.join('table:' + pfx + str(i) + '\n' for i in (1, 3, 5)) outfile = "listout.txt" self.runWt(["list", "table:"], outfilename=outfile) self.check_file_content(outfile, tablelist) def test_list_drop_all(self): """ Test list in a 'wt' process, with a mix of populated and empty tables, after all tables have been dropped. """ pfx = self.tablenamepfx params = self.session_params self.session.create('table:' + pfx + '5', params) self.session.create('table:' + pfx + '3', params) self.session.create('table:' + pfx + '1', params) self.session.create('table:' + pfx + '2', params) self.session.create('table:' + pfx + '4', params) self.populate(pfx + '2') self.populate(pfx + '3') self.session.drop('table:' + pfx + '5', None) self.session.drop('table:' + pfx + '4', None) self.session.drop('table:' + pfx + '3', None) self.session.drop('table:' + pfx + '2', None) self.session.drop('table:' + pfx + '1', None) # Construct what we think we'll find filelist = '' outfile = "listout.txt" self.runWt(["list"], outfilename=outfile) self.check_file_content(outfile, filelist) if __name__ == '__main__': wttest.run()
from src.server.server import Server from src.constant import Constant def compute_inter_sever_cost(servers): # servers is a list of server cost = 0 for server in servers: for node in server.graph: if server.graph.nodes[node]['node_type'] == Constant.NON_PRIMARY_COPY or server.graph.nodes[node][ 'node_type'] == Constant.VIRTUAL_PRIMARY_COPY: cost = cost + server.graph.nodes[node]['write_freq'] return cost def compute_inter_sever_cost_graph(graphs): # servers is a list of server cost = 0 for graph in graphs: for node in graph: if graph.nodes[node]['node_type'] == Constant.NON_PRIMARY_COPY or graph.nodes[node][ 'node_type'] == Constant.VIRTUAL_PRIMARY_COPY: cost = cost + graph.nodes[node]['write_freq'] return cost
banner = """ ██╗ ██╗██╗███████╗██████╗ ██║ ██║██║██╔════╝██╔══██╗ ██║ █╗ ██║██║███████╗██████╔╝ ██║███╗██║██║╚════██║██╔═══╝ ╚███╔███╔╝██║███████║██║ ╚══╝╚══╝ ╚═╝╚══════╝╚═╝ 0.0.1-beta JIMUT(TM) """ print(banner)
#!/usr/bin/env python import argparse import configparser import datetime from decimal import Decimal import json import sys import time import os import cbpro import requests # TODO implement allowlist to only allow requests to coinbase and pushover domains try: import http.client as http_client except ImportError: # Python 2 import httplib as http_client def get_timestamp(pretty_print=True): ts = time.time() if pretty_print: return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") else: return ts class ConfigurationError(Exception): pass class PushoverClient: def __init__(self, url, application_token, user_key): self.url = url self.application_token = application_token self.user_key = user_key def send_message(self, message): response = requests.post( f"{self.url}/1/messages.json", headers={"Content-type": "application/x-www-form-urlencoded"}, data={ "token": self.application_token, "user": self.user_key, "message": message, "timestamp": get_timestamp(pretty_print=False), }, ) if response.ok: print("Push notification successfully sent") else: print("Something went wrong with request to Pushover") return response.ok """ Basic Coinbase Pro DCA buy/sell bot that executes a market order. * CB Pro does not incentivize maker vs taker trading unless you trade over $50k in a 30 day period (0.25% taker, 0.15% maker). Current fees are 0.50% if you make less than $10k worth of trades over the last 30 days. Drops to 0.35% if you're above $10k but below $50k in trades. * Market orders can be issued for as little as $5 of value versus limit orders which must be 0.001 BTC (e.g. $50 min if btc is at $50k). BTC-denominated market orders must be at least 0.0001 BTC. This is meant to be run as a crontab to make regular buys/sells on a set schedule. """ parser = argparse.ArgumentParser( description=""" This is a basic Coinbase Pro DCA buying/selling bot. ex: BTC-USD BUY 14 USD (buy $14 worth of BTC) BTC-USD BUY 0.00125 BTC (buy 0.00125 BTC) ETH-BTC SELL 0.00125 BTC (sell 0.00125 BTC worth of ETH) ETH-BTC SELL 0.1 ETH (sell 0.1 ETH) """, formatter_class=argparse.RawTextHelpFormatter, ) # Required positional arguments parser.add_argument("market_name", help="(e.g. BTC-USD, ETH-BTC, etc)") parser.add_argument("order_side", type=str, choices=["BUY", "SELL"]) parser.add_argument( "amount", type=Decimal, help="The quantity to buy or sell in the amount_currency" ) parser.add_argument("amount_currency", help="The currency the amount is denominated in") # Additional options parser.add_argument( "-sandbox", action="store_true", default=False, dest="sandbox_mode", help="Run against sandbox, skips user confirmation prompt", ) parser.add_argument( "-warn_after", default=300, action="store", type=int, dest="warn_after", help="secs to wait before sending an alert that an order isn't done", ) parser.add_argument( "-j", "--job", action="store_true", default=False, dest="job_mode", help="Suppresses user confirmation prompt", ) parser.add_argument( "-c", "--config", default="settings.conf", dest="config_file", help="Override default config file location", ) parser.add_argument( "-p", "--push_notify", action="store_true", default=False, help="Send push notifications for results of each trade using Pushover", ) parser.add_argument( "-d", "--debug", action="store_true", default=False, help="Log all network requests for debugging", ) if __name__ == "__main__": args = parser.parse_args() print(f"{get_timestamp()}: STARTED: {args}") market_name = args.market_name order_side = args.order_side.lower() amount = args.amount amount_currency = args.amount_currency sandbox_mode = args.sandbox_mode job_mode = args.job_mode warn_after = args.warn_after push_notify = args.push_notify debug = args.debug if debug: http_client.HTTPConnection.debuglevel = 1 if not sandbox_mode and not job_mode: if sys.version_info[0] < 3: # python2.x compatibility response = raw_input("Production purchase! Confirm [Y]: ") # noqa: F821 else: response = input("Production purchase! Confirm [Y]: ") if response != "Y": print("Exiting without submitting purchase.") exit() if push_notify: application_token = os.environ.get("PUSHOVER_APP_TOKEN") user_key = os.environ.get("PUSHOVER_USER_KEY") if not (application_token and user_key): print("Missing application API token and user API key for Pushover") raise ConfigurationError pushover_client = PushoverClient( "https://api.pushover.net:443", application_token, user_key ) if sandbox_mode: config = configparser.ConfigParser() config.read(args.config_file) config_section = "sandbox" key = config.get(config_section, "API_KEY") passphrase = config.get(config_section, "PASSPHRASE") secret = config.get(config_section, "SECRET_KEY") else: key = os.environ.get("COINBASE_PROD_API_KEY") passphrase = os.environ.get("COINBASE_PROD_PASSPHRASE") secret = os.environ.get("COINBASE_PROD_API_SECRET_KEY") if not (key and passphrase and secret): error_message = "Missing API key, key secret or passphrase for Coinbase Pro" print(error_message) if push_notify: pushover_client.send_message(error_message) raise ConfigurationError # Instantiate public and auth API clients if not args.sandbox_mode: auth_client = cbpro.AuthenticatedClient(key, secret, passphrase) else: # Use the sandbox API (requires a different set of API access credentials) auth_client = cbpro.AuthenticatedClient( key, secret, passphrase, api_url="https://api-public.sandbox.pro.coinbase.com", ) public_client = cbpro.PublicClient() # Retrieve dict list of all trading pairs products = public_client.get_products() base_min_size = None base_increment = None quote_increment = None for product in products: if product.get("id") == market_name: base_currency = product.get("base_currency") quote_currency = product.get("quote_currency") base_min_size = Decimal(product.get("base_min_size")).normalize() base_increment = Decimal(product.get("base_increment")).normalize() quote_increment = Decimal(product.get("quote_increment")).normalize() if amount_currency == product.get("quote_currency"): amount_currency_is_quote_currency = True elif amount_currency == product.get("base_currency"): amount_currency_is_quote_currency = False else: raise Exception( f"amount_currency {amount_currency} not in market {market_name}" ) print(json.dumps(product, indent=2)) print(f"base_min_size: {base_min_size}") print(f"quote_increment: {quote_increment}") if amount_currency_is_quote_currency: result = auth_client.place_market_order( product_id=market_name, side=order_side, funds=float(amount.quantize(quote_increment)), ) else: result = auth_client.place_market_order( product_id=market_name, side=order_side, size=float(amount.quantize(base_increment)), ) print(json.dumps(result, sort_keys=True, indent=4)) if "message" in result: order_status = f"Could not place {market_name} {order_side} order\nResponse: {result['message']}" if push_notify: pushover_client.send_message(order_status) print(order_status) exit() if result and "status" in result and result["status"] == "rejected": order_status = f"{market_name} Order rejected" if push_notify: pushover_client.send_message(order_status) print(f"{get_timestamp()}: {order_status}") order = result order_id = order["id"] print(f"order_id: {order_id}") """ Wait to see if the order was fulfilled. """ wait_time = 5 total_wait_time = 0 while "status" in order and ( order["status"] == "pending" or order["status"] == "open" ): if total_wait_time > warn_after: order_status = f"{market_name} {order_side} order of {amount} {amount_currency} OPEN/UNFILLED" if push_notify: pushover_client.send_message(order_status) print(order_status) exit() print( f"{get_timestamp()}: Order {order_id} still {order['status']}. Sleeping for {wait_time} (total {total_wait_time})" ) time.sleep(wait_time) total_wait_time += wait_time order = auth_client.get_order(order_id) if "message" in order and order["message"] == "NotFound": order_status = f"{market_name} {order_side} order of {amount} {amount_currency} CANCELLED" if push_notify: pushover_client.send_message(order_status) print(order_status) exit() # Order status is no longer pending! print(json.dumps(order, indent=2)) market_price = ( Decimal(order["executed_value"]) / Decimal(order["filled_size"]) ).quantize(quote_increment) order_status = f"{market_name} {order_side} order of {amount} {amount_currency} {order['status']} @ {market_price} {quote_currency}" if push_notify: pushover_client.send_message(order_status) print(order_status) exit()
#!/usr/bin/python # -*- coding: cp1252 -*- import easygui """ __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2004/04/14 02:38:47 $" """ from PythonCard import model class MyBackground(model.Background): def on_initialize(self, event): # if you have any initialization # including sizer setup, do it here pass def on_Verschlsseln_mouseClick(self, event): import ver ver.do(self.components.path.text ,self.components.dictionarypy.text) def on_Entschlsseln_mouseClick(self, event): if self.components.passwort.text == "4": self.components.Gauge1.value=100 else: import ent ent.do(self.components.path.text ,self.components.dictionarypy.text) def on_neuesDict_mouseClick(self,event): import dict if easygui.buttonbox("Dies wird alle im moment Verschlüsselten dateinen unbrauchbar machen!\nSicher?","",("Ja","Nein"))=="Ja": dict.create() def on_browse_mouseClick(self, event): self.components.path.text=easygui.fileopenbox() if __name__ == '__main__': app = model.Application(MyBackground) app.MainLoop()
""" Downloading the original DES images (10000 * 10000 pixels). These images are the into 100*100 pixels are cut, using random x, y coordinates, these images are known as background sky/noise. The original images are clipped using the World Coordinate System, and are 100*100 pixels in size around stellar/astronomical objects, and these images will be referred to as negativeDES images. These negativeDES images are normalised, as well as composite RGB images are created. """ import sys import os import astropy.table as atpy import numpy as np from negativeDESUtils import getRandomIndices, loadDES, randomSkyClips, clipWCS, normaliseRGB # ---------------------------------------------------------------------------------------------------------------------------------------------------- # MAIN """ Here we call the loadImages function which will declare the varaibles gDES, rDES, iDES. Its is then clipped using the clipImages function. And we write these images to a file in .fits format using writeClippedImagesToFile function. """ table_des = atpy.Table().read("DES/DESGalaxies_18_I_22.fits") # ensuring there is no none numbers in the gmag, rmag, and imag in the DES table. # ensuring that there is no Gmag with values of 99. for key in ['MAG_AUTO_G', 'MAG_AUTO_R', 'MAG_AUTO_I']: table_des = table_des[np.isnan(table_des[key]) == False] table_des = table_des[table_des['MAG_AUTO_G'] < 24] len_tab_des = len(table_des) training_size = 12659 testing_size = 2000 random_indices = [] training = getRandomIndices(training_size, random_indices, len_tab_des) testing = getRandomIndices(testing_size, random_indices, len_tab_des) print("Training: "+str(training)) print("Testing: "+str(testing)) for i in range(0, len(training)): num = training[i] tile_name = table_des['TILENAME'][num] print(type(tile_name)) g_mag = table_des['MAG_AUTO_G'][num] i_mag = table_des['MAG_AUTO_I'][num] r_mag = table_des['MAG_AUTO_R'][num] ra = table_des['RA'][num] dec = table_des['DEC'][num] print('Gmag: ' + str(g_mag)) print('Imag: ' + str(i_mag)) print('Rmag: ' + str(r_mag)) train_file = 'Training/Negative/' train_dessky = 'Training/DESSky' if not os.path.exists('Training'): os.mkdir('Training') loadDES(tile_name) randomSkyClips(num, tile_name, ra, dec, g_mag, r_mag, i_mag, train_dessky) clipWCS(tile_name, num, g_mag, r_mag, i_mag, ra, dec, train_file) normaliseRGB(num, tile_name, train_file) for i in range(0, len(testing)): num = testing[i] tile_name = table_des['TILENAME'][num] print(type(tile_name)) g_mag = table_des['MAG_AUTO_G'][num] i_mag = table_des['MAG_AUTO_I'][num] r_mag = table_des['MAG_AUTO_R'][num] ra = table_des['RA'][num] dec = table_des['DEC'][num] print('Gmag: ' + str(g_mag)) print('Imag: ' + str(i_mag)) print('Rmag: ' + str(r_mag)) test_file = 'Testing/Negative/' test_dessky = 'Testing/DESSky' if not os.path.exists('Testing'): os.mkdir('Testing') loadDES(tile_name) randomSkyClips(num, tile_name, ra, dec, g_mag, r_mag, i_mag, test_dessky) clipWCS(tile_name, num, g_mag, r_mag, i_mag, ra, dec, test_file) normaliseRGB(num, tile_name, test_file)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = 'semi_simple' __author__ = 'JieYuan' __mtime__ = '19-1-11' """ import numpy as np import pandas as pd from tql.pipe import tqdm, cprint class SimpleSemi(object): def __init__(self, clf, subsample=0.05, n_iter=1, scale_pos=1, mode=None, opt_seed=None): """ :param subsample: :param n_iter: :param scale_pos: 正样本 / 负样本 :param mode: 'p': 从X_test, 只采样正样本 'n': 从X_test, 只采样正样本 None: 从X_test, 采样正+负样本 """ self.clf = clf self.subsample = subsample self.n_iter = n_iter self.scale_pos = scale_pos self.mode = mode self.opt_seed = opt_seed _ = "X_train will stack ≈ {:.2f}% of X_test".format( (1 - (1 - subsample - subsample * scale_pos) ** n_iter) * 100) cprint(_) def fit(self, X, y, X_test): self.X = X self.y = y self.X_test = np.asarray(X_test) for _ in tqdm(range(self.n_iter + 1)): self.clf.fit(self.X, self.y) _ = pd.Series(self.clf.predict_proba(self.X_test)[:, 1]) if self.mode == 'n': pred = _.mask(lambda x: x < x.quantile(self.subsample), 0) elif self.mode == 'p': pred = _.mask(lambda x: x > x.quantile(1 - self.subsample * self.scale_pos), 1) else: pred = (_.mask(lambda x: x < x.quantile(self.subsample), 0) .mask(lambda x: x > x.quantile(1 - self.subsample * self.scale_pos), 1)) pred_ = pred[lambda x: x.isin([0, 1])] pseudo_label_idx = pred_.index no_pseudo_label_idx = pred.index.difference(pseudo_label_idx) self.X = np.row_stack((self.X, self.X_test[pseudo_label_idx])) self.y = np.hstack((self.y, pred_)) self.X_test = self.X_test[no_pseudo_label_idx] return self.clf
from ._version import __version__ from .layer import register_carto_layer from .credentials import load_carto_credentials __all__ = ["__version__", "load_carto_credentials", "register_carto_layer"]
# This module can load passwords from external sources, such as files or # environment variables or KWallet (and no, *not* libsecret -- as much as I # want to use the nifty gi-based libsecret API...). # # It deals with strings (the lowest common denominator), but it's really meant # to be used for storing Base64-encoded keys and not raw passwords. import dbus import os import re import subprocess class KWalletClient(): app_id = "org.eu.nullroute.Secretsd" folder = "Passwords" def __init__(self): self.bus = dbus.SessionBus() self.mgr = self.bus.get_object("org.kde.kwalletd5", "/modules/kwalletd5") self.mgr = dbus.Interface(self.mgr, "org.kde.KWallet") def __enter__(self): self.wallet = self.mgr.localWallet() self.handle = self.mgr.open(self.wallet, 0, self.app_id) return self def __exit__(self, *argv): self.mgr.disconnectApplication(self.wallet, self.app_id) def get_password(self, name): if self.mgr.hasEntry(self.handle, self.folder, name, self.app_id): return str(self.mgr.readPassword(self.handle, self.folder, name, self.app_id)) else: raise KeyError(name) def set_password(self, name, value): self.mgr.writePassword(self.handle, self.folder, name, value, self.app_id) def _parse_specifier(source): m = re.match(r"^(\w+):(.*)", source) if m: return m.groups() else: # Too easy to end up saving keys in a file named 'kwallet'... #return "file", source raise ValueError("key location must be specified as 'type:rest'") def load_ext_key(source): kind, rest = _parse_specifier(source) if kind == "env": return os.environ[rest] elif kind == "exec": res = subprocess.run(rest, shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, check=True) return res.stdout.decode().strip() elif kind == "file": with open(rest, "r") as fh: return fh.read().strip() elif kind == "kwallet": with KWalletClient() as kw: return kw.get_password(rest or "secretsd master key") elif kind == "libsecret": raise ValueError("cannot load external key from myself") else: raise ValueError("unknown external key source %r" % kind) def store_ext_key(source, key): kind, rest = _parse_specifier(source) if kind == "env": raise ValueError("environment is volatile storage, cannot store keys there") elif kind == "exec": # XXX: Should there be a way to distinguish whether the command is # invoked for load vs store, or should I just remove storing to exec: # because this is an advanced operation and the user can just emulate # it with a temporary file? res = subprocess.run(rest, shell=True, input=key.encode(), check=True) elif kind == "file": with open(rest, "w", opener=lambda p, f: os.open(p, f, 0o400)) as fh: fh.write(key) elif kind == "kwallet": with KWalletClient() as kw: kw.set_password(rest or "secretsd master key", key) elif kind == "libsecret": raise ValueError("cannot store external key in myself") else: raise ValueError("unknown external key source %r" % kind) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("specifier") parser.add_argument("--store-key", metavar="KEY", help="store the specified key (as text)") args = parser.parse_args() arg = args.specifier if key := args.store_key: print(f"Storing key {key!r} to {arg!r}") store_ext_key(arg, key) print(f"Retrieving key from {arg!r}") key = load_ext_key(arg) print(f"The key is {key!r}")
# reference: Liu, Y. and Durlofsky, L.J., 2020. 3D CNN-PCA: A Deep-Learning-Based. Parameterization for Complex Geomodels. arXiv preprint arXiv:2007.08478 import numpy as np import matplotlib.pyplot as plt class PCA(object): def __init__(self, nc=1, nr=1, l=1): self.l = l self.nc = nc self.nr = nr self.xm = np.zeros((nc, 1)) self.usig = np.zeros((nc, l)) self.data_matrix = None self.sig = None self.u = None def construct_pca(self, x): assert x.shape == (self.nc, self.nr) self.data_matrix = x self.xm = np.mean(x, axis=1)[:, None] y = 1. / (np.sqrt(float(self.nr - 1.))) * (x - self.xm) self.u, self.sig, _ = np.linalg.svd(y, full_matrices=False) self.u = self.u[:, :self.l] self.sig = self.sig[:self.l, None] self.usig = np.dot(self.u, np.diag(self.sig[:, 0])) def generate_pca_realization(self, xi, dim=None): if dim is None: assert xi.shape[0] == self.l if xi.shape == (self.l, ): xi = xi[:, None] return self.usig.dot(xi) + self.xm else: assert xi.shape[0] == dim if xi.shape == (dim, ): xi = xi[:, None] return self.usig[:, :dim].dot(xi) + self.xm def get_xi(self, m, dim=None): assert self.u is not None, "Input or calculate U matrix to obtain reconstructed xi" assert m.shape[0] == self.nc if m.shape == (self.nc, ): m = m[:, None] if dim is None: xi = self.u.T.dot(m - self.xm) / self.sig else: xi = self.u[:, :dim].T.dot(m - self.xm) / self.sig[:dim] return xi def energy_plot(self, rel_energy, truncate_point): plt.figure(figsize=(8, 4)) plt.subplot(1, 2, 1) plt.plot(rel_energy) plt.ylabel('Relative Energy', fontsize=12) plt.xlabel('Number of principal components', fontsize=12) plt.subplot(1, 2, 2) plt.plot(rel_energy[:truncate_point]) plt.ylabel('Relative Energy', fontsize=12) plt.xlabel('Number of principal components', fontsize=12) plt.tight_layout() plt.show() def princ_component(self, tol=0.9): cum_energy = np.cumsum(self.sig**2) rel_energy = cum_energy / cum_energy[-1] truncate_point = np.argmin(np.abs(rel_energy - tol)) + 1 print('Principle components: ', truncate_point) return truncate_point, rel_energy
from chainercv.evaluations.eval_detection_voc import calc_detection_voc_ap # NOQA from chainercv.evaluations.eval_detection_voc import calc_detection_voc_prec_rec # NOQA from chainercv.evaluations.eval_detection_voc import eval_detection_voc # NOQA from chainercv.evaluations.eval_instance_segmentation_voc import calc_instance_segmentation_voc_prec_rec # NOQA from chainercv.evaluations.eval_instance_segmentation_voc import eval_instance_segmentation_voc # NOQA from chainercv.evaluations.eval_semantic_segmentation import calc_semantic_segmentation_confusion # NOQA from chainercv.evaluations.eval_semantic_segmentation import calc_semantic_segmentation_iou # NOQA from chainercv.evaluations.eval_semantic_segmentation import eval_semantic_segmentation # NOQA
class ListNode: def __init__(self, val = 0, next = None): self.val = val self.next = next class Solution: def removeElements(self, head, val): dummy = ListNode(0) dummy.next = head prev, curr = dummy, dummy.next while curr: if curr.val == val: prev.next = curr.next else: prev = curr curr = curr.next return dummy.next if __name__ == "__main__": l1 = ListNode(1) l2 = ListNode(2) l3 = ListNode(6) l4 = ListNode(3) l5 = ListNode(4) l6 = ListNode(5) l7 = ListNode(6) l1.next = l2 l2.next = l3 l3.next = l4 l4.next = l5 l5.next = l6 l6.next = l7 val = 6 s = Solution() s.removeElements(l1, val)
from .entfunc import * import pytest ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', "None") TEST_RANCHER_GKE_SERVER_IP = os.environ.get('RANCHER_GKE_SERVER_IP', "None") RKE_K8S_VERSION = os.environ.get('RANCHER_RKE_K8S_VERSION', "v1.15.5-rancher1-1") RANCHER_SERVER_URL = "https://" + TEST_RANCHER_GKE_SERVER_IP + ":8443" RANCHER_API_URL = RANCHER_SERVER_URL + "/v3" token = "" # flannel macvlan cluster def test_deploy_flannel_macvlan(): #node-0 #wait_until_active(RANCHER_SERVER_URL) #global token #token = get_admin_token(RANCHER_SERVER_URL) url = RANCHER_SERVER_URL + "/v3" client = get_admin_client_byToken(url, token) rke_config=get_rke_config(RKE_K8S_VERSION,"multus-flannel-macvlan",DEFAULT_MASTER) cluster = client.create_cluster( name=random_name(), driver="rancherKubernetesEngine", rancherKubernetesEngineConfig=rke_config) assert cluster.state == "provisioning" clusterregistration={"type":"clusterRegistrationToken","clusterId":cluster.id} clusterregistrationtoken=client.create_clusterRegistrationToken(clusterregistration) for num in range(0,1): nodeCommand=clusterregistrationtoken.nodeCommand \ + " --etcd --controlplane --worker --address " + "172.20.115.7" \ + num.__str__() + " --internal-address " + "172.20.115.7" + num.__str__() cmd="sudo tmux send-keys -t " + "kvm:" + num.__radd__(1).__str__() +" \"" +nodeCommand +" \" C-m" ssh_cmd= "ssh -o StrictHostKeyChecking=no -i /src/rancher-validation/.ssh/id_rsa -l jenkins " + RANCHER_SERVER_URL.split(":",2)[1][2:] + " \' " + cmd + " \'" login_cmd="sudo tmux send-keys -t " + "kvm:" + num.__radd__(1).__str__() +" \"ubuntu\" C-m" login_ssh_cmd= "ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=20 -i /src/rancher-validation/.ssh/id_rsa -l jenkins " + RANCHER_SERVER_URL.split(":",2)[1][2:] + " \' " + login_cmd + " \'" print(login_ssh_cmd) run_command(login_ssh_cmd) run_command(login_ssh_cmd) print(ssh_cmd) result=run_command(ssh_cmd) wait_for_nodes_to_become_active(client, cluster, exception_list=[]) time.sleep(10) cluster = wait_for_condition( client, cluster, lambda x: x.state == "active", lambda x: 'State is: ' + x.state, timeout=MACHINE_TIMEOUT) assert cluster.state == "active" # canal macvlan cluster def test_deploy_canal_macvlan(): #node-2 url = RANCHER_SERVER_URL + "/v3" client = get_admin_client_byToken(url, token) rke_config=get_rke_config("v1.15.5-rancher1-1","multus-canal-macvlan",DEFAULT_MASTER) cluster = client.create_cluster( name=random_name(), driver="rancherKubernetesEngine", rancherKubernetesEngineConfig=rke_config) assert cluster.state == "provisioning" clusterregistration={"type":"clusterRegistrationToken","clusterId":cluster.id} clusterregistrationtoken=client.create_clusterRegistrationToken(clusterregistration) for num in range(1,2): nodeCommand=clusterregistrationtoken.nodeCommand \ + " --etcd --controlplane --worker --address " + "172.20.115.7" \ + num.__str__() + " --internal-address " + "172.20.115.7" + num.__str__() cmd="sudo tmux send-keys -t " + "kvm:" + num.__radd__(1).__str__() +" \"" +nodeCommand +" \" C-m" ssh_cmd= "ssh -o StrictHostKeyChecking=no -i /src/rancher-validation/.ssh/id_rsa -l jenkins " + RANCHER_SERVER_URL.split(":",2)[1][2:] + " \' " + cmd + " \'" login_cmd="sudo tmux send-keys -t " + "kvm:" + num.__radd__(1).__str__() +" \"ubuntu\" C-m" login_ssh_cmd= "ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=20 -i /src/rancher-validation/.ssh/id_rsa -l jenkins " + RANCHER_SERVER_URL.split(":",2)[1][2:] + " \' " + login_cmd + " \'" print(login_ssh_cmd) run_command(login_ssh_cmd) run_command(login_ssh_cmd) print(ssh_cmd) result=run_command(ssh_cmd) wait_for_nodes_to_become_active(client, cluster, exception_list=[]) time.sleep(10) cluster = wait_for_condition( client, cluster, lambda x: x.state == "active", lambda x: 'State is: ' + x.state, timeout=MACHINE_TIMEOUT) assert cluster.state == "active" def get_admin_token(RANCHER_SERVER_URL): """Returns a ManagementContext for the default global admin user.""" CATTLE_AUTH_URL = \ RANCHER_SERVER_URL + "/v3-public/localproviders/local?action=login" r = requests.post(CATTLE_AUTH_URL, json={ 'username': 'admin', 'password': 'admin', 'responseType': 'json', }, verify=False) print(r.json()) token = r.json()['token'] print(token) # Change admin password client = rancher.Client(url=RANCHER_SERVER_URL+"/v3", token=token, verify=False) admin_user = client.list_user(username="admin").data admin_user[0].setpassword(newPassword=ADMIN_PASSWORD) # Set server-url settings serverurl = client.list_setting(name="server-url").data client.update(serverurl[0], value=RANCHER_SERVER_URL) return token def get_rke_config(k8s_version, network_plugin, master): ''' :param k8s_version: :param network_plugin: multus-flannel-macvlan ; multus-canal-macvlan :param master: :return:master ''' network = get_rke_network(network_plugin, master) rke_config = { "addonJobTimeout": 30, "ignoreDockerVersion": True, "sshAgentAuth": False, "type": "rancherKubernetesEngineConfig", "kubernetesVersion": k8s_version , "authentication": { "strategy": "x509", "type": "authnConfig" }, "network": network, "ingress": { "provider": "nginx", "type": "ingressConfig" }, "monitoring": { "provider": "metrics-server", "type": "monitoringConfig" }, "services": { "type": "rkeConfigServices", "kubeApi": { "alwaysPullImages": False, "podSecurityPolicy": False, "serviceNodePortRange": "30000-32767", "type": "kubeAPIService" }, "etcd": { "creation": "12h", "extraArgs": { "heartbeat-interval": 500, "election-timeout": 5000 }, "retention": "72h", "snapshot": False, "type": "etcdService", "backupConfig": { "enabled": True, "intervalHours": 12, "retention": 6, "type": "backupConfig" } } } } return rke_config def get_rke_network(plugin,iface): if plugin == "multus-canal-macvlan" : iface_name = "canal_iface" if plugin == "multus-flannel-macvlan": iface_name = "flannel_iface" network = { "plugin": plugin, "type": "networkConfig", "options": { "flannel_backend_type": "vxlan", iface_name: iface } } return network @pytest.fixture(scope='module', autouse="True") def create_project_client(request): wait_until_active(RANCHER_SERVER_URL) global token token = get_admin_token(RANCHER_SERVER_URL)
#!/usr/bin/env python import argparse import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, Pose, TwistStamped from styx_msgs.msg import TrafficLightArray, TrafficLight, Lane, Waypoint from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport from sensor_msgs.msg import Image from cv_bridge import CvBridge import tf import cv2 import pygame import sys import numpy as np import matplotlib.pyplot as plt import math import yaml import os MPS = 0.44704 class GenerateDiagnostics(): def __init__(self, img_vis_ratio, max_history, text_spacing, font_size, camera_topic, config_file): # initialize and subscribe to the camera image and traffic lights topic rospy.init_node('diag_gps_rosbag') self.restricted_speed = 10. self.cv_image = None self.camera_image = None self.lights = [] self.i = 0 self.nwp = None self.ctl = 0 # lists for storing history values self.frame_history = [] self.vel_history = [] self.steering_history = [] self.throttle_history = [] self.brake_history = [] self.max_history_size = max_history self.waypoints = None self.img_rows = 2500 self.img_cols = 2500 self.img_ch = 3 # get waypoint configuration with open(os.getcwd()+'/src/tl_detector/'+config_file, 'r') as myconfig: config_string=myconfig.read() self.config = yaml.load(config_string) self.camera_topic = camera_topic self.sub_raw_camera = None self.bridge = CvBridge() # test different raw image update rates: self.updateRate = 20 # 20 times a second self.state = TrafficLight.UNKNOWN self.last_state = TrafficLight.UNKNOWN self.last_wp = -1 self.state_count = 0 self.current_linear_velocity = 0. self.current_angular_velocity = 0. self.steering_cmd = 0. self.traffic_light_to_waypoint_map = [] self.fwaypointsx = [] self.fwaypointsy = [] self.fwaypointss = [] self.fwaypointx = 0. self.fwaypointy = 0. self.screen = None self.position = None self.theta = None self.lights = [] self.throttle_cmd = None self.steering_cmd = None self.brake_cmd = None # parameters for adjusting the output window size and text output self.img_vis_ratio = img_vis_ratio self.img_vis_font_size = font_size self.img_vis_txt_x = text_spacing self.img_vis_txt_y = text_spacing self.sub_waypoints = rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb) self.sub_fwaypoints = rospy.Subscriber('/final_waypoints', Lane, self.fwaypoints_cb) self.sub_current_pose = rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb) self.sub_current_velocity = rospy.Subscriber('/current_velocity', TwistStamped, self.velocity_cb) self.steering_pub = rospy.Subscriber('/vehicle/steering_cmd', SteeringCmd, self.steering_cb) self.throttle_pub = rospy.Subscriber('/vehicle/throttle_cmd', ThrottleCmd, self.throttle_cb) self.brake_pub = rospy.Subscriber('/vehicle/brake_cmd', BrakeCmd, self.brake_cb) self.sub_traffic_lights = rospy.Subscriber('/vehicle/traffic_lights', TrafficLightArray, self.traffic_cb) # reset the max_open_warning plt.rcParams.update({'figure.max_open_warning': 0}) self.loop() def project_to_image_plane(self, point_in_world): """Project point from 3D world coordinates to 2D camera image location Args: point_in_world (Point): 3D location of a point in the world Returns: x (int): x coordinate of target point in image y (int): y coordinate of target point in image """ fx = self.config.camera_info.focal_length_x fy = self.config.camera_info.focal_length_y image_width = self.config.camera_info.image_width image_height = self.config.camera_info.image_height # get transform between pose of camera and world frame trans = None try: now = rospy.Time.now() self.listener.waitForTransform("/base_link", "/world", now, rospy.Duration(1.0)) (trans, rot) = self.listener.lookupTransform("/base_link", "/world", now) except (tf.Exception, tf.LookupException, tf.ConnectivityException): rospy.logerr("Failed to find camera to map transform") #TODO Use tranform and rotation to calculate 2D position of light in image print "trans: ", trans print "rot: ", rot wp = np.array([ point_in_world.x, point_in_world.y, point_in_world.z ]) print "point_in_world: ", (wp + trans) x = 0 y = 0 return (x, y) def draw_light_box(self, light): """Draw boxes around traffic lights Args: light (TrafficLight): light to classify Returns: image with boxes around traffic lights """ (x,y) = self.project_to_image_plane(light.pose.pose.position) # use light location to draw box around traffic light in image print "x, y:", x, y def image_cb(self, msg): """Grab the first incoming camera image and saves it Args: msg (Image): image from car-mounted camera """ # unregister the subscriber to throttle the images coming in # if self.sub_raw_camera is not None: # self.sub_raw_camera.unregister() # self.sub_raw_camera = None if len(self.lights) > 0: height = int(msg.height) width = int(msg.width) # fixing convoluted camera encoding... if hasattr(msg, 'encoding'): if msg.encoding == '8UC3': msg.encoding = "rgb8" else: msg.encoding = 'rgb8' self.camera_image = self.bridge.imgmsg_to_cv2(msg, "rgb8") def traffic_cb(self, msg): self.lights = msg.lights # print "lights:", self.lights def steering_cb(self, msg): self.steering_cmd = msg.steering_wheel_angle_cmd if len(self.steering_history)>self.max_history_size: self.steering_history.pop(0) self.steering_history.append(self.steering_cmd*10.) def throttle_cb(self, msg): self.throttle_cmd = msg.pedal_cmd if len(self.throttle_history)>self.max_history_size: self.throttle_history.pop(0) self.throttle_history.append(self.throttle_cmd) def brake_cb(self, msg): self.brake_cmd = msg.pedal_cmd if len(self.brake_history)>self.max_history_size: self.brake_history.pop(0) self.brake_history.append(self.brake_cmd) def pose_cb(self, msg): self.i += 1 self.pose = msg.pose self.position = self.pose.position euler = tf.transformations.euler_from_quaternion([ self.pose.orientation.x, self.pose.orientation.y, self.pose.orientation.z, self.pose.orientation.w]) self.theta = euler[2] def velocity_cb(self, msg): self.current_linear_velocity = msg.twist.linear.x self.current_angular_velocity = msg.twist.angular.z if len(self.vel_history)>self.max_history_size: self.vel_history.pop(0) self.frame_history.pop(0) self.vel_history.append(self.current_linear_velocity) self.frame_history.append(self.i) def waypoints_cb(self, msg): # DONE: Implement if self.waypoints is None: self.waypoints = [] for waypoint in msg.waypoints: self.waypoints.append(waypoint) # No wrapping for this project! # # make sure we wrap! # self.waypoints.append(msg.waypoints[0]) # self.waypoints.append(msg.waypoints[1]) # create the polyline that defines the track x = [] y = [] for i in range(len(self.waypoints)): x.append(self.waypoints[i].pose.pose.position.x*75+510) y.append(self.img_rows-(self.waypoints[i].pose.pose.position.y*75+212)) self.XYPolyline = np.column_stack((x, y)).astype(np.int32) # just need to get it once self.sub_waypoints.unregister() self.sub_waypoints = None # initialize lights to waypoint map self.initializeLightToWaypointMap() def initializeLightToWaypointMap(self): # find the closest waypoint to the given (x,y) of the triffic light dl = lambda a, b: math.sqrt((a.x-b[0])**2 + (a.y-b[1])**2) for lidx in range(len(self.config['light_positions'])): dist = 100000. tlwp = 0 for widx in range(len(self.waypoints)): d1 = dl(self.waypoints[widx].pose.pose.position, self.config['light_positions'][lidx]) if dist > d1: tlwp = widx dist = d1 self.traffic_light_to_waypoint_map.append(tlwp) def fwaypoints_cb(self, msg): # DONE: Implement waypoints = [] fx = [] fy = [] fs = [] for i in range(len(msg.waypoints)): fx.append(float(msg.waypoints[i].pose.pose.position.x*75+510)) fy.append(self.img_rows-(float(msg.waypoints[i].pose.pose.position.y*75+212))) fs.append(int(msg.waypoints[i].twist.twist.linear.x/(self.restricted_speed*MPS)*255)) self.fwaypointsx = fx self.fwaypointsy = fy self.fwaypointss = fs self.fwaypointx = fx[0] self.fwaypointy = fy[0] def nextWaypoint(self, pose): """Identifies the next path waypoint to the given position https://en.wikipedia.org/wiki/Closest_pair_of_points_problem Args: pose (Pose): position to match a waypoint to Returns: int: index of the next waypoint in self.waypoints """ #DONE implement location = pose.position dist = 100000. dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2) nwp = 0 for i in range(len(self.waypoints)): d1 = dl(location, self.waypoints[i].pose.pose.position) if dist > d1: nwp = i dist = d1 x = self.waypoints[nwp].pose.pose.position.x y = self.waypoints[nwp].pose.pose.position.y heading = np.arctan2((y-location.y), (x-location.x)) angle = np.abs(self.theta-heading) if angle > np.pi/4.: nwp += 1 if nwp >= len(self.waypoints): nwp = 0 return nwp def getNextLightWaypoint(self): # find the closest waypoint from our pre-populated waypoint to light map tlwp = None self.nwp = self.nextWaypoint(self.pose) for ctl in range(len(self.traffic_light_to_waypoint_map)): # make sure its forward in our direction if self.nwp < self.traffic_light_to_waypoint_map[ctl] and tlwp is None: tlwp = self.traffic_light_to_waypoint_map[ctl] self.ctl = ctl return tlwp def distance(self, waypoints, wp1, wp2): dist = 0 dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2) for i in range(wp1, wp2+1): dist += dl(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.position) wp1 = i return dist def dist_to_next_traffic_light(self): dist = None tlwp = self.getNextLightWaypoint() if tlwp is not None: dist = self.distance(self.waypoints, self.nwp, tlwp) return dist def drawWaypoints(self, img, size=5, size2=10): color = (128, 128, 128) color2 = (128, 0, 0) cv2.polylines(img, [self.XYPolyline], 0, color, size) lastwp = len(self.waypoints)-1 x = int(self.waypoints[lastwp].pose.pose.position.x*75+510) y = int(self.img_rows-(self.waypoints[lastwp].pose.pose.position.y*75+212)) cv2.circle(img, (x, y), size2, color2, -1) def drawFinalWaypoints(self, img, size=1, size2=15): for i in range(len(self.fwaypointsx)): if self.fwaypointss[i] > 0: color = (0, 192, 0) else: color = (192, 0, 0) cv2.circle(img, (int(self.fwaypointsx[i]), int(self.fwaypointsy[i])), size, color, -1) if len(self.fwaypointsx) > 0: if self.fwaypointss[i] > 0: color = (0, 192, 0) else: color = (192, 0, 0) cv2.circle(img, (int(self.fwaypointsx[0]), int(self.fwaypointsy[0])), size2, color, -1) def drawTrafficLights(self, img, size=10): font = cv2.FONT_HERSHEY_COMPLEX for i in range(len(self.traffic_light_to_waypoint_map)): tlidx = self.traffic_light_to_waypoint_map[i] x = self.waypoints[tlidx].pose.pose.position.x y = self.waypoints[tlidx].pose.pose.position.y color = (255, 255, 0) cv2.circle(img, (int(x*75+510), int(self.img_rows-(y*75+212))), size, color, -1) cv2.putText(img, "%d"%(i), (int(x*75+510-10), int(self.img_rows-(y*75+212)+40)), font, 1, color, 2) def drawCurrentPos(self, img, size=20): color = (128, 128, 255) cv2.circle(img, (int(self.position.x*75+510), int(self.img_rows-(self.position.y*75+212))), size, color, -1) def loop(self): # only check once a updateRate time in milliseconds... font = cv2.FONT_HERSHEY_COMPLEX rate = rospy.Rate(self.updateRate) while not rospy.is_shutdown(): if self.theta is not None and self.waypoints is not None: tl_dist = self.dist_to_next_traffic_light() if tl_dist is None or tl_dist > 80.: self.camera_image = None if self.sub_raw_camera is not None: self.sub_raw_camera.unregister() self.sub_raw_camera = None elif self.sub_raw_camera is None: self.sub_raw_camera = rospy.Subscriber(self.camera_topic, Image, self.image_cb) if self.sub_waypoints is None: self.cv_image = np.zeros((self.img_rows, self.img_cols, self.img_ch), dtype=np.uint8) self.drawWaypoints(self.cv_image) self.drawFinalWaypoints(self.cv_image) self.drawTrafficLights(self.cv_image) self.drawCurrentPos(self.cv_image) color = (192, 192, 0) text0 = "Frame: %d" text1a = "Nearest Traffic Light (%d) is %fm ahead." text1b = "Nearest Traffic Light (%d) is behind us." text2 = "Curr. position is (%f, %f, %f). Yaw: %f" text3 = "Next Waypoint position is (%f, %f) with %d array len." cv2.putText(self.cv_image, text0%(self.i), (self.img_vis_txt_x, self.img_vis_txt_y), font, self.img_vis_font_size, color, 2) if tl_dist is not None: cv2.putText(self.cv_image, text1a%(self.ctl, tl_dist), (self.img_vis_txt_x, self.img_vis_txt_y*2), font, self.img_vis_font_size, color, 2) else: cv2.putText(self.cv_image, text1b%(self.ctl), (self.img_vis_txt_x, self.img_vis_txt_y*2), font, self.img_vis_font_size, color, 2) cv2.putText(self.cv_image, text2%(self.position.x, self.position.y, self.position.z, self.theta), (self.img_vis_txt_x, self.img_vis_txt_y*3), font, self.img_vis_font_size, color, 2) cv2.putText(self.cv_image, text3%(self.fwaypointx, self.fwaypointy, len(self.fwaypointsx)), (self.img_vis_txt_x, self.img_vis_txt_y*4), font, self.img_vis_font_size, color, 2) if self.camera_image is not None: self.cv_image[self.img_rows//2+100:self.img_rows//2+700, self.img_cols//2-200:self.img_cols//2+600] = cv2.resize(self.camera_image, (800,600), interpolation=cv2.INTER_AREA) self.update_pygame() # schedule next loop rate.sleep() def update_pygame(self): ### initialize pygame if self.screen is None: pygame.init() pygame.display.set_caption("Udacity SDC System Integration Project: Rosbag Diagnostics") self.screen = pygame.display.set_mode((self.img_cols//self.img_vis_ratio,self.img_rows//self.img_vis_ratio), pygame.DOUBLEBUF) ## give us a machine view of the world self.sim_img = pygame.image.fromstring(cv2.resize(self.cv_image,(self.img_cols//self.img_vis_ratio, self.img_rows//self.img_vis_ratio), interpolation=cv2.INTER_AREA).tobytes(), (self.img_cols//self.img_vis_ratio, self.img_rows//self.img_vis_ratio), 'RGB') self.screen.blit(self.sim_img, (0,0)) pygame.display.flip() if __name__ == "__main__": parser = argparse.ArgumentParser(description='Udacity SDC System Integration, Diagnostic Screen') parser.add_argument('--screensize', type=int, default="4", help='Screen sizes: 1:2500x2500px, 2:1250x1250px, 3:833x833px, 4:625x625px, 5:500x500px ') parser.add_argument('--maxhistory', type=int, default="200", help='Maximum History: default=200') parser.add_argument('--textspacing', type=int, default="100", help='Text Spacing: default=100') parser.add_argument('--fontsize', type=float, default="2", help='Font Size: default=2') parser.add_argument('--cameratopic', type=str, default='/image_color', help='camera ros topic') parser.add_argument('--trafficconfig', type=str, default='site_rosbag_traffic_light_config.yaml', help='traffic light yaml config') args = parser.parse_args() try: GenerateDiagnostics(int(args.screensize), int(args.maxhistory), int(args.textspacing), float(args.fontsize), args.cameratopic, args.trafficconfig) except rospy.ROSInterruptException: rospy.logerr('Could not start front camera viewer.')
import pytest # noqa: F401 from common import login import sys sys.path.insert(0, './app/') from app.models import db, Users # noqa E402 from app.tools import hash_str_with_pepper # noqa E402 def test_account_settings_password(client): login(client) # First test the default username (note the username hash is generated # from a lowercase version of the username) user = Users.query.filter_by( username_hash=hash_str_with_pepper('test_user_01')).first() assert user.check_password('12345678') res = client.post( '/account', data={ 'password_form-password': "asdfasdf", 'password_form-repeat_password': "asdfasdf", 'password_form-submit_password': 'Change', }, follow_redirects=True) html = str(res.data) # Confirm password fields are still blank assert '<input autocomplete="new-password" class="input_form__field_entry" id="password_form-password" name="password_form-password" required size="256" type="password" value="">' in html # noqa assert '<input autocomplete="new-password" class="input_form__field_entry" id="password_form-repeat_password" name="password_form-repeat_password" required size="256" type="password" value="">' in html # noqa # Confirm success message appeared assert '<span class="input_form__submit_ok_message_text">Password updated</span>' in html # noqa # Confirm password is updated assert user.check_password('12345678') is False assert user.check_password('asdfasdf') def test_account_settings_password_different(client): login(client) user = Users.query.filter_by( username_hash=hash_str_with_pepper('test_user_01')).first() assert user.check_password('12345678') res = client.post( '/account', data={ 'password_form-password': "asdfasdf", 'password_form-repeat_password': "asdfasdf1", 'password_form-submit_password': 'Change', }, follow_redirects=True) html = str(res.data) # Confirm password fields are still blank assert '<input autocomplete="new-password" class="input_form__field_entry" id="password_form-password" name="password_form-password" required size="256" type="password" value="">' in html # noqa assert '<input autocomplete="new-password" class="input_form__field_entry" id="password_form-repeat_password" name="password_form-repeat_password" required size="256" type="password" value="">' in html # noqa # Confirm error message appeared assert '<span class="input_form__field_error_message">Field must be equal to password.</span>' in html # noqa # Confirm password did not change assert user.check_password('12345678') def test_account_settings_password_too_short(client): login(client) user = Users.query.filter_by( username_hash=hash_str_with_pepper('test_user_01')).first() assert user.check_password('12345678') res = client.post( '/account', data={ 'password_form-password': "asdf", 'password_form-repeat_password': "asdf", 'password_form-submit_password': 'Change', }, follow_redirects=True) html = str(res.data) # Confirm password fields are still blank assert '<input autocomplete="new-password" class="input_form__field_entry" id="password_form-password" name="password_form-password" required size="256" type="password" value="">' in html # noqa assert '<input autocomplete="new-password" class="input_form__field_entry" id="password_form-repeat_password" name="password_form-repeat_password" required size="256" type="password" value="">' in html # noqa # Confirm error message appeared assert '<span class="input_form__field_error_message">Password must be at least 8 characters</span>' in html # noqa # Confirm password did not change assert user.check_password('12345678')
# -*- coding: utf-8 -*- __all__ = ["TrivialSolver", "BasicSolver", "HODLRSolver"] from .trivial import TrivialSolver from .basic import BasicSolver from .hodlr import HODLRSolver
import urllib.parse import requests import time import json import os from bs4 import BeautifulSoup STORE = 'momo' MOMO_MOBILE_URL = 'http://m.momoshop.com.tw/' MOMO_QUERY_URL = MOMO_MOBILE_URL + 'mosearch/%s.html' USER_AGENT_VALUE = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' def get_web_content(query): encoded_query = urllib.parse.quote(query) query_url = MOMO_QUERY_URL % encoded_query headers = {'User-Agent': USER_AGENT_VALUE} resp = requests.get(query_url, headers=headers) if not resp: return [] resp.encoding = 'UTF-8' return BeautifulSoup(resp.text, 'html.parser') def search_momo(query): dom = get_web_content(query) if dom: items = [] for element in dom.find(id='itemizedStyle').ul.find_all('li'): item_name = element.find('p', 'prdName').text item_price = element.find('b', 'price').text.replace(',', '') if not item_price: continue item_price = int(item_price) item_url = MOMO_MOBILE_URL + element.find('a')['href'] item_img_url = element.a.img['src'] item = { 'name': item_name, 'price': item_price, 'url': item_url, 'img_url': item_img_url } items.append(item) return items def save_search_result(data): with open(os.path.join('json', data['date'] + '-%s.json' % STORE), 'w', encoding='UTF-8') as file: json.dump(data, file, indent=2, ensure_ascii=False) def main(): query_str = 'iPhone 7 Plus 128G' items = search_momo(query_str) today = time.strftime('%m-%d') print('Search item \'%s\' from %s...' % (query_str, STORE)) print('Search %d records on %s' % (len(items), today)) for item in items: print(item) data = { 'date': today, 'store': STORE, 'items': items } save_search_result(data) if __name__ == '__main__': main()
import unittest import solution class TestQ(unittest.TestCase): def test_case_0(self): dist = solution.calculate_distances(5, [1, 1, 1, 1, 2, 3, 4], [2, 3, 4, 5, 3, 4, 5], [20, 50, 70, 90, 30, 40, 60]) self.assertEqual(solution.shortest_distance(dist, 1, 4), 70) self.assertEqual(solution.shortest_distance(dist, 5, 1), -1) self.assertEqual(solution.shortest_distance(dist, 2, 5), 130) self.assertEqual(solution.shortest_distance(dist, 3, 4), 40) self.assertEqual(solution.shortest_distance(dist, 1, 4), 70) self.assertEqual(solution.shortest_distance(dist, 1, 2), 20) self.assertEqual(solution.shortest_distance(dist, 3, 1), -1) self.assertEqual(solution.shortest_distance(dist, 1, 2), 20) def test_case_1(self): dist = solution.calculate_distances(4, [1, 1, 2, 3, 3], [2, 4, 4, 4, 2], [5, 24, 6, 4, 7]) self.assertEqual(solution.shortest_distance(dist, 1, 2), 5) self.assertEqual(solution.shortest_distance(dist, 3, 1), -1) self.assertEqual(solution.shortest_distance(dist, 1, 4), 11) if __name__ == '__main__': unittest.main()
from collections import defaultdict from redash.handlers.base import BaseResource, get_object_or_404 from redash.models import AccessPermission, Query, Dashboard, User, db from redash.permissions import require_admin_or_owner, ACCESS_TYPES from flask import request from flask_restful import abort from sqlalchemy.orm.exc import NoResultFound model_to_types = { 'queries': Query, 'dashboards': Dashboard } def get_model_from_type(type): model = model_to_types.get(type) if model is None: abort(404) return model class ObjectPermissionsListResource(BaseResource): def get(self, object_type, object_id): model = get_model_from_type(object_type) obj = get_object_or_404(model.get_by_id_and_org, object_id, self.current_org) # TODO: include grantees in search to avoid N+1 queries permissions = AccessPermission.find(obj) result = defaultdict(list) for perm in permissions: result[perm.access_type].append(perm.grantee.to_dict()) return result def post(self, object_type, object_id): model = get_model_from_type(object_type) obj = get_object_or_404(model.get_by_id_and_org, object_id, self.current_org) require_admin_or_owner(obj.user_id) req = request.get_json(True) access_type = req['access_type'] if access_type not in ACCESS_TYPES: abort(400, message='Unknown access type.') try: grantee = User.get_by_id_and_org(req['user_id'], self.current_org) except NoResultFound: abort(400, message='User not found.') permission = AccessPermission.grant(obj, access_type, grantee, self.current_user) self.record_event({ 'action': 'grant_permission', 'object_id': object_id, 'object_type': object_type, 'access_type': access_type, 'grantee': grantee.id }) return permission.to_dict() def delete(self, object_type, object_id): model = get_model_from_type(object_type) obj = get_object_or_404(model.get_by_id_and_org, object_id, self.current_org) require_admin_or_owner(obj.user_id) req = request.get_json(True) grantee_id = req['user_id'] access_type = req['access_type'] grantee = User.query.get(req['user_id']) if grantee is None: abort(400, message='User not found.') AccessPermission.revoke(obj, grantee, access_type) self.record_event({ 'action': 'revoke_permission', 'object_id': object_id, 'object_type': object_type, 'access_type': access_type, 'grantee_id': grantee_id }) db.session.commit() class CheckPermissionResource(BaseResource): def get(self, object_type, object_id, access_type): model = get_model_from_type(object_type) obj = get_object_or_404(model.get_by_id_and_org, object_id, self.current_org) has_access = AccessPermission.exists(obj, access_type, self.current_user) return {'response': has_access}
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import threading import os import sys import traceback try: from multiprocessing import current_process from multiprocessing import util as mputil except ImportError: current_process = mputil = None # noqa from . import current_app from . import signals from .local import Proxy from .utils import LOG_LEVELS, isatty from .utils.compat import LoggerAdapter, WatchedFileHandler from .utils.encoding import safe_str, str_t from .utils.patch import ensure_process_aware_logger from .utils.term import colored is_py3k = sys.version_info >= (3, 0) def mlevel(level): if level and not isinstance(level, int): return LOG_LEVELS[level.upper()] return level class ColorFormatter(logging.Formatter): #: Loglevel -> Color mapping. COLORS = colored().names colors = {"DEBUG": COLORS["blue"], "WARNING": COLORS["yellow"], "ERROR": COLORS["red"], "CRITICAL": COLORS["magenta"]} def __init__(self, msg, use_color=True): logging.Formatter.__init__(self, msg) self.use_color = use_color def formatException(self, ei): r = logging.Formatter.formatException(self, ei) if isinstance(r, str) and not is_py3k: return safe_str(r) return r def format(self, record): levelname = record.levelname color = self.colors.get(levelname) if self.use_color and color: try: record.msg = safe_str(str_t(color(record.msg))) except Exception, exc: record.msg = "<Unrepresentable %r: %r>" % ( type(record.msg), exc) record.exc_info = sys.exc_info() if not is_py3k: # Very ugly, but have to make sure processName is supported # by foreign logger instances. # (processName is always supported by Python 2.7) if "processName" not in record.__dict__: process_name = (current_process and current_process()._name or "") record.__dict__["processName"] = process_name return safe_str(logging.Formatter.format(self, record)) class Logging(object): #: The logging subsystem is only configured once per process. #: setup_logging_subsystem sets this flag, and subsequent calls #: will do nothing. _setup = False def __init__(self, app): self.app = app self.loglevel = mlevel(self.app.conf.CELERYD_LOG_LEVEL) self.format = self.app.conf.CELERYD_LOG_FORMAT self.task_format = self.app.conf.CELERYD_TASK_LOG_FORMAT self.colorize = self.app.conf.CELERYD_LOG_COLOR def supports_color(self, logfile=None): if self.app.IS_WINDOWS: # Windows does not support ANSI color codes. return False if self.colorize is None: # Only use color if there is no active log file # and stderr is an actual terminal. return logfile is None and isatty(sys.stderr) return self.colorize def colored(self, logfile=None): return colored(enabled=self.supports_color(logfile)) def get_task_logger(self, loglevel=None, name=None): logger = logging.getLogger(name or "celery.task.default") if loglevel is not None: logger.setLevel(mlevel(loglevel)) return logger def setup_logging_subsystem(self, loglevel=None, logfile=None, format=None, colorize=None, **kwargs): if Logging._setup: return loglevel = mlevel(loglevel or self.loglevel) format = format or self.format if colorize is None: colorize = self.supports_color(logfile) if mputil and hasattr(mputil, "_logger"): mputil._logger = None if not is_py3k: ensure_process_aware_logger() receivers = signals.setup_logging.send(sender=None, loglevel=loglevel, logfile=logfile, format=format, colorize=colorize) if not receivers: root = logging.getLogger() if self.app.conf.CELERYD_HIJACK_ROOT_LOGGER: root.handlers = [] mp = mputil.get_logger() if mputil else None for logger in filter(None, (root, mp)): self._setup_logger(logger, logfile, format, colorize, **kwargs) logger.setLevel(mlevel(loglevel)) signals.after_setup_logger.send(sender=None, logger=logger, loglevel=loglevel, logfile=logfile, format=format, colorize=colorize) # This is a hack for multiprocessing's fork+exec, so that # logging before Process.run works. os.environ.update(_MP_FORK_LOGLEVEL_=str(loglevel), _MP_FORK_LOGFILE_=logfile or "", _MP_FORK_LOGFORMAT_=format) Logging._setup = True return receivers def setup(self, loglevel=None, logfile=None, redirect_stdouts=False, redirect_level="WARNING"): handled = self.setup_logging_subsystem(loglevel=loglevel, logfile=logfile) if not handled: logger = self.get_default_logger() if redirect_stdouts: self.redirect_stdouts_to_logger(logger, loglevel=redirect_level) os.environ.update( CELERY_LOG_LEVEL=str(loglevel) if loglevel else "", CELERY_LOG_FILE=str(logfile) if logfile else "", CELERY_LOG_REDIRECT="1" if redirect_stdouts else "", CELERY_LOG_REDIRECT_LEVEL=str(redirect_level)) def _detect_handler(self, logfile=None): """Create log handler with either a filename, an open stream or :const:`None` (stderr).""" logfile = sys.__stderr__ if logfile is None else logfile if hasattr(logfile, "write"): return logging.StreamHandler(logfile) return WatchedFileHandler(logfile) def get_default_logger(self, loglevel=None, name="celery"): """Get default logger instance. :keyword loglevel: Initial log level. """ logger = logging.getLogger(name) if loglevel is not None: logger.setLevel(mlevel(loglevel)) return logger def setup_logger(self, loglevel=None, logfile=None, format=None, colorize=None, name="celery", root=True, app=None, **kwargs): """Setup the :mod:`multiprocessing` logger. If `logfile` is not specified, then `sys.stderr` is used. Returns logger object. """ loglevel = mlevel(loglevel or self.loglevel) format = format or self.format if colorize is None: colorize = self.supports_color(logfile) if not root or self.app.conf.CELERYD_HIJACK_ROOT_LOGGER: return self._setup_logger(self.get_default_logger(loglevel, name), logfile, format, colorize, **kwargs) self.setup_logging_subsystem(loglevel, logfile, format, colorize, **kwargs) return self.get_default_logger(name=name) def setup_task_logger(self, loglevel=None, logfile=None, format=None, colorize=None, task_name=None, task_id=None, propagate=False, app=None, **kwargs): """Setup the task logger. If `logfile` is not specified, then `sys.stderr` is used. Returns logger object. """ loglevel = mlevel(loglevel or self.loglevel) format = format or self.task_format if colorize is None: colorize = self.supports_color(logfile) logger = self._setup_logger(self.get_task_logger(loglevel, task_name), logfile, format, colorize, **kwargs) logger.propagate = int(propagate) # this is an int for some reason. # better to not question why. signals.after_setup_task_logger.send(sender=None, logger=logger, loglevel=loglevel, logfile=logfile, format=format, colorize=colorize) return LoggerAdapter(logger, {"task_id": task_id, "task_name": task_name}) def redirect_stdouts_to_logger(self, logger, loglevel=None, stdout=True, stderr=True): """Redirect :class:`sys.stdout` and :class:`sys.stderr` to a logging instance. :param logger: The :class:`logging.Logger` instance to redirect to. :param loglevel: The loglevel redirected messages will be logged as. """ proxy = LoggingProxy(logger, loglevel) if stdout: sys.stdout = proxy if stderr: sys.stderr = proxy return proxy def _is_configured(self, logger): return logger.handlers and not getattr( logger, "_rudimentary_setup", False) def _setup_logger(self, logger, logfile, format, colorize, formatter=ColorFormatter, **kwargs): if self._is_configured(logger): return logger handler = self._detect_handler(logfile) handler.setFormatter(formatter(format, use_color=colorize)) logger.addHandler(handler) return logger get_default_logger = Proxy(lambda: current_app.log.get_default_logger) setup_logger = Proxy(lambda: current_app.log.setup_logger) setup_task_logger = Proxy(lambda: current_app.log.setup_task_logger) get_task_logger = Proxy(lambda: current_app.log.get_task_logger) setup_logging_subsystem = Proxy( lambda: current_app.log.setup_logging_subsystem) redirect_stdouts_to_logger = Proxy( lambda: current_app.log.redirect_stdouts_to_logger) class LoggingProxy(object): """Forward file object to :class:`logging.Logger` instance. :param logger: The :class:`logging.Logger` instance to forward to. :param loglevel: Loglevel to use when writing messages. """ mode = "w" name = None closed = False loglevel = logging.ERROR _thread = threading.local() def __init__(self, logger, loglevel=None): self.logger = logger self.loglevel = mlevel(loglevel or self.logger.level or self.loglevel) self._safewrap_handlers() def _safewrap_handlers(self): """Make the logger handlers dump internal errors to `sys.__stderr__` instead of `sys.stderr` to circumvent infinite loops.""" def wrap_handler(handler): # pragma: no cover class WithSafeHandleError(logging.Handler): def handleError(self, record): exc_info = sys.exc_info() try: try: traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], None, sys.__stderr__) except IOError: pass # see python issue 5971 finally: del(exc_info) handler.handleError = WithSafeHandleError().handleError return map(wrap_handler, self.logger.handlers) def write(self, data): if getattr(self._thread, "recurse_protection", False): # Logger is logging back to this file, so stop recursing. return """Write message to logging object.""" data = data.strip() if data and not self.closed: self._thread.recurse_protection = True try: self.logger.log(self.loglevel, safe_str(data)) finally: self._thread.recurse_protection = False def writelines(self, sequence): """`writelines(sequence_of_strings) -> None`. Write the strings to the file. The sequence can be any iterable object producing strings. This is equivalent to calling :meth:`write` for each string. """ for part in sequence: self.write(part) def flush(self): """This object is not buffered so any :meth:`flush` requests are ignored.""" pass def close(self): """When the object is closed, no write requests are forwarded to the logging object anymore.""" self.closed = True def isatty(self): """Always returns :const:`False`. Just here for file support.""" return False def fileno(self): pass class SilenceRepeated(object): """Only log action every n iterations.""" def __init__(self, action, max_iterations=10): self.action = action self.max_iterations = max_iterations self._iterations = 0 def __call__(self, *args, **kwargs): if not self._iterations or self._iterations >= self.max_iterations: self.action(*args, **kwargs) self._iterations = 0 else: self._iterations += 1
from charrnn import CharacterRNN
import asyncio from typing import Union import discord async def add_choices_message(message: discord.Message, num: int, cancellable: bool = False) -> list: """React with choice emotes to message, return them as list""" # Only supports 10 max. stock "keycap digit" emojis assert 0 <= num <= 10 # Indexed from 1 (more user friendly I think) number_emotes = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "0️⃣"] # Copy first n elements choices = number_emotes[:num] if cancellable: choices.append("❌") # Add them to message for emote in choices: await message.add_reaction(emote) return choices async def wait_for_choice(bot: discord.Client, user: Union[discord.User, discord.Member], message: discord.Message, choices: list, cancellable: bool = False) -> int: """Wait for user to react with emote, then remove their reaction Example: No reaction (timeout) -> -1 Cancelled (❌) -> 0 Valid reaction -> 1 / 2 / 3 / ... (index of emoji in choices list + 1) """ number_emotes = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "0️⃣"] if cancellable: number_emotes.append("❌") choices.append("❌") # Checks if added reaction is the one we're waiting for def check(payload: discord.RawReactionActionEvent): if message.id == payload.message_id and payload.emoji.name in number_emotes and payload.user_id != bot.user.id: return True choice = None author_id = -1 while choice not in choices or author_id != user.id: # Watch for reaction try: payload: discord.RawReactionActionEvent = await bot.wait_for("raw_reaction_add", timeout=300, check=check) choice = payload.emoji.name author_id = payload.user_id # No reaction after timeout except asyncio.TimeoutError: return -1 # Remove user's reaction try: # Message.remove_reaction requires a Snowflake - according to documentation, it has 2 attributes, `id` and `created_at` # Well, Snowflake is missing the `id` attribute in discord.py 1.7.3, but remove_reaction still requires it snowflake = discord.abc.Snowflake snowflake.id = author_id await message.remove_reaction(payload.emoji.name, snowflake) except discord.errors.Forbidden: pass if choice == "❌": return 0 else: # Return emote as the number it represents (1️⃣ represents 1, 0️⃣️ represents 10) return choices.index(choice) + 1 async def remove_choices(message: discord.Message) -> None: """Remove all number emotes from message""" number_emotes = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "0️⃣", "❌"] for emote in number_emotes: try: await message.clear_reaction(emote) except (discord.HTTPException, discord.Forbidden, discord.NotFound): pass
""" Used to execute code before running tests, in this case we want to use test database. We don't want to mess up dev database. Put here any Pytest related code (it will be executed before `app/tests/...`) """ import os os.environ["ENVIRONMENT"] = "PYTEST"
from django.contrib import admin from guardian.admin import GuardedModelAdmin from models import SearchEngine, Project, Subject class ProjectAdmin(GuardedModelAdmin): model = Project class SubjectAdmin(GuardedModelAdmin): model = Subject class SearchEngineAdmin(admin.ModelAdmin): model = SearchEngine admin.site.register(Project, ProjectAdmin) admin.site.register(Subject, ProjectAdmin) admin.site.register(SearchEngine, SearchEngineAdmin)
# In OnData(self, data) bar = data["EURUSD"] # Anywhere in the code equity = self.Securities["EURUSD"]
# save python objects as pickle object in ROOT file from rootpyPickler import Pickler from ShipGeoConfig import AttrDict import ROOT,os,subprocess def execute(f,o): # record some basic information about version of software: tmp = os.environ['FAIRSHIP']+'/.git/refs/remotes/origin/master' if os.path.isfile(tmp): x = subprocess.check_output(['more',tmp]).replace('\n','') o.FairShip = AttrDict(origin=x) tmp = os.environ['FAIRSHIP']+'/.git/refs/heads/master' if os.path.isfile(tmp): x = subprocess.check_output(['more',tmp]).replace('\n','') o.FairShip = AttrDict(local=x) tmp = os.environ['SIMPATH']+'/../FairSoft/.git/refs/heads/master' if os.path.isfile(tmp): x = subprocess.check_output(['more',tmp]).replace('\n','') o.FairSoft = AttrDict(master=x) tmp = os.environ['SIMPATH']+'/../FairSoft/.git/refs/heads/dev' if os.path.isfile(tmp): x = subprocess.check_output(['more',tmp]).replace('\n','') o.FairSoft = AttrDict(dev=x) tmp = os.environ['FAIRROOTPATH']+'/../FairRoot/.git/refs/heads/dev' if os.path.isfile(tmp): x = subprocess.check_output(['more',tmp]).replace('\n','') o.FairRoot = AttrDict(dev=x) tmp = os.environ['FAIRROOTPATH']+'/../FairRoot/.git/refs/heads/master' if os.path.isfile(tmp): x = subprocess.check_output(['more',tmp]).replace('\n','') o.FairRoot = AttrDict(master=x) fg = ROOT.TFile.Open(f,'update') pkl=Pickler(fg) pkl.dump(o,'ShipGeo') fg.Close()
def main(): # input N = int(input()) Hs = list(map(int, input().split())) # compute flag = True for i in reversed(range(N-1)): if Hs[i]-Hs[i+1] == 1: Hs[i] -= 1 for i in range(N-1): if Hs[i] > Hs[i+1]: flag = False # output if flag: print('Yes') else: print('No') if __name__ == '__main__': main()
TCP_IP = '0.0.0.0' TCP_PORT = 5005 BUFFER_SIZE = 1024
from os import environ as env aws_access_key_id = env.get("aws_access_key_id") aws_secret_key = env.get("aws_secret_access_key") region_name = env.get("region_name")
"""We intend to make our reproduction as close as possible to the original paper. The configuration in the file is mostly from the description in the original paper and will be loaded when setting up.""" def dataset_based_configure(opts): if opts['dataset'] == 'cycles': ds_configure = cycles_configure else: raise ValueError('Unsupported dataset: {}'.format(opts['dataset'])) opts = {**opts, **ds_configure} return opts synthetic_dataset_configure = { 'node_hidden_size': 16, 'num_propagation_rounds': 2, 'optimizer': 'Adam', 'nepochs': 25, 'ds_size': 4000, 'num_generated_samples': 10000, } cycles_configure = { **synthetic_dataset_configure, **{ 'min_size': 10, 'max_size': 20, 'lr': 5e-4, } }
from flask import (Blueprint, flash, jsonify, redirect, render_template, request, url_for) from flask_login import current_user, login_required, login_user, logout_user from lisapi import db from lisapi.helpers import helpers from lisapi.models.forms import EditPin, NewPin from lisapi.models.tables import Pin, User from . import pin @pin.route('/create', methods=['GET', 'POST']) def create_pin(): form_new_pin = NewPin() if form_new_pin.validate_on_submit(): pin_name = form_new_pin.name.data pin_number = int(form_new_pin.pin.data) pin_color = form_new_pin.color.data pin_icon = form_new_pin.icon.data check_pin = helpers.check_pin(pin_number) if not check_pin: flash('Pin {} dont exists!'.format(pin_number), 'error') return render_template('pin/new.html', form=form_new_pin) else: pin = Pin(name=pin_name, pin=pin_number, color=pin_color, icon=pin_icon, state=False, user_id=current_user.id) db.session.add(pin) db.session.commit() flash('Pin created!', 'success') return redirect(url_for('pin.list_pins')) if len(form_new_pin.errors) > 0: flash('Check form data!', 'error') context = { 'form': form_new_pin, 'active_menu': 'New Pin' } return render_template('pin/new.html', **context) @pin.route('/list', methods=['GET']) @login_required def list_pins(): list_pins = Pin.query.all() context = { 'pins': list_pins, 'active_menu': 'List Pins' } return render_template('pin/list.html', **context) @pin.route('/edit/<int:pin_id>', methods=['GET', 'POST']) @login_required def edit_pin(pin_id): pin = Pin.query.get(pin_id) form_editpin = EditPin(obj=pin) context = { 'form': form_editpin, 'pin': pin, 'active_menu': 'Edit Pin' } if request.method == 'POST': if form_editpin.validate_on_submit(): pin_number = int(form_editpin.pin.data) check_pin = helpers.check_pin(pin_number) if not check_pin: flash('Pin {} dont exists!'.format(pin_number), 'error') return render_template('pin/edit.html', **context) pin = Pin.query.get(pin_id) pin.name = form_editpin.name.data pin.pin = form_editpin.pin.data pin.color = form_editpin.color.data pin.icon = form_editpin.icon.data db.session.commit() flash('Pin edited!', 'success') return redirect(url_for('pin.list_pins')) if len(form_editpin.errors) > 0: flash('Check form data!', 'error') print(form_editpin.errors) return render_template('pin/edit.html', **context) @pin.route('/delete/<int:pin_id>', methods=['GET']) @login_required def delete_pin(pin_id): pin = Pin.query.get(pin_id) db.session.delete(pin) db.session.commit() flash('Pin removed!', 'warning') return redirect(url_for('pin.list_pins')) @pin.route('/control', methods=['GET']) @login_required def control_pins(): list_pins = Pin.query.all() context = { 'pins': list_pins, 'active_menu': 'Control Pins' } return render_template('pin/control.html', **context)
import ctypes class Region(ctypes.Structure): ''' @class Region @brief Class containing lattice bounds and ticks. @details Replicates C Region class. ''' _fields_ = [('imin', ctypes.c_uint32), ('jmin', ctypes.c_uint32), ('kmin', ctypes.c_uint32), ('ni', ctypes.c_uint32), ('nj', ctypes.c_uint32), ('nk', ctypes.c_uint32), ('voxels', ctypes.c_uint64), ('X', ctypes.POINTER(ctypes.c_float)), ('Y', ctypes.POINTER(ctypes.c_float)), ('Z', ctypes.POINTER(ctypes.c_float)), ('L', ctypes.POINTER(ctypes.c_uint16))] def __init__(self, (xmin, ymin, zmin)=(0.,0.,0.), (xmax, ymax, zmax)=(0.,0.,0.), scale=100., dummy=False, depth=None): """ @brief Creates an array. """ dx = float(xmax - xmin) dy = float(ymax - ymin) dz = float(zmax - zmin) if depth is not None: scale = 3*(2**6)* 2**(depth/3.) / (dx+dy+dz) ni = max(int(round(dx*scale)), 1) nj = max(int(round(dy*scale)), 1) nk = max(int(round(dz*scale)), 1) # Dummy assignments so that Doxygen recognizes these instance variables self.ni = self.nj = self.nk = 0 self.imin = self.jmin = self.kmin = 0 self.voxels = 0 self.X = self.Y = self.Z = self.L = None ## @var ni # Number of ticks along x axis ## @var nj #Number of points along y axis ## @var nk # Number of points along z axis ## @var imin # Minimum i coordinate in global lattice space ## @var jmin # Minimum j coordinate in global lattice space ## @var kmin # Minimum k coordinate in global lattice space ## @var voxels # Voxel count in this section of the lattice ## @var X # Array of ni+1 X coordinates as floating-point values ## @var Y # Array of nj+1 Y coordinates as floating-point values ## @var Z # Array of nk+1 Z coordinates as floating-point values ## @var L # Array of nk+1 luminosity values as 16-bit integers ## @var free_arrays # Boolean indicating whether this region dynamically allocated # the X, Y, Z, and L arrays. # # Determines whether these arrays are # freed when the structure is deleted. ctypes.Structure.__init__(self, 0, 0, 0, ni, nj, nk, ni*nj*nk, None, None, None, None) if dummy is False: libfab.build_arrays(ctypes.byref(self), xmin, ymin, zmin, xmax, ymax, zmax) self.free_arrays = True else: self.free_arrays = False def __del__(self): """ @brief Destructor for Region @details Frees allocated arrays if free_arrays is True """ if hasattr(self, 'free_arrays') and self.free_arrays and libfab is not None: libfab.free_arrays(self) def __repr__(self): return ('[(%g, %g), (%g, %g), (%g, %g)]' % (self.imin, self.imin + self.ni, self.jmin, self.jmin + self.nj, self.kmin, self.kmin + self.nk)) def split(self, count=2): """ @brief Repeatedly splits the region along its longest axis @param count Number of subregions to generate @returns List of regions (could be fewer than requested if the region is indivisible) """ L = (Region*count)() count = libfab.split(self, L, count) return L[:count] def split_xy(self, count=2): """ @brief Repeatedly splits the region on the X and Y axes @param count Number of subregions to generate @returns List of regions (could be fewer than requested if the region is indivisible) """ L = (Region*count)() count = libfab.split_xy(self, L, count) return L[:count] def octsect(self, all=False, overlap=False): """ @brief Splits the region into eight subregions @param all If true, returns an 8-item array with None in the place of missing subregions. Otherwise, the output array is culled to only include valid subregions. @returns An array of containing regions (and Nones if all is True and the region was indivisible along some axis) """ L = (Region*8)() if overlap: bits = libfab.octsect_overlap(self, L) else: bits = libfab.octsect(self, L) if all: return [L[i] if (bits & (1 << i)) else None for i in range(8)] else: return [L[i] for i in range(8) if (bits & (1 << i))] from koko.c.libfab import libfab from koko.c.vec3f import Vec3f
import torch import numpy as np class SequenceAccuracy(object): """Computes accuracy between two sequences. Inputs: pred (N, L, C) tgt (N, L) ignore_index (int): index of token to mask out """ def __init__(self, ignore_index=-100): self.ignore_index = ignore_index def __call__(self, pred, tgt): n = tgt.shape[0] pred = pred.argmax(dim=-1).view(n,-1) tgt = tgt.view(n, -1) mask = tgt != self.ignore_index tgt = tgt[mask] pred = pred[mask] return (pred == tgt).float().mean() class MaskedAccuracy(object): """Masked accuracy. Inputs: pred (N, L, C) tgt (N, L) mask (N, L) """ def __call__(self, pred, tgt, mask): _, p = torch.max(pred, -1) masked_tgt = torch.masked_select(tgt, mask.bool()) p = torch.masked_select(p, mask.bool()) return torch.mean((p == masked_tgt).float()) class MaskedTopkAccuracy(object): """Masked top k accuracy. Inputs: pred (N, L, C) tgt (N, L) mask (N, L) k (int) """ def __call__(self, pred, tgt, mask, k): _, p = torch.topk(pred, k, -1) masked_tgt = torch.masked_select(tgt, mask.bool()) p = torch.masked_select(p, mask.bool().unsqueeze(-1)).view(-1, k) masked_tgt = masked_tgt.repeat(k).view(k, -1).t() return (p == masked_tgt).float().sum(dim=1).mean() class UngappedAccuracy(MaskedAccuracy): def __init__(self, gap_index): self.gap_index = gap_index def __call__(self, pred, tgt): mask = tgt != self.gap_index return super().__call__(pred, tgt, mask) class LPrecision(object): """ Calculates top L // k precision where L is length * params acquired from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4894841/#FN1 """ def __init__(self, k=5, contact_range='medium-long'): """ Args: k: L // k number of contacts to check contact_range: short, medium or long contacts """ if contact_range == 'short': self.res_range = [6, 12] elif contact_range == 'medium': self.res_range = [12, 24] elif contact_range == 'long': self.res_range = [24, np.inf] elif contact_range == 'medium-long': self.res_range = [12, np.inf] else: raise ValueError("contact_range must be one of 'short', 'medium', 'long', or 'medium-long'.") # contact if d < 8 angstroms, or d > exp(-8 ** 2 / 8 ** 2) self.contact_threshold = np.exp(-1) self.k = k def __call__(self, prediction, tgt, mask, ells): """ Args: prediction: torch.tensor (N, L, L) tgt: torch.tensor (N, L, L) mask: torch.tensor (N, L, L) ells: torch.tensor (N,) lengths of protein sequences """ n, el, _ = tgt.shape # update the mask # get distance based on primary structure pri_dist = torch.abs(torch.arange(el)[None, :].repeat(el, 1) - torch.arange(el).view(-1, 1)).float() # repeat for each sample in batch size pri_dist = pri_dist.view(1, el, el).repeat(n, 1, 1) dist_mask = (pri_dist > self.res_range[0]) & (pri_dist < self.res_range[1]) mask = dist_mask & mask # pull the top_k most likely contacts from each prediction prediction = prediction.masked_fill(~mask, -1) tgt = tgt.masked_fill(~mask, -1) # Get just the upper triangular idx = torch.triu_indices(el, el, offset=1) prediction = torch.stack([p[idx[0], idx[1]] for p in prediction]) # N x n_triu tgt = torch.stack([t[idx[0], idx[1]] for t in tgt]) # N x n_triu tgt = tgt > self.contact_threshold idx = torch.argsort(prediction, dim=1, descending=True) # N x tri_u # see how many are tp or fp # how many contacts to look at top_k = ells // self.k n_valid = mask.sum(dim=-1).sum(dim=1) n_valid = np.minimum(n_valid, top_k).long() # (N, ) n_predicted = n_valid.sum().item() if n_predicted == 0: return 0, 0 # n_predicted = (prediction > self.contact_threshold).sum(dim=1) # n_valid = np.minimum(n_valid, n_predicted).long() n_contacts = 0 for ids, t, n in zip(idx, tgt, n_valid): n_contacts += t[ids[:n]].sum().item() precision = n_contacts / n_predicted return precision, n_predicted
from common_fixtures import * # NOQA from test_docker import docker_client, TEST_IMAGE_UUID, if_docker import requests import jwt # work around flake8 issue docker_client @if_docker def test_stats_host(docker_client, context): host = docker_client.list_host()[0] sim_host = context.host assert 'stats' in host.links assert 'hostStats' in host.links assert 'containerStats' in host.links assert 'stats' not in sim_host.links stats_access = host.stats() assert stats_access.token.index('.') > 0 assert '/v1/stats' in stats_access.url @if_docker def test_hoststats_host(docker_client, context): host = docker_client.list_host()[0] stats_access = host.hostStats() assert stats_access.token.index('.') > 0 assert '/v1/hoststats' in stats_access.url try: payload = jwt.decode(stats_access.token, verify=False) assert 'hostUuid' in payload assert 'resourceId' in payload except jwt.InvalidTokenError: assert False @if_docker def test_hoststats_project(admin_user_client, context): project = admin_user_client.list_project()[0] assert 'hostStats' in project.links stats_access = project.hostStats() assert stats_access.token.index('.') > 0 assert '/v1/hoststats' in stats_access.url try: payload = jwt.decode(stats_access.token, verify=False) assert 'project' in payload except jwt.InvalidTokenError: assert False def _get_host_stats_ip(host): found_ip = None for ip in host.ipAddresses(): if found_ip is None: found_ip = ip elif found_ip.role == 'primary': found_ip = ip break elif ip.createdTS < found_ip.createdTS: found_ip = ip assert found_ip is not None assert found_ip.address is not None return found_ip @if_docker def test_stats_container(docker_client): uuid = TEST_IMAGE_UUID container = docker_client.create_container(imageUuid=uuid, networkMode='bridge') container = docker_client.wait_success(container) assert container.state == 'running' assert len(container.hosts()) == 1 stats_access = container.stats() assert stats_access.token.index('.') > 0 assert '/v1/stats/%s' % container.externalId in stats_access.url def test_host_api_key_download(client): url = client._url.split('v2-beta', 1)[0] + 'v1/scripts/api.crt' assert url is not None cert = requests.get(url).text assert cert is not None assert cert.startswith('-----BEGIN PUBLIC KEY-')
from PLC.Faults import * from PLC.Method import Method from PLC.Parameter import Parameter, Mixed from PLC.ConfFiles import ConfFile, ConfFiles from PLC.Nodes import Node, Nodes from PLC.Auth import Auth class AddConfFileToNode(Method): """ Adds a configuration file to the specified node. If the node is already linked to the configuration file, no errors are returned. Returns 1 if successful, faults otherwise. """ roles = ['admin'] accepts = [ Auth(), ConfFile.fields['conf_file_id'], Mixed(Node.fields['node_id'], Node.fields['hostname']) ] returns = Parameter(int, '1 if successful') def call(self, auth, conf_file_id, node_id_or_hostname): # Get configuration file conf_files = ConfFiles(self.api, [conf_file_id]) if not conf_files: raise PLCInvalidArgument("No such configuration file") conf_file = conf_files[0] # Get node nodes = Nodes(self.api, [node_id_or_hostname]) if not nodes: raise PLCInvalidArgument("No such node") node = nodes[0] if node['peer_id'] is not None: raise PLCInvalidArgument("Not a local node") # Link configuration file to node if node['node_id'] not in conf_file['node_ids']: conf_file.add_node(node) # Log affected objects self.event_objects = {'ConfFile': [conf_file_id], 'Node': [node['node_id']] } return 1
from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.embeddings import Embedding from keras.layers.normalization import BatchNormalization from keras.layers import Input, Convolution1D, GlobalMaxPooling1D, GlobalAveragePooling1D, \ Lambda, TimeDistributed, SpatialDropout1D, Reshape, RepeatVector from keras.layers.merge import Dot, Concatenate, Multiply, Add from keras.models import Model from keras import backend as K from keras.initializers import RandomUniform DSSM_NUM_NEGS = 5 ATTENTION_DEEP_LEVEL = 5 def keras_diagonal(x): seq_len = 10 if 'seq_len' not in K.params else K.params['seq_len'] if seq_len != 10: print("dim of diagonal matrix in keras_diagonal: %d" % seq_len) return K.sum(K.eye(seq_len) * x, axis=1) def elementwise_prod(x, y): (_, vec_size,) = K.int_shape(x) attention_level = K.params['attention_level'] return x*y[:, attention_level, 0:vec_size] def attention_weighting_prod(attention, weights): attention_level = K.params['attention_level'] return attention * weights[:, attention_level, :, :] def repeat_vector(x, rep, axis): return K.repeat(x, rep, axis) def max_pooling(x): return K.max(x, axis=1) def mean_pooling(x): return K.mean(x, axis=1) def max_pooling_with_mask(x, query_mask): # x is batch_size * |doc| * |query| # query_mask is batch_size * |query| (with masks as 0) return K.max(x, axis=1) * query_mask def mean_pooling_with_mask(x, doc_mask, query_mask): # x is batch_size * |doc| * |query| # doc_mask is batch_size * |doc| (with masks as 0) # query_mask is batch_size * |query| (with masks as 0) ZERO_SHIFT = 0.1 doc_mask_sum = (K.sum(doc_mask, axis=-1, keepdims=True) + ZERO_SHIFT) return query_mask * K.batch_dot(x, doc_mask, axes=[1, 1]) / doc_mask_sum def add_embed_layer(vocab_emb, vocab_size, embed_size, train_embed, dropout_rate): emb_layer = Sequential() if vocab_emb is not None: print("Embedding with initialized weights") print(vocab_size, embed_size) emb_layer.add(Embedding(input_dim=vocab_size, output_dim=embed_size, weights=[vocab_emb], trainable=train_embed, mask_zero=False)) else: print("Embedding with random weights") emb_layer.add(Embedding(input_dim=vocab_size, output_dim=embed_size, trainable=True, mask_zero=False, embeddings_initializer=RandomUniform(-0.05, 0.05))) emb_layer.add(SpatialDropout1D(dropout_rate)) return emb_layer def add_conv_layer(input_list, layer_name, nb_filters, kernel_size, padding, dropout_rate=0.1, activation='relu', strides=1, attention_level=0, conv_option="normal", prev_conv_tensors=None): conv_layer = Convolution1D(filters=nb_filters, kernel_size=kernel_size, padding=padding, activation=activation, strides=strides, name=layer_name) max_pooling_layer = GlobalMaxPooling1D() dropout_layer = Dropout(dropout_rate) output_list, conv_output_list = [], [] for i in range(len(input_list)): input = input_list[i] conv_tensor = conv_layer(input) if conv_option == "ResNet": conv_tensor = Add()([conv_tensor, prev_conv_tensors[i][-1]]) dropout_tensor = dropout_layer(conv_tensor) #conv_pooling_tensor = max_pooling_layer(conv_tensor) output_list.append(dropout_tensor) #conv_output_list.append(conv_pooling_tensor) conv_output_list.append(conv_tensor) return output_list, conv_output_list def add_attention_layer(query_embedding, doc_embedding, layer_name, query_mask=None, doc_mask=None, mask=False): dot_prod = Dot(axes=-1, name=layer_name)([doc_embedding, query_embedding]) norm_sim = Activation('softmax')(dot_prod) if mask: max_sim = Lambda(lambda x: max_pooling_with_mask(x[0], x[1]), output_shape=lambda inp_shp: ( inp_shp[0][0], inp_shp[0][2],))([norm_sim, query_mask]) mean_sim = Lambda(lambda x: mean_pooling_with_mask(x[0], x[1], x[2]), output_shape=lambda inp_shp: ( inp_shp[0][0], inp_shp[0][2],))([norm_sim, doc_mask, query_mask]) else: max_sim = Lambda(max_pooling, output_shape=lambda inp_shp: (inp_shp[0], inp_shp[2], ))(norm_sim) mean_sim = Lambda(mean_pooling, output_shape=lambda inp_shp: (inp_shp[0], inp_shp[2],))(norm_sim) return norm_sim, max_sim, mean_sim def add_attention_layer_with_query_weighting(query_embedding, doc_embedding, layer_name, attention_level, query_weight, query_mask=None, doc_mask=None, mask=False): """ Dot -> softmax -> pooling -> (mask) -> weighting """ dot_prod = Dot(axes=-1, name=layer_name)([doc_embedding, query_embedding]) norm_sim = Activation('softmax')(dot_prod) if mask: max_sim = Lambda(lambda x: max_pooling_with_mask(x[0], x[1]), output_shape=lambda inp_shp: ( inp_shp[0][0], inp_shp[0][2],))([norm_sim, query_mask]) mean_sim = Lambda(lambda x: mean_pooling_with_mask(x[0], x[1], x[2]), output_shape=lambda inp_shp: ( inp_shp[0][0], inp_shp[0][2],))([norm_sim, doc_mask, query_mask]) else: max_sim = Lambda(max_pooling, output_shape=lambda inp_shp: (inp_shp[0], inp_shp[2], ))(norm_sim) mean_sim = Lambda(mean_pooling, output_shape=lambda inp_shp: (inp_shp[0], inp_shp[2],))(norm_sim) if attention_level <= 1: setattr(K, 'params', {'attention_level': attention_level}) max_sim = Lambda(lambda x: elementwise_prod(x[0], x[1]), output_shape=lambda inp_shp: (inp_shp[0][0], inp_shp[0][1],))([max_sim, query_weight]) mean_sim = Lambda(lambda x: elementwise_prod(x[0], x[1]), output_shape=lambda inp_shp: (inp_shp[0][0], inp_shp[0][1]))([mean_sim, query_weight]) return norm_sim, max_sim, mean_sim # doc weighting is not tested yet, please use query weighting instead. def add_attention_layer_with_doc_weighting(query_embedding, doc_embedding, layer_name, attention_level, query_weight, doc_weight, max_query_len, max_doc_len, query_mask=None, doc_mask=None, mask=False): dot_prod = Dot(axes=-1, name=layer_name)([doc_embedding, query_embedding]) norm_sim = Activation('softmax')(dot_prod) reshaped_query_weight = Reshape((ATTENTION_DEEP_LEVEL, max_query_len, 1), input_shape=(ATTENTION_DEEP_LEVEL, max_query_len,))(query_weight) repeated_query_weight = Lambda(lambda x: repeat_vector(x[0], x[1], x[2]), output_shape=lambda inp_shp:( inp_shp[0][0], inp_shp[0][1], max_query_len, max_doc_len,))([reshaped_query_weight, max_doc_len, -1]) reshaped_doc_weight = Reshape((ATTENTION_DEEP_LEVEL, 1, max_doc_len), input_shape=(ATTENTION_DEEP_LEVEL, max_doc_len,))(doc_weight) repeated_doc_weight = Lambda(lambda x: repeat_vector(x[0], x[1], x[2]), output_shape=lambda inp_shp: ( inp_shp[0][0], inp_shp[0][1], max_query_len, max_doc_len,))([reshaped_doc_weight, max_query_len, -2]) weight_product = Multiply()([repeated_query_weight, repeated_doc_weight]) transformed_weight_product = Dense(max_doc_len, activation='relu')(weight_product) setattr(K, 'params', {'attention_level': attention_level}) norm_sim = Lambda(lambda x: attention_weighting_prod(x[0], x[1]), output_shape=lambda inp_shp:( inp_shp[0][0], inp_shp[0][1], inp_shp[0][2]))([norm_sim, transformed_weight_product]) if mask: max_sim = Lambda(lambda x: max_pooling_with_mask(x[0], x[1]), output_shape=lambda inp_shp: ( inp_shp[0][0], inp_shp[0][2],))([norm_sim, query_mask]) mean_sim = Lambda(lambda x: mean_pooling_with_mask(x[0], x[1], x[2]), output_shape=lambda inp_shp: ( inp_shp[0][0], inp_shp[0][2],))([norm_sim, doc_mask, query_mask]) else: max_sim = Lambda(max_pooling, output_shape=lambda inp_shp: (inp_shp[0], inp_shp[2], ))(norm_sim) mean_sim = Lambda(mean_pooling, output_shape=lambda inp_shp: (inp_shp[0], inp_shp[2],))(norm_sim) return norm_sim, max_sim, mean_sim ########################## Our model implementation ######################### def create_attention_model(max_query_len, max_doc_len, max_url_len, vocab_size, embedding_matrix, nb_filters, embed_size=300, dropout_rate=0.1, trainable=True, weighting=False, mask=False, conv_option="normal", model_option="complete"): print('create attention model...') model = Sequential() query_word_input = Input(shape=(max_query_len['word'], ), name="query_word_input") doc_word_input = Input(shape=(max_doc_len['word'],), name="doc_word_input") query_char_input = Input(shape=(max_query_len['3gram'],), name="query_3gram_input") doc_char_input = Input(shape=(max_doc_len['3gram'],), name="doc_3gram_input") url_char_input = Input(shape=(max_url_len['url'],), name="url_3gram_input") input_list = [query_word_input, doc_word_input, query_char_input, doc_char_input, url_char_input] # Define Mask query_word_mask, query_char_mask, doc_word_mask, doc_char_mask, url_char_mask = None, None, None, None, None if mask: query_word_mask = Input(shape=(max_query_len['word'], ), name="query_word_mask") doc_word_mask = Input(shape=(max_doc_len['word'], ), name="doc_word_mask") query_char_mask = Input(shape=(max_query_len['3gram'],), name="query_3gram_mask") doc_char_mask = Input(shape=(max_doc_len['3gram'],), name="doc_3gram_mask") url_char_mask = Input(shape=(max_url_len['url'],), name="url_3gram_mask") input_list.extend([query_word_mask, doc_word_mask, query_char_mask, url_char_mask]) query_word_weight, query_char_weight, doc_word_weight, doc_char_weight, url_char_weight = None, None, None, None, None if weighting == 'query': query_word_weight = Input(shape=(ATTENTION_DEEP_LEVEL, max_query_len['word'], ), name="query_word_weight") query_char_weight = Input(shape=(ATTENTION_DEEP_LEVEL, max_query_len['3gram'],), name="query_3gram_weight") #external_feat = Input(shape=(2, ), name='overlap_feat') input_list.extend([query_word_weight, query_char_weight]) #input_list.append(external_feat) elif weighting == 'doc': query_word_weight = Input(shape=(ATTENTION_DEEP_LEVEL, max_query_len['word'],), name="query_word_weight") query_char_weight = Input(shape=(ATTENTION_DEEP_LEVEL, max_query_len['3gram'],), name="query_3gram_weight") doc_word_weight = Input(shape=(ATTENTION_DEEP_LEVEL, max_doc_len['word'],), name="doc_word_weight") doc_char_weight = Input(shape=(ATTENTION_DEEP_LEVEL, max_doc_len['3gram'],), name="doc_3gram_weight") url_char_weight = Input(shape=(ATTENTION_DEEP_LEVEL, max_url_len['url'],), name="url_3gram_weight") input_list.extend([query_word_weight, query_char_weight, doc_word_weight, doc_char_weight, url_char_weight]) char_weight_candidates = [doc_char_weight, url_char_weight] # Create query-doc word-to-word attention layer query_word_embedding_layer = add_embed_layer(embedding_matrix, vocab_size['word'], embed_size, trainable, dropout_rate) query_embedding = query_word_embedding_layer(query_word_input) doc_embedding = query_word_embedding_layer(doc_word_input) norm_sim_list, max_sim_list, mean_sim_list = [], [], [] conv_embedding_list = [[query_embedding], [doc_embedding]] for i in range(ATTENTION_DEEP_LEVEL): if i > 0: output_list, conv_output_list = add_conv_layer([query_embedding, doc_embedding], "word-conv%d" % i, nb_filters, 2, "same", dropout_rate, strides=1, attention_level=i, conv_option=conv_option, prev_conv_tensors=conv_embedding_list) query_embedding, doc_embedding = output_list[0], output_list[1] conv_embedding_list[0].append(conv_output_list[0]) conv_embedding_list[1].append(conv_output_list[1]) if weighting == 'query': norm_sim, max_sim, mean_sim = add_attention_layer_with_query_weighting( query_embedding, doc_embedding, "word-attention%d" % i, i, query_word_weight, query_word_mask, doc_word_mask, mask) elif weighting == 'doc': norm_sim, max_sim, mean_sim = add_attention_layer_with_doc_weighting( query_embedding, doc_embedding, "word-attention%d" % i, i, query_word_weight, doc_word_weight, max_query_len['word'], max_doc_len['word'], query_word_mask, doc_word_mask, mask) norm_sim_list.append(norm_sim) max_sim_list.append(max_sim) mean_sim_list.append(mean_sim) # Create query-doc char-to-char attention layer char_embedding_layer = add_embed_layer(None, vocab_size['char'], embed_size, True, dropout_rate) query_char_embedding_layer = url_char_embedding_layer = doc_char_embedding_layer = char_embedding_layer doc_char_embedding = doc_char_embedding_layer(doc_char_input) url_char_embedding = url_char_embedding_layer(url_char_input) char_embedding_candidates = [doc_char_embedding, url_char_embedding] char_mask_candidates = [doc_char_mask, url_char_mask] max_doc_len_candidates = [max_doc_len["3gram"], max_url_len["url"]] j = 0 for char_embedding, char_mask, char_weight, max_doc_len_tmp in zip(char_embedding_candidates, char_mask_candidates, char_weight_candidates, max_doc_len_candidates): query_embedding = query_char_embedding_layer(query_char_input) conv_embedding_list = [[query_embedding], [char_embedding]] setattr(K, 'params', {'max_doc_len': max_doc_len_tmp, 'max_query_len': max_query_len['3gram']}) for i in range(ATTENTION_DEEP_LEVEL): if i > 0: output_list, conv_output_list = add_conv_layer([query_embedding, char_embedding], "3gram-conv%d" % j, nb_filters, 4, "same", dropout_rate, strides=1, attention_level=i, conv_option=conv_option, prev_conv_tensors=conv_embedding_list) query_embedding, char_embedding = output_list[0], output_list[1] conv_embedding_list[0].append(conv_output_list[0]) conv_embedding_list[1].append(conv_output_list[1]) if weighting == 'query': norm_sim2, max_sim2, mean_sim2 = add_attention_layer_with_query_weighting( query_embedding, char_embedding, "url-attention%d" % j, i, query_char_weight, query_char_mask, char_mask, mask) elif weighting == 'doc': norm_sim2, max_sim2, mean_sim2 = add_attention_layer_with_doc_weighting( query_embedding, char_embedding, "url-attention%d" % j, i, query_char_weight, char_weight, max_query_len['3gram'], max_url_len['url'], query_char_mask, char_mask, mask) else: norm_sim2, max_sim2, mean_sim2 = add_attention_layer(query_embedding, char_embedding, "url-attention%d" % j, query_char_mask, char_mask, mask) norm_sim_list.append(norm_sim2) max_sim_list.append(max_sim2) mean_sim_list.append(mean_sim2) j += 1 max_sim_list.extend(mean_sim_list) feature_vector = Concatenate(axis=-1, name="feature_vector")(max_sim_list) #if weighting: # feature_vector = Concatenate(axis=-1, name="external_feature_vector")([feature_vector, external_feat]) feature_vector1 = Dense(150, activation='relu', name="feature_vector1")(feature_vector) feature_vector2 = Dense(50, activation='relu', name="feature_vector2")(feature_vector1) prediction = Dense(1, activation='sigmoid', name="prediction")(feature_vector2) return Model(input_list, [prediction])
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class LianjiaspiderItem(scrapy.Item): # define the fields for your item here like: # 定义爬取的信息 # 爬取房屋的所在城市 city = scrapy.Field() # 街道的名字 street = scrapy.Field() # 街道的url地址 street_page_url = scrapy.Field() # 房屋的url地址 detail_url = scrapy.Field() # 房屋的详细信息 house_info_dict = scrapy.Field()
from datetime import datetime, timedelta from itertools import accumulate from typing import Iterator, NamedTuple, Tuple from fastapi import APIRouter, Depends, Request from fastapi.templating import Jinja2Templates from sqlalchemy.orm.session import Session from app.database.models import Event, User from app.dependencies import get_db, TEMPLATES_PATH from app.routers.dayview import ( DivAttributes, dayview, get_events_and_attributes ) templates = Jinja2Templates(directory=TEMPLATES_PATH) router = APIRouter() class DayEventsAndAttrs(NamedTuple): day: datetime template: Jinja2Templates.TemplateResponse events_and_attrs: Tuple[Event, DivAttributes] def get_week_dates(firstday: datetime) -> Iterator[datetime]: rest_of_days = [timedelta(days=1) for _ in range(6)] rest_of_days.insert(0, firstday) return accumulate(rest_of_days) async def get_day_events_and_attributes( request: Request, day: datetime, session: Session, user: User, ) -> DayEventsAndAttrs: template = await dayview( request=request, date=day.strftime('%Y-%m-%d'), view='week', session=session ) events_and_attrs = get_events_and_attributes( day=day, session=session, user_id=user.id) return DayEventsAndAttrs(day, template, events_and_attrs) @router.get('/week/{firstday}') async def weekview( request: Request, firstday: str, session=Depends(get_db) ): user = session.query(User).filter_by(username='test_username').first() firstday = datetime.strptime(firstday, '%Y-%m-%d') week_days = get_week_dates(firstday) week = [await get_day_events_and_attributes( request, day, session, user ) for day in week_days] return templates.TemplateResponse("weekview.html", { "request": request, "week": week, })
""" MIT License Copyright (c) 2021 Tim Schneider Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import warnings from .dynamixel_connector import DynamixelConnector, Field RHP12RN_EEPROM_FIELDS = [ Field(0, "H", "model_number", "Model Number", False, 35073), Field(2, "i", "model_information", "Model Information", False, None), Field(6, "B", "firmware_version", "Firmware Version", False, None), Field(7, "B", "id", "DYNAMIXEL ID", True, 1), Field(8, "B", "baud_rate", "Communication Speed", True, 1), Field(9, "B", "return_delay_time", "Response Delay Time", True, 250), Field(11, "B", "operating_mode", "Operating Mode", True, 5), Field(17, "i", "moving_threshold", "Velocity Threshold for Movement Detection", True, 10), Field(21, "B", "temperature_limit", "Maximum Internal Temperature Limit", True, 80), Field(22, "H", "max_voltage_limit", "Maximum Input Voltage Limit", True, 400), Field(24, "H", "min_voltage_limit", "Minimum Input Voltage Limit", True, 150), Field(26, "i", "acceleration_limit", "Maximum Accleration Limit", True, 255), Field(30, "H", "current_limit", "Maximum Current Limit", True, 820), Field(32, "i", "velocity_limit", "Maximum Velocity Limit", True, 100), Field(36, "i", "max_position_limit", "Maximum Position Limit", True, 1150), Field(40, "i", "min_position_limit", "Minimum Position Limit", True, 0), Field(44, "B", "external_port_mode_1", "External Port Mode 1", True, 0), Field(45, "B", "external_port_mode_2", "External Port Mode 2", True, 0), Field(46, "B", "external_port_mode_3", "External Port Mode 3", True, 0), Field(47, "B", "external_port_mode_4", "External Port Mode 4", True, 0), Field(48, "B", "shutdown", "Shutdown Error Information", True, 48) ] RHP12RN_EEPROM_FIELDS += [ Field(49 + i * 2, "H", "indirect_address_{}".format(i + 1), "Indirect Address {}".format(i + 1), True, 634 + i) for i in range(256) ] RHP12RN_RAM_FIELDS = [ Field(562, "B", "torque_enable", "Motor Torque On/Off", True, 0), Field(563, "B", "led_red", "Red LED Intensity Value", True, 0), Field(564, "B", "led_green", "Green LED Intensity Value", True, 0), Field(565, "B", "led_blue", "Blue LED Intensity Value", True, 0), Field(590, "H", "position_d_gain", "D Gain of Position", True, None), Field(592, "H", "position_i_gain", "I Gain of Position", True, None), Field(594, "H", "position_p_gain", "P Gain of Position", True, None), Field(596, "i", "goal_position", "Target Position Value", True, None), Field(600, "i", "goal_velocity", "Target Velocity Value", True, 0), Field(604, "H", "goal_current", "Target Current Value", True, 0), Field(606, "i", "goal_acceleration", "Target Acceleration Value", True, 0), Field(610, "B", "moving", "Movement Status", False, None), Field(611, "i", "present_position", "Present Position Value", False, None), Field(615, "i", "present_velocity", "Present Velocity Value", False, None), Field(621, "H", "present_current", "Present Current Value", False, None), Field(623, "H", "present_input_voltage", "Present Input Voltage", False, None), Field(625, "B", "present_temperature", "Present Internal Temperature", False, None), Field(626, "H", "external_port_data_1", "External Port Data 1", True, 0), Field(628, "H", "external_port_data_2", "External Port Data 2", True, 0), Field(630, "H", "external_port_data_3", "External Port Data 3", True, 0), Field(632, "H", "external_port_data_4", "External Port Data 4", True, 0) ] RHP12RN_RAM_FIELDS += [ Field(634 + i, "B", "indirect_data_{}".format(i + 1), "Indirect Data {}".format(i + 1), True, 0) for i in range(256) ] RHP12RN_RAM_FIELDS += [ Field(890, "B", "registered_instruction", "Check Reception of Instruction", False, 0), Field(891, "B", "status_return_level", "Select Types of Status Return", True, 2), Field(892, "B", "hardware_error_status", "Hardware Error Status", False, 0) ] RHP12RN_FIELDS = RHP12RN_EEPROM_FIELDS + RHP12RN_RAM_FIELDS class RHP12RNConnector(DynamixelConnector): def __init__(self, device: str = "/dev/ttyUSB0", baud_rate: int = 57600, dynamixel_id: int = 1): super(RHP12RNConnector, self).__init__( RHP12RN_FIELDS, device=device, baud_rate=baud_rate, dynamixel_id=dynamixel_id) def connect(self): super(RHP12RNConnector, self).connect() model_number = self.read_field("model_number") if model_number != self.fields["model_number"].initial_value: warnings.warn("The connected device does not appear to be a RH-P12-RN gripper.")
import os from setuptools import setup import codenerix_storages with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-codenerix-storages', version=codenerix_storages.__version__, packages=["codenerix_storages"], include_package_data=True, zip_safe=False, license='Apache License Version 2.0', description='Codenerix Storages is a module that enables CODENERIX to set storages on serveral platforms in a general manner.', long_description=README, url='https://github.com/codenerix/django-codenerix-storages', author=", ".join(codenerix_storages.__authors__), keywords=['django', 'codenerix', 'management', 'erp', 'crm', 'storages'], platforms=['OS Independent'], classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.10', 'Intended Audience :: Developers', 'License :: Other/Proprietary License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], install_requires=[ 'django-codenerix', 'django-codenerix-extensions', ] )
#!/usr/bin/python3 import prpg prpg.main()
# -*- coding: utf-8 -*- from flask import Flask from redis import StrictRedis import arrow redis_client = StrictRedis(host="192.168.0.111", port=6380, db=0, decode_responses=True) def create_app(): app = Flask(__name__) @app.route("/hello", methods=["GET", "POST"]) def hello(): date = arrow.now(tz="local").strftime("%Y%m%d") key = f"test_su_demo:{date}" if redis_client.exists(key): value = redis_client.incr(key) result = None else: value = redis_client.incr(key) result = redis_client.expire(key, 3600) return "incr_value:{},expire_value:{}".format(value, result) return app if __name__ == '__main__': app = create_app() app.run()
from property.zoopla import Zoopla from utils import db def get_listings(): db.insert_or_replace(table_name='Listings', items=Zoopla().get_listings())
import torch from tqdm import tqdm from sklearn.metrics import roc_auc_score as auc def train_desc(epoch, **kw): _ = ' | '.join([f'{k.title()} = {v:.5f}' for k, v in kw.items()]) return f'Epoch {epoch+1: >2}: ' + _ def fit(model, X, y, epochs=5, batch_size=128, loss_func=torch.nn.CrossEntropyLoss()): assert isinstance(y, torch.LongTensor) optimizer = torch.optim.Adam(model.parameters()) for e in range(epochs): # X, y = map(torch.LongTensor, shuffle(X.numpy(), y.numpy())) with tqdm(range(0, X.size(0), batch_size)) as batchs: for b in batchs: # for each training step # train your data... b_X = X[b:b + batch_size] b_y = y[b:b + batch_size] _y = model(b_X) # rnn output loss = loss_func(_y, b_y) # cross entropy loss and y is not one-hotted optimizer.zero_grad() # clear gradients for this training step loss.backward() # backpropagation, compute gradients optimizer.step() if b % 50 == 0: _ = train_desc(e, loss=loss, auc=auc(b_y.numpy(), _y[:, 1].data.numpy()), acc=(b_y==torch.max(_y, 1)[1]).sum().numpy()/len(_y)) batchs.set_description(_)
"""Template methods for API.""" # Standard Python Libraries import os # cisagov Libraries from dmcli.utils import api def get_templates(): """Get templates.""" return api.get("/api/templates/") def template_attributes(): """Get generated template attributes.""" return api.get("/api/templates/attributes/") def upload_template(filepath): """Upload template zip file.""" with open(filepath, "rb") as zipfile: content = zipfile.read() return api.post( path="/api/templates/", files={"zip": (os.path.basename(filepath), content)} )
"""Data resource.""" from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import requests from six.moves.urllib.parse import urljoin # pylint: disable=wrong-import-order from resdk.constants import CHUNK_SIZE from .base import BaseResolweResource from .descriptor import DescriptorSchema from .utils import get_descriptor_schema_id, is_descriptor_schema, iterate_schema class Data(BaseResolweResource): """Resolwe Data resource. One and only one of the identifiers (slug, id or model_data) should be given. :param resolwe: Resolwe instance :type resolwe: Resolwe object :param model_data: Resource model data """ endpoint = 'data' #: (lazy loaded) annotated ``Sample`` to which ``Data`` object belongs _sample = None #: (lazy loaded) list of collections to which data object belongs _collections = None WRITABLE_FIELDS = ('descriptor_schema', 'descriptor', 'tags') + BaseResolweResource.WRITABLE_FIELDS UPDATE_PROTECTED_FIELDS = ('input', 'process') + BaseResolweResource.UPDATE_PROTECTED_FIELDS READ_ONLY_FIELDS = ('process_input_schema', 'process_output_schema', 'output', 'started', 'finished', 'checksum', 'status', 'process_progress', 'process_rc', 'process_info', 'process_warning', 'process_error', 'process_type', 'process_name') + BaseResolweResource.READ_ONLY_FIELDS ALL_PERMISSIONS = ['view', 'download', 'edit', 'share', 'owner'] def __init__(self, resolwe, **model_data): """Initialize attributes.""" #: descriptor schema id in which data object is self._descriptor_schema = None #: (lazy loaded) descriptor schema object in which data object is self._hydrated_descriptor_schema = None #: Flattened dict of inputs and outputs, where keys are dit separated paths to values self.annotation = {} #: specification of inputs self.process_input_schema = None #: actual input values self.input = None #: specification of outputs self.process_output_schema = None #: actual output values self.output = None #: annotation data, with the form defined in descriptor_schema self.descriptor = None #: The ID of the process used in this data object self.process = None #: start time of the process in data object self.started = None #: finish time of the process in data object self.finished = None #: checksum field calculated on inputs self.checksum = None #: process status - Possible values: Uploading(UP), Resolving(RE), #: Waiting(WT), Processing(PR), Done(OK), Error(ER), Dirty (DR) self.status = None #: process progress in percentage self.process_progress = None #: Process algorithm return code self.process_rc = None #: info log message (list of strings) self.process_info = None #: warning log message (list of strings) self.process_warning = None #: error log message (list of strings) self.process_error = None #: what kind of output does process produce self.process_type = None #: process name self.process_name = None #: data object's tags self.tags = None super(Data, self).__init__(resolwe, **model_data) self.logger = logging.getLogger(__name__) def update(self): """Clear cache and update resource fields from the server.""" self._sample = None self._collections = None self._hydrated_descriptor_schema = None super(Data, self).update() def _update_fields(self, payload): """Update the Data object with new data. :param dict payload: Data resource fields :rtype: None """ BaseResolweResource._update_fields(self, payload) if 'input' in payload and 'process_input_schema' in payload: self.annotation.update( self._flatten_field(payload['input'], payload['process_input_schema'], 'input') ) if 'output' in payload and 'process_output_schema' in payload: self.annotation.update( self._flatten_field(payload['output'], payload['process_output_schema'], 'output') ) # TODO: Descriptor schema! def _flatten_field(self, field, schema, path): """Reduce dicts of dicts to dot separated keys. :param field: Field instance (e.g. input) :type field: dict :param schema: Schema instance (e.g. input_schema) :type schema: dict :param path: Field path :type path: string :return: flattened annotations :rtype: dictionary """ flat = {} for field_schema, fields, path in iterate_schema(field, schema, path): name = field_schema['name'] typ = field_schema['type'] label = field_schema['label'] value = fields[name] if name in fields else None flat[path] = {'name': name, 'value': value, 'type': typ, 'label': label} return flat @property def collections(self): """Return list of collections to which data object belongs.""" if self.id is None: raise ValueError('Instance must be saved before accessing `collections` attribute.') if self._collections is None: self._collections = self.resolwe.collection.filter(data=self.id) return self._collections @property def sample(self): """Get ``sample`` that object belongs to.""" if self.id is None: raise ValueError('Instance must be saved before accessing `sample` attribute.') if self._sample is None: self._sample = self.resolwe.sample.filter(data=self.id) self._sample = self._sample[0] if self._sample else None return self._sample @property def descriptor_schema(self): """Return descriptor schema assigned to the data object.""" if self._descriptor_schema is None: return None if self._hydrated_descriptor_schema is None: if isinstance(self._descriptor_schema, int): query_filters = {'id': self._descriptor_schema} else: query_filters = {'slug': self._descriptor_schema} self._hydrated_descriptor_schema = self.resolwe.descriptor_schema.get( ordering='-version', limit=1, **query_filters ) return self._hydrated_descriptor_schema @descriptor_schema.setter def descriptor_schema(self, dschema): """Set collection to which relation belongs.""" # On single data object endpoint descriptor schema is already # hidrated, so it should be transformed into resource. if isinstance(dschema, dict): dschema = DescriptorSchema(resolwe=self.resolwe, **dschema) self._descriptor_schema = get_descriptor_schema_id(dschema) # Save descriptor schema if already hydrated, otherwise it will be rerived in getter self._hydrated_descriptor_schema = dschema if is_descriptor_schema(dschema) else None def _files_dirs(self, field_type, file_name=None, field_name=None): """Get list of downloadable fields.""" download_list = [] def put_in_download_list(elm, fname): """Append only files od dirs with equal name.""" if field_type in elm: if file_name is None or file_name == elm[field_type]: download_list.append(elm[field_type]) else: raise KeyError("Item {} does not contain '{}' key.".format(fname, field_type)) if field_name and not field_name.startswith('output.'): field_name = 'output.{}'.format(field_name) for ann_field_name, ann in self.annotation.items(): if (ann_field_name.startswith('output') and (field_name is None or field_name == ann_field_name) and ann['value'] is not None): if ann['type'].startswith('basic:{}:'.format(field_type)): put_in_download_list(ann['value'], ann_field_name) elif ann['type'].startswith('list:basic:{}:'.format(field_type)): for element in ann['value']: put_in_download_list(element, ann_field_name) return download_list def _get_dir_files(self, dir_name): files_list, dir_list = [], [] dir_url = urljoin(self.resolwe.url, 'data/{}/{}'.format(self.id, dir_name)) if not dir_url.endswith('/'): dir_url += '/' response = requests.get(dir_url, auth=self.resolwe.auth) response = json.loads(response.content.decode('utf-8')) for obj in response: obj_path = '{}/{}'.format(dir_name, obj['name']) if obj['type'] == 'directory': dir_list.append(obj_path) else: files_list.append(obj_path) if dir_list: for new_dir in dir_list: files_list.extend(self._get_dir_files(new_dir)) return files_list def files(self, file_name=None, field_name=None): """Get list of downloadable file fields. Filter files by file name or output field. :param file_name: name of file :type file_name: string :param field_name: output field name :type field_name: string :rtype: List of tuples (data_id, file_name, field_name, process_type) """ if not self.id: raise ValueError('Instance must be saved before using `files` method.') file_list = self._files_dirs('file', file_name, field_name) for dir_name in self._files_dirs('dir', file_name, field_name): file_list.extend(self._get_dir_files(dir_name)) return file_list def download(self, file_name=None, field_name=None, download_dir=None): """Download Data object's files and directories. Download files and directoriesfrom the Resolwe server to the download directory (defaults to the current working directory). :param file_name: name of file or directory :type file_name: string :param field_name: file or directory field name :type field_name: string :param download_dir: download path :type download_dir: string :rtype: None Data objects can contain multiple files and directories. All are downloaded by default, but may be filtered by name or output field: * re.data.get(42).download(file_name='alignment7.bam') * re.data.get(42).download(field_name='bam') """ if file_name and field_name: raise ValueError("Only one of file_name or field_name may be given.") files = ['{}/{}'.format(self.id, fname) for fname in self.files(file_name, field_name)] self.resolwe._download_files(files, download_dir) # pylint: disable=protected-access def print_annotation(self): """Provide annotation data.""" # TODO: Think of a good way to present all annotation raise NotImplementedError() def stdout(self): """Return process standard output (stdout.txt file content). Fetch stdout.txt file from the corresponding Data object and return the file content as string. The string can be long and ugly. :rtype: string """ output = b'' url = urljoin(self.resolwe.url, 'data/{}/stdout.txt'.format(self.id)) response = requests.get(url, stream=True, auth=self.resolwe.auth) if not response.ok: response.raise_for_status() else: for chunk in response.iter_content(chunk_size=CHUNK_SIZE): output += chunk return output.decode("utf-8")
from django.contrib import admin class GroundtruthRecordAdminMixin(admin.ModelAdmin): fields = ('groundtruth_target', 'actual_use', 'contact_name', 'contact_email', 'contact_phone', 'added',) list_display = ('pk', 'groundtruth_target', 'actual_use', 'contact_name', 'contact_email', 'contact_phone', 'added',) readonly_fields = ('added', 'groundtruth_target',) def groundtruth_target(self, obj): try: return '<a href="%s" target="_blank">%s</a>' % ( obj.content_object.get_absolute_url(), obj.content_object ) except Exception: return '' groundtruth_target.allow_tags = True
""" shaa2tn.py - convert a Shaarli HTML export to a Trilium Notes markdown.tar import. Terry N. Brown terrynbrown@gmail.com Tue Aug 27 19:21:47 CDT 2019 """ import argparse import os import random import xml.etree.ElementTree as ET from trilium_io import attr_template, node_template, write_tar # used to generate Trilium node IDs ID_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" def make_parser(): """Prepare an argument parser""" parser = argparse.ArgumentParser( description="""convert a Shaarli HTML export to a Trilium Notes markdown.tar import.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("shaarli", help="The shaarli file to process") parser.add_argument("trilium", help="Trilium output file") parser.add_argument( "--node-type", help="'html' or 'markdown' nodes created in Trilium", default="html", ) return parser def get_options(args=None): """ get_options - use argparse to parse args, and return a argparse.Namespace, possibly with some changes / expansions / validatations. Client code should call this method with args as per sys.argv[1:], rather than calling make_parser() directly. Args: args ([str]): arguments to parse Returns: argparse.Namespace: options with modifications / validations """ opt = make_parser().parse_args(args) # modifications / validations go here return opt def strike_through(text): """Replace ~~foo~~ with <s>foo</s> to support strike-through in output""" text = text.split('\n') for line_i, line in enumerate(text): if '~~' not in line: continue line = line.split('~~') parts = [] for part_i, part in enumerate(line): if part_i % 2 == 0: parts.append(part) else: parts.append("<s>%s</s>" % part) text[line_i] = ''.join(parts) return '\n'.join(text) def get_bookmarks(htmlpath): """Read Shaarli .html database export""" dom = ET.parse(htmlpath) # filter out a couple of empty <p/>s dlist = [i for i in dom.findall('.//dl/*') if i.tag in ('dt', 'dd')] # An error in Shaarli export of bodyless (no dd) links: # <dt link 1 stuff><dt link 2 stuff></dt></dt><dd>link 2 stuff</dd> # instead of # <dt link 1 stuff></dt><dt link 2 stuff></dt><dd>link 2 stuff</dd> # this digs all the buried <dt>s out dlist2 = [] for ele in dlist: dlist2.append(ele) dlist2.extend(ele.findall(".//dt")) dlist = dlist2 bookmarks = [] while dlist: title = dlist.pop(0) assert title.tag == 'dt', title.tag title = title.find('a') body = dlist.pop(0).text if dlist and dlist[0].tag == 'dd' else "" if title.get('href', '').startswith('?'): href = None # a Shaarli note with no link else: href = title.get('href') body = ("[link](%s)\n\n%s" % (href, body)).strip() body = strike_through(body) bookmarks.append( { 'title': title.text, 'tags': title.get('tags', "").split(','), 'body': body, 'add_date': title.get('add_date'), 'href': href, } ) if title.get('private'): bookmarks[-1]['tags'].append("shaarli_private") bookmarks[-1]['tags'].append("shaarli_import") return bookmarks def make_node_id(): return ''.join(random.choices(ID_CHARS, k=12)) def write_bookmarks(opt, bookmarks): """writes metadata and .md files to folder and creates .tar""" items = [] for bookmark_i, bookmark in enumerate(bookmarks): node = node_template( {'title': bookmark['title'], 'body': bookmark['body']} ) if opt.node_type == 'markdown': node.update({'type': "code", 'mime': "text/x-markdown"}) items.append(node) node['_ext']['tags'].extend(bookmark['tags']) attrs = node['attributes'] attrs.append( attr_template( { "type": "label", "name": "shaarli_date", "value": bookmark['add_date'], } ) ) if bookmark['body']: node['_ext']['body'] = bookmark['body'] write_tar(opt.trilium, items) def main(): opt = get_options() if not os.path.exists(opt.shaarli): html = opt.shaarli + '.html' if os.path.exists(html): opt.shaarli = html if not os.path.exists(opt.shaarli): print("Can't find '%s'" % opt.shaarli) exit(10) if not opt.trilium.lower().endswith('.tar'): opt.trilium += '.tar' bookmarks = get_bookmarks(opt.shaarli) write_bookmarks(opt, bookmarks) if __name__ == "__main__": main()