answer stringlengths 15 1.25M |
|---|
#ifndef HARDCODED_SHADERS_H
#define HARDCODED_SHADERS_H
#include "common/shader_structs.h"
#define BASIC_SHADER 0
extern struct shader_load_command basic_sh_load_cmd;
#define SDF_SHADER 1
extern struct shader_load_command sdf_sh_load_cmd;
#define DISP_EFFECT_SHADER 2
extern struct shader_load_command <API key>;
#define BLOOM_SHADER 3
extern struct shader_load_command bloom_sh_load_cmd;
#endif |
// LBPhotoPreviewCell.h
// <API key>
#import <UIKit/UIKit.h>
#import "LBPhotoPreviewModel.h"
@interface LBPhotoPreviewCell : <API key>
@property (nonatomic, strong) LBPhotoPreviewModel *model;
@end |
package com.example.oltu.client.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Service;
import com.google.common.base.Strings;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
@Service
public class OAuth2Service {
private static final String CLIENT_ID = "<API key>";
private static final String CLIENT_SCERET = "<API key>";
private static final String REDIRECT_URI = "http://app1.example.com/oauth2/callback";
public String getUserName(String code) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
String accessToken = getAccessToken(httpClient, code);
if (!Strings.isNullOrEmpty(accessToken)) {
String url = "http://login.example.com/get_token_info?access_token=" + accessToken;
String body = "";// httpClient.get(url);
if (body.contains("name")) {
Map<String, String> map = new Gson().fromJson(body, new TypeToken<Map<String, String>>() {
}.getType());
return map.get("name");
}
}
return "";
}
private String getAccessToken(HttpClient httpClient, String code) {
String url = "http://login.example.com/oauth2/access_token";
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("client_id", CLIENT_ID));
nvps.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI));
nvps.add(new BasicNameValuePair("client_secret", CLIENT_SCERET));
nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
nvps.add(new BasicNameValuePair("code", code));
String body = "";// httpClient.post(url, nvps);
System.out.println(body);
if (body.contains("access")) {
Gson gson = new GsonBuilder().<API key>(FieldNamingPolicy.<API key>)
.create();
OAuth2AccessToken token = gson.fromJson(body, OAuth2AccessToken.class);
return token.getAccessToken();
}
return "";
}
class OAuth2AccessToken {
private String accessToken;
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessToken() {
return accessToken;
}
}
} |
namespace Construktion
{
public interface ExitBlueprint
{
bool Matches(object item, ConstruktionContext context);
object Construct(object item, <API key> pipeline);
}
public interface ExitBlueprint<T>
{
bool Matches(T item, ConstruktionContext context);
T Construct(T item, <API key> pipeline);
}
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ansiStyles = require("ansi-styles");
var ansi2css = require("./ansi2css/index");
exports.fg = {
red: function (text) {
return ansiStyles.red.open +
ansiStyles.bold.open +
text +
ansiStyles.bold.close +
ansiStyles.red.close;
},
green: function (text) {
return ansiStyles.green.open +
ansiStyles.bold.open +
text +
ansiStyles.bold.close +
ansiStyles.green.close;
},
yellow: function (text) {
return ansiStyles.yellow.open +
ansiStyles.bold.open +
text +
ansiStyles.bold.close +
ansiStyles.yellow.close;
},
blue: function (text) {
return ansiStyles.blue.open +
ansiStyles.bold.open +
text +
ansiStyles.bold.close +
ansiStyles.blue.close;
},
purple: function (text) {
return ansiStyles.magenta.open +
ansiStyles.bold.open +
text +
ansiStyles.bold.close +
ansiStyles.magenta.close;
},
cyan: function (text) {
return ansiStyles.cyan.open +
ansiStyles.bold.open +
text +
ansiStyles.bold.close +
ansiStyles.cyan.close;
},
white: function (text) {
return ansiStyles.white.open +
text +
ansiStyles.white.close;
},
};
exports.fgCycles = [
exports.fg.yellow,
exports.fg.green,
exports.fg.red,
exports.fg.blue,
exports.fg.purple,
exports.fg.cyan,
];
var prefixColorMap = {};
var prefixCycle = 0;
var levelMap = {
silly: exports.fg.white,
debug: exports.fg.purple,
verbose: exports.fg.blue,
info: exports.fg.green,
warn: exports.fg.yellow,
error: exports.fg.red,
};
function levelColor(level) {
if (levelMap.hasOwnProperty(level))
return levelMap[level];
else
return exports.fg.white;
}
function prefixColor(prefix) {
if (!prefixColorMap.hasOwnProperty(prefix)) {
var colorIndex = prefixCycle++ % exports.fgCycles.length;
prefixColorMap[prefix] = colorIndex;
}
return exports.fgCycles[prefixColorMap[prefix]];
}
function getNewColorCycle() {
var index = -1;
return function () {
++index;
if (index >= exports.fgCycles.length)
index = 0;
return exports.fgCycles[index];
};
}
exports.getNewColorCycle = getNewColorCycle;
function colorizeLevel(level) {
return levelColor(level)(level);
}
exports.colorizeLevel = colorizeLevel;
function colorizePrefix(prefix) {
return prefixColor(prefix)(prefix);
}
exports.colorizePrefix = colorizePrefix;
exports.browsify = ansi2css.textToParts;
//# sourceMappingURL=colors.js.map |
package day14
import (
"fmt"
"strings"
"crypto/md5"
"github.com/gsmcwhirter/advent2016/lib"
)
func LoadData(filename string) string {
dat := lib.ReadFileData(filename)
return strings.Trim(string(dat), "\n")
}
func GenerateHash(salt string, index int) []rune {
return []rune(fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%v%v", salt, index)))))
}
func <API key>(salt string, index int) []rune {
hash := string(GenerateHash(salt, index))
for i := 0; i < 2016; i++ {
hash = fmt.Sprintf("%x", md5.Sum([]byte(hash)))
}
return []rune(hash)
}
func HashHas5Consecutive(hash []rune, target rune) bool {
for i := 0; i < len(hash)-4; i++ {
fiveOkay := true
for j := 0; j < 5; j++ {
if hash[i+j] != target {
fiveOkay = false
break
}
}
if fiveOkay {
return true
}
}
return false
}
func HashIndicatesKey(salt string, index int, hash []rune, HashGen func(string, int) []rune, hashHistory map[int][]rune) (bool, map[int][]rune) {
extraHashes := map[int][]rune{}
keyRune := 'x' // hash is hex, so this will never be valid
for i, iRune := range hash[:len(hash)-2] {
if hash[i+1] == iRune && hash[i+2] == iRune {
keyRune = iRune
break
}
}
if keyRune == 'x' {
return false, extraHashes
}
for j := 1; j <= 1000; j++ {
nextHash, exists := hashHistory[index+j]
if !exists {
nextHash = HashGen(salt, index+j)
extraHashes[index+j] = nextHash
}
if HashHas5Consecutive(nextHash, keyRune) {
return true, extraHashes
}
}
return false, extraHashes
}
func RunPartA(filename string) {
salt := LoadData(filename)
keysFound := 0
var lastKey int
index := 0
for keysFound < 64 {
hash := GenerateHash(salt, index)
isKey, _ := HashIndicatesKey(salt, index, hash, GenerateHash, map[int][]rune{})
if isKey {
lastKey = index
keysFound++
fmt.Printf("Key %v is %v\n", keysFound, lastKey)
}
index++
}
fmt.Println(lastKey)
}
func RunPartB(filename string) {
salt := LoadData(filename)
keysFound := 0
var lastKey int
hashLookup := map[int][]rune{
0: <API key>(salt, 0),
}
index := 0
for keysFound < 64 {
hash, exists := hashLookup[index]
if !exists {
hash = <API key>(salt, index)
}
isKey, extraHashes := HashIndicatesKey(salt, index, hash, <API key>, hashLookup)
if isKey {
lastKey = index
keysFound++
fmt.Printf("Key %v is %v\n", keysFound, lastKey)
}
for k, v := range extraHashes {
hashLookup[k] = v
}
index++
}
fmt.Println(lastKey)
} |
package lmtas.app.com.lmtas;
import org.junit.Test;
import static org.junit.Assert.*;
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} |
USE [Koski_SA]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [sa].[<API key>] AS
IF EXISTS (SELECT * FROM sys.indexes WHERE name='NC_amm_paataso' AND object_id = OBJECT_ID('sa.<API key>'))
BEGIN
DROP INDEX [NC_amm_paataso] ON sa.<API key>
END
TRUNCATE TABLE sa.<API key>
INSERT INTO sa.<API key>
SELECT
a.opiskeluoikeus_oid
,a.<API key>
,a.suorituksen_tyyppi
,tutkinto_koodi = coalesce(kl.uusi_eat_koodi, kl.<API key>)
,a.<API key>
,a.tutkinto_koodiarvo
,a.<API key>
,a.toimipiste_oid
,a.<API key>
,a.<API key>
,a.<API key>
,a.vahvistus_paiva
,a.<API key>
,a.rnk
FROM
(
SELECT DISTINCT
ps.opiskeluoikeus_oid
,<API key>
,suorituksen_tyyppi
,<API key>
,tutkinto_koodiarvo
,<API key>
,toimipiste_oid
,<API key>
,<API key>
,<API key> = case when <API key> in ('FI','SE','SV','EN','RU','RI','VK') then <API key> else 'XX' end
,vahvistus_paiva
,<API key> = CASE WHEN YEAR(<API key>) < 1900 THEN NULL ELSE <API key> END
,ROW_NUMBER() OVER (PARTITION BY ps.opiskeluoikeus_oid ORDER BY ca.<API key>,<API key>,<API key>) as rnk
FROM sa.<API key> ps
JOIN sa.<API key> oo on oo.opiskeluoikeus_oid = ps.opiskeluoikeus_oid
CROSS APPLY (
SELECT
<API key> =
case ps.suorituksen_tyyppi
when '<API key>' then 1
when '<API key>' then 2
when '<API key>' then 3
when 'telma' then 4
when 'tutkinnonosaapienemmistäkokonaisuuksistakoostuvasuoritus' then 5
when 'valma' then 6
when '<API key>' then 10
else 9
end
) ca
WHERE oo.koulutusmuoto = '<API key>'
--AND ps.suorituksen_tyyppi != '<API key>'
) a
LEFT JOIN ANTERO.dw.d_koulutusluokitus kl ON kl.<API key> = (CASE WHEN LEN(a.<API key>) > 6 THEN NULL ELSE COALESCE(NULLIF(a.<API key>, '999904'), a.tutkinto_koodiarvo) END)
CREATE NONCLUSTERED INDEX [NC_amm_paataso] ON [sa].[<API key>]
(
[opiskeluoikeus_oid] ASC,
[suorituksen_tyyppi] ASC,
[vahvistus_paiva] ASC
)WITH (PAD_INDEX = OFF, <API key> = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] |
import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '(4c=bbck6l7(ws%o9%7q-$_*zlbidtmd38w4763_5*_-d_dss)'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'django_ses',
'account',
# Local apps
'heros',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.<API key>,
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.<API key>',
'whitenoise.middleware.<API key>',
'account.middleware.LocaleMiddleware',
'account.middleware.TimezoneMiddleware',
# Custom middlewares
]
ROOT_URLCONF = 'dota_world.urls'
APPEND_SLASH = True
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'dota_world.context_processors.site_processor',
],
},
},
]
WSGI_APPLICATION = 'dota_world.wsgi.application'
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
# CACHE CONFIGURATION
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
# END CACHE CONFIGURATION
# Database Configuration
# Development database
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
# 'NAME': 'dotadb',
# 'USER': 'dotauser',
# 'PASSWORD': 'doTaSecret',
# 'HOST': 'localhost',
# 'PORT': '5432',
# # Production database
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'DB_NAME',
# 'USER': 'DB_USER',
# 'PASSWORD': 'DB_PASSWORD',
# 'HOST': 'localhost', # Or an IP Address that your DB is hosted on
# 'PORT': '3306',
# Heroku Database Configuration
import dj_database_url
DATABASES = {
'default': dj_database_url.config()
}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
<API key> = ('<API key>', 'https')
# Password validation
# <API key> = [
# 'NAME': 'django.contrib.auth.password_validation.<API key>',
# 'NAME': 'django.contrib.auth.password_validation.<API key>',
# 'NAME': 'django.contrib.auth.password_validation.<API key>',
# 'NAME': 'django.contrib.auth.password_validation.<API key>',
SITE_ID = 1
# <API key>
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Logging Configuration
LOGGING = {
'version': 1,
'<API key>': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler',
'formatter': 'verbose'
},
'console': {
'level': 'ERROR',
'class': 'logging.StreamHandler',
'stream': sys.stdout,
'formatter': 'verbose'
},
'file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': 'logs/dota_world.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers': ['file'],
'propagate': True,
'level': 'ERROR',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'': { # generic logger for all django apps. For specific app use format like 'cms.views'.
'handlers': ['console', 'file'],
'level': 'ERROR'
},
}
}
# Media Configuration
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, "static/")
# STATIC_ROOT = 'staticfiles'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Add media directory and its base url for user uploads
MEDIA_URL = '/site_media/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "site_media/")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'project_static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.<API key>',
)
# Simplified static file serving.
# STATICFILES_STORAGE = 'whitenoise.django.<API key>'
# Account configuration (<API key>)
<API key> = True
<API key> = False
<API key> = False
ACCOUNT_OPEN_SIGNUP = False
# <API key> = {
# "account.auth_backends.Email<API key>
# Specified in seconds. Enable caching by setting this to a value greater than 0.
RESPONSE_CACHE_TTL = 60 * 60
# Email configuration
DEFAULT_FROM_EMAIL = 'DotaWorld <noreply@mydomain.com>'
# # Email settings (SMTP from Google)
# EMAIL_HOST = 'smtp.gmail.com'
# EMAIL_HOST_USER = ''
# EMAIL_HOST_PASSWORD = ''
# EMAIL_USE_TLS = True
# EMAIL_PORT = 587
# Email settings (SES from AWS)
EMAIL_BACKEND = 'django_ses.SESBackend'
# These are optional -- if they're set as environment variables they won't
# need to be set here as well
AWS_ACCESS_KEY_ID = 'YOUR-AWS-ACCESS-KEY'
<API key> = 'YOUR-AWS-SECRET-KEY'
# Additionally, you can specify an optional region, like so:
AWS_SES_REGION_NAME = 'us-west-2'
<API key> = 'email.us-west-2.amazonaws.com'
# Google Maps configuration
GOOGLE_MAPS_<TwitterConsumerkey>'
# Lastly, see if the developer has any local overrides.
try:
from .private import * # pylint: disable=import-error
except ImportError:
pass |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title></title>
<meta http-equiv="refresh" content="0; url=../#work/alior/index.html">
</head>
<body>
<p>
</p>
</body>
</html> |
/* jslint node: true */
'use strict';
// Tries to load settings from the parent directory.
// Recognized settings
// ../settings.js
// redis.port ; network port, number
// redis.host ; domain, string
// redis.database ; sub database, number
var settings;
try {
settings = require('../settings');
} catch (e) {
settings = {};
}
// Defaults
var setup = {
port: 6379,
host: '127.0.0.1',
database: 0
};
// Extend
if (settings.hasOwnProperty('redis')) {
for (var a in settings.redis) { setup[a] = settings.redis[a]; }
}
module.exports = setup; |
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.6
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
# Allow only one "make -f Makefile2" at a time, but pass parallelism.
.NOTPARALLEL:
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .<API key>
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /home/202145/Downloads/clion-2016.3/bin/cmake/bin/cmake
# The command to remove a file.
RM = /home/202145/Downloads/clion-2016.3/bin/cmake/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/202145/Desktop/Cpp-exercises/complex
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/202145/Desktop/Cpp-exercises/complex/cmake-build-debug
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..."
/home/202145/Downloads/clion-2016.3/bin/cmake/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available.
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/home/202145/Downloads/clion-2016.3/bin/cmake/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# The main all target
all: <API key>
$(CMAKE_COMMAND) -E <API key> /home/202145/Desktop/Cpp-exercises/complex/cmake-build-debug/CMakeFiles /home/202145/Desktop/Cpp-exercises/complex/cmake-build-debug/CMakeFiles/progress.marks
$(MAKE) -f CMakeFiles/Makefile2 all
$(CMAKE_COMMAND) -E <API key> /home/202145/Desktop/Cpp-exercises/complex/cmake-build-debug/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
$(MAKE) -f CMakeFiles/Makefile2 preinstall
.PHONY : preinstall/fast
# clear depends
depend:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
# Target rules for targets named complex
# Build rule for target.
complex: <API key>
$(MAKE) -f CMakeFiles/Makefile2 complex
.PHONY : complex
# fast build rule for target.
complex/fast:
$(MAKE) -f CMakeFiles/complex.dir/build.make CMakeFiles/complex.dir/build
.PHONY : complex/fast
complex.o: complex.cpp.o
.PHONY : complex.o
# target to build an object file
complex.cpp.o:
$(MAKE) -f CMakeFiles/complex.dir/build.make CMakeFiles/complex.dir/complex.cpp.o
.PHONY : complex.cpp.o
complex.i: complex.cpp.i
.PHONY : complex.i
# target to preprocess a source file
complex.cpp.i:
$(MAKE) -f CMakeFiles/complex.dir/build.make CMakeFiles/complex.dir/complex.cpp.i
.PHONY : complex.cpp.i
complex.s: complex.cpp.s
.PHONY : complex.s
# target to generate assembly for a file
complex.cpp.s:
$(MAKE) -f CMakeFiles/complex.dir/build.make CMakeFiles/complex.dir/complex.cpp.s
.PHONY : complex.cpp.s
main.o: main.cpp.o
.PHONY : main.o
# target to build an object file
main.cpp.o:
$(MAKE) -f CMakeFiles/complex.dir/build.make CMakeFiles/complex.dir/main.cpp.o
.PHONY : main.cpp.o
main.i: main.cpp.i
.PHONY : main.i
# target to preprocess a source file
main.cpp.i:
$(MAKE) -f CMakeFiles/complex.dir/build.make CMakeFiles/complex.dir/main.cpp.i
.PHONY : main.cpp.i
main.s: main.cpp.s
.PHONY : main.s
# target to generate assembly for a file
main.cpp.s:
$(MAKE) -f CMakeFiles/complex.dir/build.make CMakeFiles/complex.dir/main.cpp.s
.PHONY : main.cpp.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... edit_cache"
@echo "... rebuild_cache"
@echo "... complex"
@echo "... complex.o"
@echo "... complex.i"
@echo "... complex.s"
@echo "... main.o"
@echo "... main.i"
@echo "... main.s"
.PHONY : help
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
<API key>:
$(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : <API key> |
<?php
namespace Helldar\Vk\Controllers\Database;
use Helldar\Vk\Controllers\Controller;
class <API key> extends Controller
{
/**
* Available method parameters.
*
* @var array
*/
protected $parameters = ['country_ids'];
} |
namespace GitVersion
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibGit2Sharp;
static class LibGitExtensions
{
public static DateTimeOffset When(this Commit commit)
{
return commit.Committer.When;
}
<summary>
Checks if the two branch objects refer to the same branch (have the same friendly name).
</summary>
public static bool IsSameBranch(this Branch branch, Branch otherBranch)
{
// For each branch, fixup the friendly name if the branch is remote.
var <API key> = otherBranch.IsRemote ?
otherBranch.FriendlyName.Substring(otherBranch.FriendlyName.IndexOf("/", StringComparison.Ordinal) + 1) :
otherBranch.FriendlyName;
var branchFriendlyName = branch.IsRemote ?
branch.FriendlyName.Substring(branch.FriendlyName.IndexOf("/", StringComparison.Ordinal) + 1) :
branch.FriendlyName;
return <API key> == branchFriendlyName;
}
<summary>
Exclude the given branches (by value equality according to friendly name).
</summary>
public static IEnumerable<BranchCommit> ExcludingBranches(this IEnumerable<BranchCommit> branches, IEnumerable<Branch> branchesToExclude)
{
return branches.Where(b => branchesToExclude.All(bte => !IsSameBranch(b.Branch, bte)));
}
<summary>
Exclude the given branches (by value equality according to friendly name).
</summary>
public static IEnumerable<Branch> ExcludingBranches( this IEnumerable<Branch> branches, IEnumerable<Branch> branchesToExclude)
{
return branches.Where(b => branchesToExclude.All(bte => !IsSameBranch(b, bte)));
}
public static GitObject PeeledTarget(this Tag tag)
{
var target = tag.Target;
while (target is TagAnnotation)
{
target = ((TagAnnotation)(target)).Target;
}
return target;
}
public static IEnumerable<Commit> CommitsPriorToThan(this Branch branch, DateTimeOffset olderThan)
{
return branch.Commits.SkipWhile(c => c.When() > olderThan);
}
public static bool IsDetachedHead(this Branch branch)
{
return branch.CanonicalName.Equals("(no branch)", StringComparison.OrdinalIgnoreCase);
}
public static string <API key>(this IRepository repository, bool omitGitPostFix = true)
{
var gitDirectory = repository.Info.Path;
gitDirectory = gitDirectory.TrimEnd(Path.<API key>);
if (omitGitPostFix && gitDirectory.EndsWith(".git"))
{
gitDirectory = gitDirectory.Substring(0, gitDirectory.Length - ".git".Length);
gitDirectory = gitDirectory.TrimEnd(Path.<API key>);
}
return gitDirectory;
}
public static void <API key>(this IRepository repository, params string[] fileNames)
{
if (fileNames == null || fileNames.Length == 0)
{
return;
}
Logger.WriteInfo("Checking out files that might be needed later in dynamic repository");
foreach (var fileName in fileNames)
{
try
{
Logger.WriteInfo(string.Format(" Trying to check out '{0}'", fileName));
var headBranch = repository.Head;
var tip = headBranch.Tip;
var treeEntry = tip[fileName];
if (treeEntry == null)
{
continue;
}
var fullPath = Path.Combine(repository.<API key>(), fileName);
using (var stream = ((Blob)treeEntry.Target).GetContentStream())
{
using (var streamReader = new BinaryReader(stream))
{
File.WriteAllBytes(fullPath, streamReader.ReadBytes((int)stream.Length));
}
}
}
catch (Exception ex)
{
Logger.WriteWarning(string.Format(" An error occurred while checking out '{0}': '{1}'", fileName, ex.Message));
}
}
}
}
} |
module IVLE
module IVLEModule
def modules(duration=0, include_all_info=true)
api 'Modules', duration: duration, includeallinfo: include_all_info
end
def modules_staff(duration=0, include_all_info=true)
api 'Modules_Staff', duration: duration, includeallinfo: include_all_info
end
def modules_student(duration=0, include_all_info=true)
api 'Modules_Student', duration: duration, includeallinfo: include_all_info
end
def module(course_id, title_only=false, duration=0, include_all_info=true)
api 'Module', courseid: course_id, titleonly: title_only, duration: duration, includeallinfo: include_all_info
end
def modules_search(search_parameters={}, duration=0, include_all_info=true)
# Verbatim from API docs: AuthToken, ModuleCode, ModuleTitle, LecturerName, Department, Semester, AcadYear, ModNameExact,
# LecNameExact, tag are optional fields. But at least one must be supplied.
api 'Modules_Search', search_parameters.merge({ duration: duration, includeallinfo: include_all_info })
end
def module_lecturers(course_id, duration=0)
api 'Module_Lecturers', courseid: course_id, duration: duration
end
def module_information(course_id, duration=0)
api 'Module_Information', courseid: course_id, duration: duration
end
def module_weblinks(course_id)
api 'Module_Weblinks', courseid: course_id
end
def <API key>(course_id, duration=0)
api '<API key>', courseid: course_id, duration: duration
end
def <API key>(course_id, duration=0)
api '<API key>', courseid: course_id, duration: duration
end
def module_reading(course_id, duration=0)
api 'Module_Reading', courseid: course_id, duration: duration
end
def modules_taken(student_id)
api 'Modules_Taken', studentid: student_id
end
end
end |
// lua.hpp
// Lua header files for C++
// <<extern "C">> not supplied automatically because Lua also compiles as C++
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
} |
import { Component } from '@angular/core';
@Component({
selector: 'app-body',
templateUrl: './body.component.html'
})
export class BodyComponent {
projects:string[][] = [['Creative Commons','Licencias de autor.'],
['Open Library.','Base de datos de libros colaborativa y de acceso público.'],
['RSS','Formato de fuente web.'],
['web.py','Una libreria de PYTHON.']]
constructor(){}
} |
#include "HttpRequest.h"
#include <String.h>
// Strings stored in program memoy (flash)
static const char LF[] PROGMEM = "\r\n";
static const char GET[] PROGMEM = "GET ";
static const char POST[] PROGMEM = "POST ";
static const char HTTP[] PROGMEM = " HTTP/1.0";
static const char FORM_URLENCODED[] PROGMEM = "Content-Type: Application/<API key>";
static const char QUESTION_MARK[] PROGMEM = "?";
static const char CONTENT_LENGTH[] PROGMEM = "Content-Length: ";
// Converts a program memory string to a __FlashStringHelper,
// such that the methods of the String class can recognize them.
#define FLASH_STRING(ptr) ((__FlashStringHelper*)(ptr))
static void strcls(char *str)
{
str[0] = 0;
}
HttpRequest::HttpRequest(const String &path)
{
_path = path;
}
void HttpRequest::addParameter(const String &key, const String &value)
{
// Add separator
if (_request.length() != 0)
_request += F("&");
// Add parameter
_request += key;
_request += F("=");
_request += value;
}
void HttpRequest::get(char *ret) const
{
if (!ret)
return;
// Clear string
strcls(ret);
// Get + path
strcat_P(ret, GET);
strcat(ret, _path.c_str());
// Query string
strcat_P(ret, QUESTION_MARK);
strcat(ret, _request.c_str());
strcat_P(ret, LF);
strcat_P(ret, LF);
}
String HttpRequest::get() const
{
String ret;
// Get + path
ret += FLASH_STRING(GET);
ret += _path;
// Query string
ret += FLASH_STRING(QUESTION_MARK);
ret += _request;
ret += FLASH_STRING(LF);
ret += FLASH_STRING(LF);
return ret;
}
void HttpRequest::post(char *ret) const
{
if (!ret)
return;
char contentLength[10];
snprintf(contentLength, 10, "%d", _request.length());
// Clear string
strcls(ret);
// Post field
strcat_P(ret, POST);
strcat(ret, _path.c_str());
strcat_P(ret, HTTP);
strcat_P(ret, LF);
// URL-encoded field
strcat_P(ret, FORM_URLENCODED);
strcat_P(ret, LF);
// Content-Length field
strcat_P(ret, CONTENT_LENGTH);
strcat(ret, contentLength);
strcat_P(ret, LF);
strcat_P(ret, LF);
// Query string
strcat(ret, _request.c_str());
}
String HttpRequest::post() const
{
String ret;
// Post field
ret += FLASH_STRING(POST);
ret += _path;
ret += FLASH_STRING(HTTP);
ret += FLASH_STRING(LF);
// URL-encoded field
ret += FLASH_STRING(FORM_URLENCODED);
ret += FLASH_STRING(LF);
// Content-Length field
ret += FLASH_STRING(CONTENT_LENGTH);
ret += _request.length();
ret += FLASH_STRING(LF);
ret += FLASH_STRING(LF);
// Query string
ret += _request;
return ret;
} |
import { connect } from 'react-redux';
import {
doCollectionEdit,
<API key>,
<API key>,
doPrepareEdit,
<API key>,
<API key>,
COLLECTIONS_CONSTS,
<API key>,
} from 'lbry-redux';
import { <API key> } from 'redux/selectors/blocked';
import { doChannelMute, doChannelUnmute } from 'redux/actions/blocked';
import { doSetActiveChannel, doSetIncognito, doOpenModal } from 'redux/actions/app';
import {
doCommentModBlock,
doCommentModUnBlock,
<API key>,
<API key>,
} from 'redux/actions/comments';
import {
<API key>,
<API key>,
<API key>,
} from 'redux/selectors/comments';
import { doToast } from 'redux/actions/notifications';
import { <API key> } from 'redux/selectors/content';
import { doChannelSubscribe, <API key> } from 'redux/actions/subscriptions';
import { <API key> } from 'redux/selectors/subscriptions';
import { <API key> } from 'redux/selectors/user';
import ClaimPreview from './view';
import fs from 'fs';
const select = (state, props) => {
const claim = <API key>(props.uri, false)(state);
const repostedClaim = claim && claim.reposted_claim;
const contentClaim = repostedClaim || claim;
const <API key> = contentClaim && contentClaim.signing_channel;
const contentPermanentUri = contentClaim && contentClaim.permanent_url;
const contentChannelUri = (<API key> && <API key>.permanent_url) || contentPermanentUri;
return {
claim,
repostedClaim,
contentClaim,
<API key>,
contentChannelUri,
claimIsMine: <API key>(props.uri)(state),
<API key>: <API key>(COLLECTIONS_CONSTS.WATCH_LATER_ID, contentPermanentUri)(state),
hasClaimInCustom: <API key>(COLLECTIONS_CONSTS.FAVORITES_ID, contentPermanentUri)(state),
channelIsMuted: <API key>(contentChannelUri)(state),
channelIsBlocked: <API key>(contentChannelUri)(state),
fileInfo: <API key>(props.uri)(state),
isSubscribed: <API key>(contentChannelUri, true)(state),
<API key>: <API key>(props.uri)(state),
isAdmin: <API key>(state),
claimInCollection: <API key>(props.collectionId, contentPermanentUri)(state),
isMyCollection: <API key>(props.collectionId)(state),
editedCollection: <API key>(props.collectionId)(state),
isAuthenticated: Boolean(<API key>(state)),
};
};
const perform = (dispatch) => ({
prepareEdit: (publishData, uri, fileInfo) => {
if (publishData.signing_channel) {
dispatch(doSetIncognito(false));
dispatch(doSetActiveChannel(publishData.signing_channel.claim_id));
} else {
dispatch(doSetIncognito(true));
}
dispatch(doPrepareEdit(publishData, uri, fileInfo, fs));
},
doToast: (props) => dispatch(doToast(props)),
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
doChannelMute: (channelUri) => dispatch(doChannelMute(channelUri)),
doChannelUnmute: (channelUri) => dispatch(doChannelUnmute(channelUri)),
doCommentModBlock: (channelUri) => dispatch(doCommentModBlock(channelUri)),
doCommentModUnBlock: (channelUri) => dispatch(doCommentModUnBlock(channelUri)),
<API key>: (commenterUri, blockerId) =>
dispatch(<API key>(commenterUri, blockerId)),
<API key>: (commenterUri, blockerId) =>
dispatch(<API key>(commenterUri, blockerId)),
doChannelSubscribe: (subscription) => dispatch(doChannelSubscribe(subscription)),
<API key>: (subscription) => dispatch(<API key>(subscription)),
doCollectionEdit: (collection, props) => dispatch(doCollectionEdit(collection, props)),
});
export default connect(select, perform)(ClaimPreview); |
{% extends 'layouts/application.html' %}
{% block content %}
<div class="container">
<h1 class="page-header">Edit post</h1>
<form action="/posts/update/{{post.id}}" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="title" placeholder="Title" value="{{post.title}}">
</div>
<div class="form-group">
<textarea type="text" rows="10" class="form-control" name="body" placeholder="Post body">{{post.body}}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
{% endblock %} |
'use strict'
var assert = require('assert')
describe('#parameter', function () {
var paramCtor = require('../../dist/annotation/annotations/parameter').default
var param = paramCtor(require('./envMock'))
it('should return an object', function () {
assert.deepEqual(param.parse('{type} $hyphenated-name [default] - description'), { type: 'type', name: 'hyphenated-name', default: 'default', description: 'description' })
assert.deepEqual(param.parse('{type} $name [default] - description [with brackets]'), { type: 'type', name: 'name', default: 'default', description: 'description [with brackets]' })
assert.deepEqual(param.parse('{List} $list - list to check'), { type: 'List', name: 'list', description: 'list to check' })
})
it('should parse all chars in type', function () {
assert.deepEqual(param.parse('{*} $name - description'), { type: '*', name: 'name', description: 'description' })
assert.deepEqual(param.parse('{type|other} $name - description'), { type: 'type|other', name: 'name', description: 'description' })
})
it('should work for multiline description', function () {
assert.deepEqual(param.parse('{type} $hyphenated-name [default] - description\nmore\nthan\none\nline'), { type: 'type', name: 'hyphenated-name', default: 'default', description: 'description\nmore\nthan\none\nline' })
})
it('should work without the $', function () {
assert.deepEqual(param.parse('{type} hyphenated-name [default] - description\nmore\nthan\none\nline'), { type: 'type', name: 'hyphenated-name', default: 'default', description: 'description\nmore\nthan\none\nline' })
})
it('should work without a type', function () {
assert.deepEqual(param.parse('hyphenated-name [default] - description\nmore\nthan\none\nline'), { name: 'hyphenated-name', default: 'default', description: 'description\nmore\nthan\none\nline' })
})
it('should warn when a name is missing', function (done) {
param = paramCtor({
logger: {
warn: function (msg) {
assert.equal(msg, '@parameter must at least have a name. Location: FileID:1:2')
done()
}
}
})
assert.deepEqual(param.parse('{type} [default] - description\nmore\nthan\none\nline', { commentRange: { start: 1, end: 2 } }, 'FileID'), undefined)
})
it('should work without a description', function () {
assert.deepEqual(param.parse('{type} name'), { type: 'type', name: 'name' })
})
}) |
# JS Burner - A Framework for JavaScript
An amd-based framework focuses on class structure and ui components for javascript.
# Contribute
Framework is very fresh and it is under development now. It needs many arrangements and optimizations or new ideas make it better. Also documentation page may need language fixes.
# Brief Information
This framework does not use package managers like npm. Since it's designed for full of browser usage. That's why it uses AMD (Asyncronous Module Definition). Also this framework has its own class stucture to make writing code closer to object-oriented class logic, and it supports more than javascript's native class structure. To tell usage mentality of framework, this can be said that component classes and methods are like a little Java programming and a little jQuery.
# Install
Requirements
- [RequireJS](http://requirejs.org/) For AMD module management.
- [Font Awesome](http://fontawesome.io/) Default icon set used in components.
Installation
Clone repository into wherever you want in your project.
sh
git clone git@github.com:alpertuna/burner.git
Or you can download and extract it.
sh
tar -xf burner-xxx.tar.gz
Then embed stylesheet to your project.
html
<link rel="stylesheet" href="path/to/burner.min.css" />
Add JS Burner Framework bundle script, between RequireJS script and your main script.
html
<script type="text/javscript" src="path/to/require.js"></script>
<script type="text/javscript" src="path/to/burner.min.js"></script>
<script type="text/javscript" src="path/to/your_main.js"></script>
For debugging, you may use non-minified files.
# Usage
To learn how to use it, you should read [documentation](https://alpertuna.github.io/burner). |
<style>
.user-info {
position: absolute;
right: 110px;
top: 20px;
}
</style>
<div ng-if="existUser">
<div class="user-info">Hello, {{userName}}</div>
<md-fab-speed-dial md-direction="down" md-open="false" class="md-scale md-fab-top-right" ng-class="{ 'md-hover-full': false }">
<md-fab-trigger>
<md-button aria-label="menu" class="md-fab md-warn">
<md-tooltip md-direction="top" md-visible="tooltipVisible">Menu</md-tooltip>
<md-icon md-svg-src="/lan_crud/public/img/icons/menu.svg" aria-label="menu"></md-icon>
</md-button>
</md-fab-trigger>
<md-fab-actions>
<md-button aria-label="Quit" class="md-fab md-raised md-mini" ng-click="exitAndDestroy($event)">
<md-tooltip md-direction="down" md-visible="tooltipVisible" md-autohide="false">
Exit & Destroy
</md-tooltip>
<md-icon aria-label="exit">clear</md-icon>
</md-button>
</md-fab-actions>
</md-fab-speed-dial>
</div> |
package com.darksci.pardot.api.rest;
import com.darksci.pardot.api.config.Configuration;
import com.darksci.pardot.api.request.Request;
/**
* Interface for making HTTP calls.
*/
public interface RestClient {
/**
* Initializes the RestClient implementation.
* Any setup or resource allocation should happen here.
* @param configuration Pardot Api Configuration.
*/
void init(final Configuration configuration);
/**
* Make a request against the Pardot API.
* @param request The request to submit.
* @return The response, in UTF-8 String format.
* @throws RestException When something goes wrong in an underlying implementation.
*/
RestResponse submitRequest(final Request request) throws RestException;
/**
* Called to release any internally held resources.
*/
void close();
} |
import { moduleForComponent, test } from 'ember-qunit';
import hbs from '<API key>';
moduleForComponent('ember-a-camera', 'Integration | Component | ember a camera', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{ember-a-camera}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#ember-a-camera}}
template block text
{{/ember-a-camera}}
`);
assert.equal(this.$().text().trim(), 'template block text');
}); |
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
phone_number = models.CharField(max_length=15) |
package org.heigit.ors.v2.services.isochrones;
import org.heigit.ors.services.isochrones.<API key>;
import org.heigit.ors.v2.services.common.EndPointAnnotation;
import org.heigit.ors.v2.services.common.ServiceTest;
import org.heigit.ors.v2.services.common.VersionAnnotation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.lessThan;
@EndPointAnnotation(name = "isochrones")
@VersionAnnotation(version = "v2")
public class ResultTest extends ServiceTest {
public ResultTest() {
// Locations
addParameter("preference", "fastest");
addParameter("cyclingProfile", "cycling-regular");
addParameter("carProfile", "driving-car");
JSONArray firstLocation = new JSONArray();
firstLocation.put(8.684177);
firstLocation.put(49.423034);
JSONArray secondLocation = new JSONArray();
secondLocation.put(8.684177);
secondLocation.put(49.410034);
JSONArray unknownLocation = new JSONArray();
unknownLocation.put(-18.215332);
unknownLocation.put(45.79817);
JSONArray locations_1_unknown = new JSONArray();
locations_1_unknown.put(unknownLocation);
JSONArray locations_1 = new JSONArray();
locations_1.put(firstLocation);
JSONArray locations_2 = new JSONArray();
locations_2.put(firstLocation);
locations_2.put(secondLocation);
JSONArray ranges_2 = new JSONArray();
ranges_2.put(1800);
ranges_2.put(1800);
JSONArray ranges_400 = new JSONArray();
ranges_400.put(400);
JSONArray ranges_1800 = new JSONArray();
ranges_1800.put(1800);
JSONArray ranges_2000 = new JSONArray();
ranges_2000.put(2000);
Integer interval_100 = new Integer(100);
Integer interval_200 = new Integer(200);
Integer interval_400 = new Integer(400);
Integer interval_900 = new Integer(900);
JSONArray <API key> = new JSONArray();
<API key>.put("area");
<API key>.put("reachfactor");
JSONArray <API key> = new JSONArray();
<API key>.put("areaaaa");
<API key>.put("reachfactorrrr");
addParameter("locations_1", locations_1);
addParameter("locations_2", locations_2);
addParameter("locations_1_unknown", locations_1_unknown);
addParameter("ranges_2", ranges_2);
addParameter("ranges_400", ranges_400);
addParameter("ranges_1800", ranges_1800);
addParameter("ranges_2000", ranges_2000);
addParameter("interval_100", interval_100);
addParameter("interval_200", interval_200);
addParameter("interval_200", interval_400);
addParameter("interval_900", interval_900);
addParameter("<API key>", <API key>);
addParameter("<API key>", <API key>);
}
@Test
public void testPolygon() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].geometry.coordinates[0].size()", is(49))
.body("features[0].properties.center.size()", is(2))
.body("bbox", hasItems(8.663323f, 49.40837f, 8.700336f, 49.439884f))
.body("features[0].type", is("Feature"))
.body("features[0].geometry.type", is("Polygon"))
.body("features[0].properties.group_index", is(0))
.body("features[0].properties.value", is(400f))
.body("metadata.containsKey('system_message')", is(true))
.statusCode(200);
}
@Test
public void testGroupIndices() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_2"));
body.put("range", getParameter("ranges_400"));
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features.size()", is(2))
.body("features[0].properties.group_index", is(0))
.body("features[1].properties.group_index", is(1))
.statusCode(200);
}
@Test
public void testUnknownLocation() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1_unknown"));
body.put("range", getParameter("ranges_400"));
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.statusCode(500)
.body("error.code", is(<API key>.UNKNOWN));
}
@Test
public void testBoundingBox() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("bbox[0]", is(8.663323f))
.body("bbox[1]", is(49.40837f))
.body("bbox[2]", is(8.700336f))
.body("bbox[3]", is(49.439884f))
.statusCode(200);
}
@Test
public void testLocationType() {
JSONArray locations = new JSONArray();
JSONArray loc1 = new JSONArray();
loc1.put(8.681495);
loc1.put(49.41461);
locations.put(loc1);
JSONArray ranges = new JSONArray();
ranges.put(200);
JSONObject body = new JSONObject();
body.put("locations", locations);
body.put("range", ranges);
body.put("attributes", getParameter("<API key>"));
body.put("range_type", "time");
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", "driving-hgv")
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then().log().ifValidationFails()
.body("features[0].properties.area", is(1699492.0f))
.statusCode(200);
body.put("location_type", "destination");
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", "driving-hgv")
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then().log().ifValidationFails()
.body("features[0].properties.area", is(1561223.9f))
.statusCode(200);
}
@Test
public void <API key>() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
body.put("attributes", getParameter("<API key>"));
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].properties.area", is(both(greaterThan(6590000f)).and(lessThan(6600000f))))
.body("features[0].properties.reachfactor", is(0.7561f))
.statusCode(200);
}
@Test
public void <API key>() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
body.put("attributes", getParameter("<API key>"));
body.put("area_units", getParameter("m"));
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].properties.area", is(both(greaterThan(6590000f)).and(lessThan(6600000f))))
.body("features[0].properties.reachfactor", is(0.7561f))
.statusCode(200);
}
@Test
public void <API key>() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
body.put("attributes", getParameter("<API key>"));
body.put("area_units", "km");
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].properties.area", is(both(greaterThan(6.59f)).and(lessThan(6.60f))))
.body("features[0].properties.reachfactor", is(0.7561f))
.statusCode(200);
}
@Test
public void <API key>() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
body.put("area_units", "km");
body.put("units", "m");
body.put("range_type", "time");
body.put("attributes", getParameter("<API key>"));
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].properties.area", is(both(greaterThan(6.59f)).and(lessThan(6.60f))))
.statusCode(200);
}
@Test
public void <API key>() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
body.put("attributes", getParameter("<API key>"));
body.put("area_units", "mi");
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].properties.area", is(both(greaterThan(2.53f)).and(lessThan(2.55f))))
.body("features[0].properties.reachfactor", is(0.7561f))
.statusCode(200);
}
@Test
public void testIntersections() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_2"));
body.put("range", getParameter("ranges_400"));
body.put("attributes", getParameter("<API key>"));
body.put("intersections", "true");
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features.size()", is(3))
.body("features[0].type", is("Feature"))
.body("features[0].geometry.type", is("Polygon"))
.body("features[1].type", is("Feature"))
.body("features[1].geometry.type", is("Polygon"))
.body("features[2].type", is("Feature"))
.body("features[2].geometry.type", is("Polygon"))
//.body("features[2].geometry.coordinates[0].size()", is(26))
.body("features[2].geometry.coordinates[0].size()", is(38))
.body("features[2].properties.contours.size()", is(2))
.body("features[2].properties.containsKey('area')", is(true))
//.body("features[2].properties.area", is(5824280.5f))
.body("features[0].properties.area", is(both(greaterThan(6590000f)).and(lessThan(6600000f))))
.body("features[2].properties.contours[0][0]", is(0))
.body("features[2].properties.contours[0][1]", is(0))
.body("features[2].properties.contours[1][0]", is(1))
.body("features[2].properties.contours[1][1]", is(0))
.statusCode(200);
}
@Test
public void testSmoothingFactor() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_2000"));
body.put("smoothing", "10");
body.put("range_type", "distance");
// Updated in the GH 0.12 update from size = 52 as there is a difference in the order that edges are returned and
// so neighbourhood search results in slightly different results
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].geometry.coordinates[0].size", is(51))
.statusCode(200);
body.put("smoothing", "100");
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.body("any { it.key == 'type' }", is(true))
.body("any { it.key == 'features' }", is(true))
.body("features[0].geometry.coordinates[0].size", is(19))
.statusCode(200);
}
@Test
public void <API key>() {
JSONObject body = new JSONObject();
body.put("locations", getParameter("locations_1"));
body.put("range", getParameter("ranges_400"));
body.put("id", "request123");
given()
.header("Accept", "application/geo+json")
.header("Content-Type", "application/json")
.pathParam("profile", getParameter("cyclingProfile"))
.body(body.toString())
.when()
.post(getEndPointPath() + "/{profile}/geojson")
.then()
.assertThat()
.body("any {it.key == 'metadata'}", is(true))
.body("metadata.containsKey('id')", is(true))
.body("metadata.id", is("request123"))
.body("metadata.containsKey('attribution')", is(true))
.body("metadata.service", is("isochrones"))
.body("metadata.containsKey('timestamp')", is(true))
.body("metadata.containsKey('query')", is(true))
.body("metadata.query.id", is("request123"))
.body("metadata.query.containsKey('locations')", is(true))
.body("metadata.query.locations.size()", is(1))
.body("metadata.query.locations[0][0]", is(8.684177f))
.body("metadata.query.locations[0][1]", is(49.423034f))
.body("metadata.query.containsKey('range')", is(true))
.body("metadata.query.range.size()", is(1))
.body("metadata.query.range[0]", is(400.0f))
.body("metadata.query.profile", is("cycling-regular"))
.body("metadata.query.id", is("request123"))
.body("metadata.engine.containsKey('version')", is(true))
.body("metadata.engine.containsKey('build_date')", is(true))
.body("metadata.engine.containsKey('graph_date')", is(true))
.body("metadata.containsKey('system_message')", is(true))
.statusCode(200);
}
} |
using GeckoMapTester;
using System;
using System.Collections.Generic;
using System.Text;
namespace GeckoDotNet
{
public enum AddressType
{
Rw,
Ro,
Ex,
Hardware,
Unknown
}
public class AddressRange
{
private AddressType PDesc;
private Byte PId;
private UInt32 PLow;
private UInt32 PHigh;
public AddressType description { get { return PDesc; } }
public Byte id { get { return PId; } }
public UInt32 low { get { return PLow; } }
public UInt32 high { get { return PHigh; } }
public AddressRange(AddressType desc, Byte id, UInt32 low, UInt32 high)
{
this.PId = id;
this.PDesc = desc;
this.PLow = low;
this.PHigh = high;
}
public AddressRange(AddressType desc, UInt32 low, UInt32 high) :
this(desc, (Byte)(low >> 24), low, high)
{ }
}
public static class ValidMemory
{
public static bool addressDebug = false;
public static readonly AddressRange[] ValidAreas = new AddressRange[] {
new AddressRange(AddressType.Ex, 0x01000000,0x01800000),
new AddressRange(AddressType.Ex, 0x0e300000,0x10000000),
new AddressRange(AddressType.Rw, 0x10000000,0x50000000),
new AddressRange(AddressType.Ro, 0xe0000000,0xe4000000),
new AddressRange(AddressType.Ro, 0xe8000000,0xea000000),
new AddressRange(AddressType.Ro, 0xf4000000,0xf6000000),
new AddressRange(AddressType.Ro, 0xf6000000,0xf6800000),
new AddressRange(AddressType.Ro, 0xf8000000,0xfb000000),
new AddressRange(AddressType.Ro, 0xfb000000,0xfb800000),
new AddressRange(AddressType.Rw, 0xfffe0000,0xffffffff)
};
public static AddressType rangeCheck(UInt32 address)
{
int id = rangeCheckId(address);
if (id == -1)
return AddressType.Unknown;
else
return ValidAreas[id].description;
}
public static int rangeCheckId(UInt32 address)
{
for (int i = 0; i < ValidAreas.Length; i++)
{
AddressRange range = ValidAreas[i];
if (address >= range.low && address < range.high)
return i;
}
return -1;
}
public static bool validAddress(UInt32 address, bool debug)
{
if (debug)
return true;
return (rangeCheckId(address) >= 0);
}
public static bool validAddress(UInt32 address)
{
return validAddress(address, addressDebug);
}
public static bool validRange(UInt32 low, UInt32 high, bool debug)
{
if (debug)
return true;
return (rangeCheckId(low) == rangeCheckId(high - 1));
}
public static bool validRange(UInt32 low, UInt32 high)
{
return validRange(low, high, addressDebug);
}
public static void setDataUpper(TCPGecko upper)
{
UInt32 mem;
switch (upper.OsVersionRequest())
{
case 400:
case 410:
mem = upper.peek_kern(0xffe8619c);
break;
case 500:
case 510:
return;
// TODO: This doesn't work for some reason - crashes on connection?
//mem = upper.peek_kern(0xffe8591c);
//break;
default:
return;
}
UInt32 tbl = upper.peek_kern(mem + 4);
UInt32 lst = upper.peek_kern(tbl + 20);
UInt32 init_start = upper.peek_kern(lst + 0 + 0x00);
UInt32 init_len = upper.peek_kern(lst + 4 + 0x00);
UInt32 code_start = upper.peek_kern(lst + 0 + 0x10);
UInt32 code_len = upper.peek_kern(lst + 4 + 0x10);
UInt32 data_start = upper.peek_kern(lst + 0 + 0x20);
UInt32 data_len = upper.peek_kern(lst + 4 + 0x20);
ValidAreas[0] = new AddressRange(AddressType.Ex, init_start, init_start + init_len);
ValidAreas[1] = new AddressRange(AddressType.Ex, code_start, code_start + code_len);
ValidAreas[2] = new AddressRange(AddressType.Rw, data_start, data_start + data_len);
}
}
} |
#ifndef __Events_H
#define __Events_H
/* MODULE Events */
#include "PE_Types.h"
#include "PE_Error.h"
#include "PE_Const.h"
#include "IO_Map.h"
#include "Led.h"
#include "SPI.h"
#include "USB.h"
#include "CSN.h"
#include "RfmIrq.h"
#include "TI1.h"
#include "typedef.h"
extern volatile bool RFM_IRQ;
void SPI_OnRxChar(void);
void TI1_OnInterrupt(void);
void RfmIrq_OnInterrupt(void);
/* END Events */
#endif /* __Events_H*/ |
import Vue from 'vue'
import {ruuvitagApi, tellstickApi, hueApi, FETCH_INTERVAL} from './config.js'
require('./index.css')
const postHeaders = {'Content-Type': 'application/json', '<API key>':'*'}
const tagData = {
template:'<div class="tag">\
<div class="tag-name">{{tag.name}}</div>\
<div class="tag-temperature"><i class="fa fa-thermometer-half fa-lg green icon"></i>{{tag.data.temperature}} °C</div>\
<div class="tag-humidity"><i class="fa fa-tint fa-lg blue icon"></i>{{tag.data.humidity}}%</div>\
<div class="tag-pressure"><i class="fa fa-tachometer fa-lg green icon"></i>{{tag.data.pressure}} hPa</div>\
</div>',
props: ['tag'],
data: function() {
return {}
}
}
const tdSensorData = {
template:'<div class="sensor">\
<div class="sensor-name">{{sensor.name}}</div>\
<div class="sensor-temperature"><i class="fa fa-thermometer-half fa-lg green icon"></i>{{sensor.temperature}} °C</div>\
<div class="sensor-humidity" v-if="sensor.humidity"><i class="fa fa-tint fa-lg blue icon"></i>{{sensor.humidity}}%</div>\
</div>',
props: ['sensor'],
data: function() {
return {}
}
}
const toggleSwitch = (url, deviceIds) => {
const postBody = JSON.stringify(deviceIds)
return fetch(url, {method: 'POST', mode: 'cors', body: postBody, headers: postHeaders})
.then(response => response.json())
.then(data => app.tellstickSwitches = data)
}
const tdSwitchData = {
template:'<div v-if="device.switchedOn" v-on:click="turnOff(device.id)" class="switch clickable">\
<div class="switch-status">\
<i class="fa fa-power-off fa-lg green icon clickable"></i>\
</div>\
<div class="switch-name">{{device.name}}</div>\
</div>\
<div v-else v-on:click="turnOn(device.id)" class="switch clickable">\
<div class="switch-status clickable">\
<i class="fa fa-power-off fa-lg red icon"></i>\
</div>\
<div class="switch-name">{{device.name}}</div>\
</div>',
props: ['device'],
data: function() {
return {}
},
methods: {
turnOn: function(deviceId) {
toggleSwitch(tellstickApi.urls.turnOnSwitch, [deviceId])
},
turnOff: function(deviceId) {
toggleSwitch(tellstickApi.urls.turnOffSwitch, [deviceId])
}
}
}
const hueSwitchData = {
template:'<div v-if="group.state.attributes.any_on" class="switch clickable" v-on:click="turnOff(group)">\
<div class="switch-status">\
<i class="fa fa-power-off fa-lg green icon"></i>\
</div>\
<div class="switch-name">{{group.attributes.attributes.name}}</div>\
</div>\
<div v-else class="switch clickable" v-on:click="turnOn(group)">\
<div class="switch-status">\
<i class="fa fa-power-off fa-lg red icon"></i>\
</div>\
<div class="switch-name">{{group.attributes.attributes.name}}</div>\
</div>',
// template: '<h1 class="switch-name">yeaaah</h1>',
props: ['group'],
data: function() {
console.log('Data');
return {}
},
methods: {
turnOn: function(group) {
const postBody = JSON.stringify({"lights": group.attributes.attributes.lights});
fetch(hueApi.urls.turnOnSwitch, {method: 'POST', mode: 'cors', body: postBody, headers: postHeaders })
.then(response => response.json())
.then(data => app.hueGroups = data)
},
turnOff: function(group) {
const postBody = JSON.stringify({"lights": group.attributes.attributes.lights});
fetch(hueApi.urls.turnOffSwitch, {method: 'POST', mode: 'cors', body: postBody, headers: postHeaders })
.then(response => response.json())
.then(data => app.hueGroups = data)
}
}
}
const app = new Vue({
el: '#app',
data: {
ruuvitags: ruuvitagApi.enabled,
tellstickSensors: tellstickApi.enabled,
tellstickSwitches: tellstickApi.enabled,
hasSensors: ruuvitagApi.enabled,
hasSwitches: false,
hasSwitchGroups: false,
hueGroups: hueApi.enabled,
hasHueGroups: false
},
components: {
'ruuvitag': tagData,
'tdsensor': tdSensorData,
'tdswitch': tdSwitchData,
'hueswitch': hueSwitchData
}
})
function fetchRuuvitagData() {
if (ruuvitagApi.enabled) {
fetch(ruuvitagApi.urls.ruuvitags)
.then(response => response.json())
.then(data => app.ruuvitags = data)
}
}
function fetchTellstickData() {
if (tellstickApi.enabled) {
fetch(tellstickApi.urls.tellstickSensors)
.then(response => response.json())
.then(data => {
app.tellstickSensors = data
if (data.length > 0) {
app.hasSensors = true
}
})
fetch(tellstickApi.urls.tellstickSwitches)
.then(response => response.json())
.then(data => {
app.tellstickSwitches = data
if (data.devices.length > 0) {
app.hasSwitches = true
}
if (data.groups.length > 0) {
app.hasSwitchGroups = true
}
})
}
}
function fetchHueData() {
if (hueApi.enabled) {
console.log('hueApi enabled!');
// app.hueSwitches = 'Jee'
fetch(hueApi.urls.init, {headers: postHeaders}).then(initdata => {
fetch(hueApi.urls.hueGroups)
.then(response => response.json())
.then(data => {
app.hueGroups = data
console.log("GROUPS:", data);
if (data.length > 0) {
console.log('Yep, got hue groups!');
app.hasHueGroups = true;
}
})
})
}
}
function fetchData() {
fetchRuuvitagData()
fetchTellstickData()
fetchHueData()
}
fetchData()
setInterval(fetchData, FETCH_INTERVAL) |
package io.mkremins.whydah.parser;
import io.mkremins.whydah.util.Reader;
public final class Morpher implements Reader<Token> {
private final Reader<Token> tokens;
private boolean ignoreNextNewline;
public Morpher(final Reader<Token> tokens) {
this.tokens = tokens;
// ignore newlines that appear before any actual code is found
ignoreNextNewline = true;
}
@Override
public Token read() {
while (true) {
final Token token = tokens.read();
switch (token.getType()) {
case COMMENT:
case WHITESPACE:
// ignore semantically meaningless tokens
continue;
case NEWLINE:
if (ignoreNextNewline) {
continue;
}
// treat multiple newlines in a row as a single newline
ignoreNextNewline = true;
break;
default:
ignoreNextNewline = false;
break;
}
return token;
}
}
} |
postSchemaObject = {
_id: {
type: String,
optional: true,
autoform: {
omit: true
}
},
createdAt: {
type: Date,
optional: true,
autoform: {
omit: true
}
},
postedAt: {
type: Date,
optional: true,
autoform: {
group: 'admin',
type: "<API key>"
}
},
url: {
type: String,
optional: true,
autoform: {
editable: true,
type: "bootstrap-url"
}
},
title: {
type: String,
optional: false,
autoform: {
editable: true
}
},
body: {
type: String,
optional: true,
autoform: {
editable: true,
rows: 5
}
},
htmlBody: {
type: String,
optional: true,
autoform: {
omit: true
}
},
viewCount: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
commentCount: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
commenters: {
type: [String],
optional: true,
autoform: {
omit: true
}
},
lastCommentedAt: {
type: Date,
optional: true,
autoform: {
omit: true
}
},
clickCount: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
baseScore: {
type: Number,
decimal: true,
optional: true,
autoform: {
omit: true
}
},
upvotes: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
upvoters: {
type: [String], // XXX
optional: true,
autoform: {
omit: true
}
},
downvotes: {
type: Number,
optional: true,
autoform: {
omit: true
}
},
downvoters: {
type: [String], // XXX
optional: true,
autoform: {
omit: true
}
},
attactments:{
type: [String],
optional: true
},
score: {
type: Number,
decimal: true,
optional: true,
autoform: {
omit: true
}
},
version:{
type: String,
optional: true
},
status: {
type: Number,
optional: true,
autoValue: function () {
// only provide a default value
// 1) this is an insert operation
// 2) status field is not set in the document being inserted
var user = Meteor.users.findOne(this.userId);
if (this.isInsert && !this.isSet)
return <API key>(user);
},
autoform: {
noselect: true,
options: postStatuses,
group: 'admin'
}
},
sticky: {
type: Boolean,
optional: true,
defaultValue: false,
autoform: {
group: 'admin',
leftLabel: "Sticky"
}
},
inactive: {
type: Boolean,
optional: true,
autoform: {
omit: true
}
},
author: {
type: String,
optional: true,
autoform: {
omit: true
}
},
userId: {
type: String, // XXX
optional: true,
autoform: {
group: 'admin',
options: function () {
return Meteor.users.find().map(function (user) {
return {
value: user._id,
label: getDisplayName(user)
}
});
}
}
},
parseId:{
type: String,
optional: true
}
};
// add any extra properties to postSchemaObject (provided by packages for example)
_.each(addToPostSchema, function(item){
postSchemaObject[item.propertyName] = item.propertySchema;
});
Posts = new Meteor.Collection("posts");
postSchema = new SimpleSchema(postSchemaObject);
Posts.attachSchema(postSchema);
getPostProperties = function (post) {
var postAuthor = Meteor.users.findOne(post.userId);
var p = {
postAuthorName : getDisplayName(postAuthor),
postTitle : cleanUp(post.title),
profileUrl: <API key>(post.userId),
postUrl: getPostPageUrl(post),
thumbnailUrl: post.thumbnailUrl,
linkUrl: !!post.url ? getOutgoingUrl(post.url) : getPostPageUrl(post._id)
};
if(post.url)
p.url = post.url;
if(post.htmlBody)
p.htmlBody = post.htmlBody;
return p;
};
// default status for new posts
<API key> = function (user) {
var hasAdminRights = typeof user === 'undefined' ? false : isAdmin(user);
if (hasAdminRights || !getSetting('<API key>', false)) {
// if user is admin, or else post approval is not required
return STATUS_APPROVED
} else {
// else
return STATUS_PENDING
}
}
getPostPageUrl = function(post){
return getSiteUrl()+'posts/'+post._id;
};
getPostEditUrl = function(id){
return getSiteUrl()+'posts/'+id+'/edit';
};
// for a given post, return its link if it has one, or else its post page URL
getPostLink = function (post) {
return !!post.url ? getOutgoingUrl(post.url) : getPostPageUrl(post);
};
// we need the current user so we know who to upvote the existing post as
<API key> = function (url, currentUser) {
// check that there are no previous posts with the same link in the past 6 months
var sixMonthsAgo = moment().subtract(6, 'months').toDate();
var postWithSameLink = Posts.findOne({url: url, postedAt: {$gte: sixMonthsAgo}});
if(typeof postWithSameLink !== 'undefined'){
upvoteItem(Posts, postWithSameLink, currentUser);
// note: error.details returns undefined on the client, so add post ID to reason
throw new Meteor.Error('603', i18n.t('<API key>') + '|' + postWithSameLink._id, postWithSameLink._id);
}
}
// when on a post page, return the current post
currentPost = function () {
return Posts.findOne(Router.current().data()._id);
}
Posts.before.insert(function (userId, doc) {
if(!!doc.body)
doc.htmlBody = sanitize(marked(doc.body));
});
Posts.before.update(function (userId, doc, fieldNames, modifier, options) {
// if body is being modified, update htmlBody too
if (Meteor.isServer && modifier.$set && modifier.$set.body) {
modifier.$set.htmlBody = sanitize(marked(modifier.$set.body));
}
});
<API key>.push(function (post) {
var userId = post.userId,
postAuthor = Meteor.users.findOne(userId);
// increment posts count
Meteor.users.update({_id: userId}, {$inc: {postCount: 1}});
upvoteItem(Posts, post, postAuthor);
return post;
});
submitPost = function (post) {
var userId = post.userId, // at this stage, a userId is expected
user = Meteor.users.findOne(userId);
// check that a title was provided
if(!post.title)
throw new Meteor.Error(602, i18n.t('<API key>'));
// check that there are no posts with the same URL
if(!!post.url)
<API key>(post.url, user);
defaultProperties = {
createdAt: new Date(),
author: getDisplayNameById(userId),
upvotes: 0,
downvotes: 0,
commentCount: 0,
clickCount: 0,
viewCount: 0,
baseScore: 0,
score: 0,
inactive: false,
sticky: false,
status: <API key>()
};
post = _.extend(defaultProperties, post);
// if post is approved but doesn't have a postedAt date, give it a default date
// note: pending posts get their postedAt date only once theyre approved
if (post.status == STATUS_APPROVED && !post.postedAt)
post.postedAt = new Date();
// clean up post title
post.title = cleanUp(post.title);
// run all post submit server callbacks on post object successively
post = <API key>.reduce(function(result, currentFunction) {
return currentFunction(result);
}, post);
post._id = Posts.insert(post);
if (Meteor.isServer) {
Meteor.defer(function () { // use defer to avoid holding up client
// run all post submit server callbacks on post object successively
post = <API key>.reduce(function(result, currentFunction) {
return currentFunction(result);
}, post);
});
}
return post;
}
postViews = [];
Meteor.methods({
submitPost: function(post){
// required properties:
// title
// optional properties
// URL
// body
// categories
// thumbnailUrl
// NOTE: the current user and the post author user might be two different users!
var user = Meteor.user(),
hasAdminRights = isAdmin(user);
// check that user can post
if (!user || !can.post(user))
throw new Meteor.Error(601, i18n.t('<API key>'));
if(!hasAdminRights){
var timeSinceLastPost=timeSinceLast(user, Posts),
<API key>=<API key>(user, Posts),
postInterval = Math.abs(parseInt(getSetting('postInterval', 30))),
maxPostsPer24Hours = Math.abs(parseInt(getSetting('maxPostsPerDay', 30)));
// check that user waits more than X seconds between posts
if(timeSinceLastPost < postInterval)
throw new Meteor.Error(604, i18n.t('please_wait')+(<API key>)+i18n.t('<API key>'));
// check that the user doesn't post more than Y posts per day
if(<API key> > maxPostsPer24Hours)
throw new Meteor.Error(605, i18n.t('<API key>')+maxPostsPer24Hours+i18n.t('posts_per_day'));
}
// admin-only properties
// status
// postedAt
// userId
// sticky (default to false)
// if user is not admin, go over each schema property and throw an error if it's not editable
if (!hasAdminRights) {
_.keys(post).forEach(function (propertyName) {
var property = postSchemaObject[propertyName];
if (!property || !property.autoform || !property.autoform.editable) {
console.log('//' + i18n.t('<API key>') + ": " + propertyName);
throw new Meteor.Error("disallowed_property", i18n.t('<API key>') + ": " + propertyName);
}
});
}
// if no post status has been set, set it now
if (!post.status) {
post.status = <API key>(user);
}
// if no userId has been set, default to current user id
if (!post.userId) {
post.userId = user._id
}
return submitPost(post);
},
editPost: function (post, modifier, postId) {
var user = Meteor.user(),
hasAdminRights = isAdmin(user);
// check that user can edit
if (!user || !can.edit(user, Posts.findOne(postId)))
throw new Meteor.Error(601, i18n.t('<API key>'));
// if user is not admin, go over each schema property and throw an error if it's not editable
if (!hasAdminRights) {
// loop over each operation ($set, $unset, etc.)
_.each(modifier, function (operation) {
// loop over each property being operated on
_.keys(operation).forEach(function (propertyName) {
var property = postSchemaObject[propertyName];
if (!property || !property.autoform || !property.autoform.editable) {
console.log('//' + i18n.t('<API key>') + ": " + propertyName);
throw new Meteor.Error("disallowed_property", i18n.t('<API key>') + ": " + propertyName);
}
});
});
}
// run all post submit server callbacks on modifier successively
modifier = <API key>.reduce(function(result, currentFunction) {
return currentFunction(result);
}, modifier);
Posts.update(postId, modifier);
// run all post submit server callbacks on modifier object successively
modifier = <API key>.reduce(function(result, currentFunction) {
return currentFunction(result);
}, modifier);
return Posts.findOne(postId);
},
setPostedAt: function(post, customPostedAt){
var postedAt = new Date(); // default to current date and time
if(isAdmin(Meteor.user()) && typeof customPostedAt !== 'undefined') // if user is admin and a custom datetime has been set
postedAt = customPostedAt;
Posts.update(post._id, {$set: {postedAt: postedAt}});
},
approvePost: function(post){
if(isAdmin(Meteor.user())){
var set = {status: 2};
// unless post is already scheduled and has a postedAt date, set its postedAt date to now
if (!post.postedAt)
set.postedAt = new Date();
var result = Posts.update(post._id, {$set: set}, {validate: false});
if (Meteor.isServer) {
Meteor.defer(function () { // use defer to avoid holding up client
// run all post submit server callbacks on post object successively
post = <API key>.reduce(function(result, currentFunction) {
return currentFunction(result);
}, post);
});
}
}else{
flashMessage('You need to be an admin to do that.', "error");
}
},
unapprovePost: function(post){
if(isAdmin(Meteor.user())){
Posts.update(post._id, {$set: {status: 1}});
}else{
flashMessage('You need to be an admin to do that.', "error");
}
},
increasePostViews: function(postId, sessionId){
this.unblock();
// only let users increment a post's view counter once per session
var view = {_id: postId, userId: this.userId, sessionId: sessionId};
if(_.where(postViews, view).length == 0){
postViews.push(view);
Posts.update(postId, { $inc: { viewCount: 1 }});
}
},
deletePostById: function(postId) {
// remove post comments
// if(!this.isSimulation) {
// Comments.remove({post: postId});
// NOTE: actually, keep comments after all
var post = Posts.findOne({_id: postId});
if(!Meteor.userId() || !can.editById(Meteor.userId(), post)) throw new Meteor.Error(606, 'You need permission to edit or delete a post');
// decrement post count
Meteor.users.update({_id: post.userId}, {$inc: {postCount: -1}});
// delete post
Posts.remove(postId);
}
}); |
package org.yield4j.tests.labelcontinue;
import static org.yield4j.YieldSupport.*;
//>> [0, 0, 1, 2, 2, 3, 6, 4, 8]
public class <API key> {
@org.yield4j.Generator public Iterable<Integer> method() {
LOOP: for (int i = 0; i < 5; i++) {
yield_return(i);
if (i == 2)
continue LOOP;
yield_return(i * 2);
}
}
} |
package nl.tno.idsa.framework.behavior.multipliers;
import nl.tno.idsa.framework.agents.Agent;
import nl.tno.idsa.framework.behavior.likelihoods.<API key>;
/**
* Multipliers for likelihoods implement this interface.
*/
public interface IMultiplier {
public void applyMultipliers(Agent agent, <API key> currentLikelihoods);
} |
<?php
namespace Controller;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response as Response;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Form\<API key> as <API key>;
class IndexController extends \Controller\<API key> {
public function __construct(Application $app) {
parent::__construct($app, __CLASS__);
$this->logoHost = $this->baseHost . "/stalker_portal/misc/logos";
$this->logoDir = str_replace('/admin', '', $this->baseDir) . "/misc/logos";
$this->app['error_local'] = array();
$this->app['baseHost'] = $this->baseHost;
}
public function index() {
if ($no_auth = $this->checkAuth()) {
return $no_auth;
}
$datatables['datatable-1'] = $this-><API key>();
$datatables['datatable-2'] = $this-><API key>();
$datatables['datatable-3'] = $this-><API key>();
$this->app['datatables'] = $datatables;
$this->app['breadcrumbs']->addItem($this->setlocalization('Dashboard'));
return $this->app['twig']->render($this->getTemplateName(__METHOD__));
}
public function <API key>() {
if (!$this->isAjax || empty($this->postData)) {
$this->app->abort(404, 'Page not found');
}
if ($no_auth = $this->checkAuth()) {
return $no_auth;
}
$data = array();
$data['action'] = '<API key>';
$error = $this->setLocalization('Failed');
$aliases = trim(str_replace($this->workURL, '', $this->refferer), '/');
$aliases = array_pad(explode('/', $aliases), 2, 'index');
$aliases[1] = urldecode($aliases[1]);
$filters = explode('?', $aliases[1]);
$aliases[1] = $filters[0];
if (count($filters) > 1 && (!empty($this->data['<API key>']) && $this->data['<API key>'] == 'with-button-filters')) {
$filters[1] = explode("&", $filters[1]);
$filters[1] = $filters[1][0];
$filters[1] = str_replace(array('=', '_'), '-', $filters[1]);
$filters[1] = preg_replace('/(\[[^\]]*\])/i', '', $filters[1]);
$aliases[1] .= "-$filters[1]";
}
// print_r($filters);exit;
$param = array();
$param['controller_name'] = $aliases[0];
$param['action_name'] = $aliases[1];
$param['admin_id'] = $this->admin->getId();
$this->db-><API key>($param);
$param['dropdown_attributes'] = serialize($this->postData);
$id = $this->db-><API key>($param);
if ($id && $id != 0) {
$error = '';
}
$response = $this-><API key>($data, $error);
if (empty($error)) {
header($_SERVER['SERVER_PROTOCOL'] . " 200 OK", true, 200);
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($response);
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
exit;
}
public function <API key>(){
$data = array(
'data' => array(),
'recordsTotal' => 0,
'recordsFiltered' => 0
);
if ($this->isAjax) {
if ($no_auth = $this->checkAuth()) {
return $no_auth;
}
}
$data['action'] = 'datatableReload';
$data['datatableID'] = 'datatable-1';
$data['json_action_alias'] = '<API key>';
$error = $this->setLocalization('Failed');
$data['data'] = array();
$row = array('category'=>'', 'number' => '');
$row['category'] = $this->setLocalization('Users online');
$row['number'] = '<span class="txt-success">' . $this->db->get_users('online') . '</sapn>';
$data['data'][] = $row;
$row['category'] = $this->setLocalization('Users offline');
$row['number'] = '<span class="txt-danger">' . $this->db->get_users('offline') . '</sapn>';
$data['data'][] = $row;
$row['category'] = $this->setLocalization('TV channels');
$row['number'] = $this->db-><API key>('itv', array('status' => 1));
$data['data'][] = $row;
$row['category'] = $this->setLocalization('Films, serials');
$row['number'] = $this->db-><API key>('video', array('status' => 1, 'accessed' => 1));
$data['data'][] = $row;
$row['category'] = $this->setLocalization('Audio albums');
$row['number'] = $this->db-><API key>('audio_albums', array('status' => 1));
$data['data'][] = $row;
$row['category'] = $this->setLocalization('Karaoke songs');
$row['number'] = $this->db-><API key>('karaoke', array('status' => 1));
$data['data'][] = $row;
$row['category'] = $this->setLocalization('Installed applications');
$row['number'] = 0;
$data['data'][] = $row;
$data["draw"] = !empty($this->data['draw']) ? $this->data['draw'] : 1;
if ($this->isAjax) {
$error = '';
$data = $this-><API key>($data);
return new Response(json_encode($data), (empty($error) ? 200 : 500));
} else {
return $data;
}
}
public function <API key>(){
$data = array(
'data' => array(),
'recordsTotal' => 0,
'recordsFiltered' => 0
);
if ($this->isAjax) {
if ($no_auth = $this->checkAuth()) {
return $no_auth;
}
}
$data['action'] = 'datatableReload';
$data['datatableID'] = 'datatable-2';
$data['json_action_alias'] = '<API key>';
$error = $this->setLocalization('Failed');
$data['data'] = array();
$storages = $this->db->getStorages();
foreach($storages as $storage){
$row = array('storage'=> $storage['storage_name'], 'video' => '-', 'tv_archive' => '-', 'timeshift'=>'-', 'loading' => 0);
$records = $this->db->getStoragesRecords($row['storage']);
$<API key> = $this->db->getStoragesRecords($row['storage'], TRUE);
$row['loading'] = (int) $storage['max_online'] ? round(($<API key>*100)/$storage['max_online'], 2) . "%": '-';
foreach ($records as $record) {
if ($record['now_playing_type'] == 2) {
$row['video'] = $record['count'];
} elseif ($record['now_playing_type'] == 11) {
$row['tv_archive'] = $record['count'];
} elseif ($record['now_playing_type'] == 14) {
$row['timeshift'] = $record['count'];
}
}
$data['data'][] = $row;
}
$data["draw"] = !empty($this->data['draw']) ? $this->data['draw'] : 1;
if ($this->isAjax) {
$error = '';
$data = $this-><API key>($data);
return new Response(json_encode($data), (empty($error) ? 200 : 500));
} else {
return $data;
}
}
public function <API key>(){
$data = array(
'data' => array(),
'recordsTotal' => 0,
'recordsFiltered' => 0
);
if ($this->isAjax) {
if ($no_auth = $this->checkAuth()) {
return $no_auth;
}
}
$data['action'] = 'datatableReload';
$data['datatableID'] = 'datatable-3';
$data['json_action_alias'] = '<API key>';
$error = $this->setLocalization('Failed');
$data['data'] = array();
$streaming_servers = $this->db->getStreamServer();
foreach($streaming_servers as $server){
$user_sessions = $this->db-><API key>($server['id'], TRUE);
$row = array(
'server'=> $server['name'],
'sessions' => $user_sessions,
'loading' => ((int) $server['max_sessions'] > 0 ? round(($user_sessions * 100)/$server['max_sessions'], 2)."%" : "∞")
);
$data['data'][] = $row;
}
$data["draw"] = !empty($this->data['draw']) ? $this->data['draw'] : 1;
if ($this->isAjax) {
$error = '';
$data = $this-><API key>($data);
return new Response(json_encode($data), (empty($error) ? 200 : 500));
} else {
return $data;
}
}
public function <API key>(){
$data = array(
'data' => array(),
'recordsTotal' => 0,
'recordsFiltered' => 0
);
if ($this->isAjax) {
if ($no_auth = $this->checkAuth()) {
return $no_auth;
}
}
$data['action'] = 'datatableReload';
$data['datatableID'] = 'datatable-4';
$data['json_action_alias'] = '<API key>';
$error = $this->setLocalization('Failed');
$data['data'] = array();
$types = array('tv' => 1,'video' => 2, 'karaoke' => 3, 'audio' => 4, 'radio' => 5);
$all_sessions = 0;
foreach($types as $key=>$type){
$data['data'][$key] = array();
$data['data'][$key]['sessions'] = $this->db-><API key>($type);
$all_sessions += $data['data'][$key]['sessions'];
}
$data['data'] = array_map(function($row) use ($all_sessions){
settype($row['sessions'], 'int');
$row['percent'] = ($all_sessions)? round(($row['sessions'] * 100)/$all_sessions,0): 0;
return $row;
}, $data['data']);
$data['data']['all_sessions'] = (int)$all_sessions;
if ($this->isAjax) {
$error = '';
$data = $this-><API key>($data);
return new Response(json_encode($data), (empty($error) ? 200 : 500));
} else {
return $data;
}
}
public function <API key>(){
$data = array(
'data' => array(),
'recordsTotal' => 0,
'recordsFiltered' => 0
);
if ($this->isAjax) {
if ($no_auth = $this->checkAuth()) {
return $no_auth;
}
}
$data['action'] = 'datatableReload';
$data['datatableID'] = 'datatable-5';
$data['json_action_alias'] = '<API key>';
$error = $this->setLocalization('Failed');
$data['data'] = $this->db->getUsersActivity();
$data['data'] = array_map(function($row){
settype($row['time'], 'int');
settype($row['users_online'], 'int');
return array($row['time'], $row['users_online']);
}, $data['data']);
if ($this->isAjax) {
$error = '';
$data = $this-><API key>($data);
return new Response(json_encode($data), (empty($error) ? 200 : 500));
} else {
return $data;
}
}
} |
<?php
ob_start();
session_start();
//set timezone
<API key>('Asia/Jakarta');
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','dbsekolah');
//application address
define('DIR','http://loginadmin.ipjpi.org/');
define('SITEEMAIL','noreply@ipjpi.org');
try {
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?> |
from __future__ import absolute_import, print_function, unicode_literals
import unittest
from choicer.test import core_tests
def suite():
return unittest.TestSuite([
unittest.TestLoader().<API key>(core_tests.ChoicerTests),
])
def run_all():
return unittest.TextTestRunner(verbosity=2).run(suite()) |
using System.Text;
using Antlr.Runtime;
using SheepAspect.Helpers;
namespace SheepAspect.Saql.Exceptions
{
public class <API key>: SaqlException
{
public <API key>(<API key> e)
: base(GetMessage(e), e)
{
}
private static string GetMessage(<API key> e)
{
var pointerBuilder = new StringBuilder(e.CharPositionInLine + 1);
for (var i = 0; i < e.CharPositionInLine; i++)
{
pointerBuilder.Append('-');
}
pointerBuilder.Append('^');
return "Error at {0}:{1}.\r\n\"{2}\"\r\n-{3}".FormatWith(e.Line, e.CharPositionInLine, e.Input, pointerBuilder);
}
}
} |
<table class="monitor-table table">
<thead>
<tr>
<th>ID</th>
<th>FULLNAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
<th>STATUS</th>
<th>REGISTERED</th>
<th>SHOPS OWNED</th>
<th>SUBSCRIPTIONS</th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($lessors as $lessor) { ?>
<tr>
<td><?php echo $lessor->subscriber_id; ?></td>
<td><?php echo $lessor->subscriber_fname . ' ' . $lessor->subscriber_lname; ?></td>
<td><?php echo $lessor->subscriber_telno; ?></td>
<td><?php echo $lessor->subscriber_email; ?></td>
<td><?php echo $lessor->subscriber_status; ?></td>
<td><?php echo $lessor->date_registered; ?></td>
<td><?php echo $lessor->total_shops; ?></td>
<td><?php echo $lessor->total_subscriptions; ?></td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table> |
<span><?php print render($content['<API key>']); ?></span><br />
<span class="size-14"><?php print render($content['body']); ?></span>
<?php if (!empty($content['field_noticia'])): ?>
<span class="label">Anexo da notícia: </span><span class="size-14"><?php print render($content['field_noticia']); ?></span><br />
<?php endif; ?>
<?php if (!empty($content['field_noticia_link'])): ?>
<span class="label">Links da notícia: </span><span class="size-14"><?php print render($content['field_noticia_link']); ?></span><br />
<?php endif; ?> |
DM.11 Implementing Newsfeed with a Graph
=====================================
Listing Functions
Standard practice
Go
func listUsers() {...}
Sublists
Go
func listUserFriends(user string) {
stmt := `
MATCH
(user:User)-[rel:FRIEND]->(friend:User)
WHERE user.name = {userSub}
RETURN
friend.name, rel.status
ORDER BY
rel.status, friend.name
`
params := neoism.Props{"userSub": user}
res := []struct {
Name string `json:"friend.name"`
Status string `json:"rel.status"`
}{}
}
func listUserPosts(user string) {
stmt := `
MATCH (user:User)-[:POSTED]-(post:Post)
WHERE user.name = {userSub}
RETURN
post.date AS date,
post.name AS title,
post.text AS text
ORDER BY post.date DESC
`
params := neoism.Props{"userSub": user}
res := []struct {
Date int `json:"date"`
Title string `json:"title"`
Text string `json:"text"`
}{}
}
Get status for all users
Go
func listUsersStatus() {
stmt := `
MATCH (u)-[:STATUS]-(p:Post)
RETURN
u.name AS name,
p.date AS date,
p.name AS title,
p.text AS text
ORDER BY p.date DESC
`
res := []struct {
User string `json:"name"`
Date int `json:"date"`
Title string `json:"title"`
Text string `json:"text"`
}{}
// construct query
cq := neoism.CypherQuery{
Statement: stmt,
Parameters: nil,
Result: &res,
}
// execute query
err := db.Cypher(&cq)
panicErr(err)
fmt.Println("User Status:")
if len(res) > 0 {
for _, n := range res {
fmt.Printf(" %-8s [%02d]: %-12s %q\n", n.User, n.Date, n.Title, n.Text)
}
} else {
fmt.Println("No results found")
}
}
Get newsfeed for a user
Go
func listUsersNewsfeed(user string) {
stmt := `
MATCH (me:User)-[rel:FRIEND]->(myfriend:User)-[:POSTED]-(post:Post)
WHERE me.name = {userSub} AND rel.status = "CONFIRMED"
RETURN
myfriend.name AS name,
post.date AS date,
post.name AS title,
post.text AS text
ORDER BY post.date DESC LIMIT 3
`
params := neoism.Props{"userSub": user}
res := []struct {
Friend string `json:"name"`
Date int `json:"date"`
Title string `json:"title"`
Text string `json:"text"`
}{}
// construct query
cq := neoism.CypherQuery{
Statement: stmt,
Parameters: params,
Result: &res,
}
// execute query
err := db.Cypher(&cq)
panicErr(err)
fmt.Println(user, " Newsfeed:")
if len(res) > 0 {
for _, n := range res {
fmt.Printf(" %-8s [%02d]: %-12s %q\n", n.Friend, n.Date, n.Title, n.Text)
}
} else {
fmt.Println("No results found")
}
}
Add a new post for a user
Go
func addNewPost(user, title, text string, date int) {
stmt := `
MATCH (user:User)-[r:STATUS]-(post:Post)
WHERE user.name = {userSub}
DELETE r
CREATE (newpost:Post {date:{dateSub}, name:{titleSub}, text:{textSub}})
CREATE (user)-[:POSTED]->(newpost)
CREATE (user)-[:STATUS]->(newpost)
`
params := neoism.Props{
"userSub": user,
"titleSub": title,
"textSub": text,
"dateSub": date,
}
// construct query
cq := neoism.CypherQuery{
Statement: stmt,
Parameters: params,
Result: nil,
}
// execute query
err := db.Cypher(&cq)
panicErr(err)
fmt.Println("New Post:\n ", user, date, title, text)
} |
layout: page
title: "Meloni Rudolph"
comments: true
description: "blanks"
keywords: "Meloni Rudolph,CU,Boulder"
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
font-family: "Bebas Neue";
src: url(https:
}
h1.Bebas {
font-family: "Bebas Neue", Verdana, Tahoma;
}
</style>
</head>
# TEACHING INFORMATION
**College**: College of Arts and Sciences
**Classes taught**: FARR 1003, FARR 1595
# FARR 1003: BANNED BOOKS
**Terms taught**: Fall 2006, Spring 2007, Fall 2007, Spring 2008, Fall 2008, Spring 2009
**Instructor rating**: 4.87
**Standard deviation in instructor rating**: 0.49
**Average grade** (4.0 scale): 0.0
**Standard deviation in grades** (4.0 scale): 0.0
**Average workload** (raw): 1.14
**Standard deviation in workload** (raw): 0.09
# FARR 1595: SVC:PERS GRTH/PUB GOOD
**Terms taught**: Spring 2007
**Instructor rating**: 4.6
**Standard deviation in instructor rating**: 0.0
**Average grade** (4.0 scale): 0.0
**Standard deviation in grades** (4.0 scale): 0.0
**Average workload** (raw): 2.2
**Standard deviation in workload** (raw): 0.0 |
body {
font-family: Neuton, Georgia, "Times New Roman",Times,serif;
font-size: 20px;
line-height: 1.5em;
color: #222;
}
h1 {
margin: 2em 0 0.35em 0;
font-weight: normal;
font-size: 2em;
}
h2 {
margin: 0 0 3em 0;
font-weight: normal;
font-size: 1.125em;
}
h3 {
margin: 2em 0 1em 0;
font-family: Montserrat, 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-weight: normal;
font-weight: 400;
font-size: 0.75em;
text-transform: uppercase;
letter-spacing: 0.125em;
}
ul {
margin: 0 0 0.25em 0;
padding: 0;
border: 1px solid #fdd;
border-top: none;
}
li {
list-style-type: none;
}
li i {
font-size: 0.8em;
padding: 0 0 0 0.5em;
font-style: normal;
color: #666;
}
li a {
display: block;
padding: 0.5em 1em;
border-top: 1px solid #fdd;
border-left: 1px solid #fdd;
text-decoration: none;
color: inherit;
}
li a:hover {
background-color: #f66;
color: #fee;
}
li a:hover i {
color: #fee;
}
p a {
text-decoration: none;
color: inherit;
}
p a:hover {
color: #f66;
border-bottom: 1px solid #fdd;
}
.note {
font-size: 0.8em;
}
.contact {
margin: 3em 0 0 0;
} |
<?php
namespace War_Api\Data;
use War_Api\Data\Query_Builder as Query_Builder;
use War_Api\Helpers\Global_Helpers as Global_Helpers;
/**
* Example Query Map
* $war_db_map = [
* 'query' => [
* 'select' => [],
* 'table' => 'table',
* 'join' => [
* [
* 'query' => [],
* 'on' => '',
* 'as' => ''
* ]
* ],
* 'where' => [],
* 'group' => [],
* 'order' => [],
* 'limit' => 10,
* 'offset' => 0,
* 'query' => NULL //To Be filled in By War_DB
* ],
* 'assoc' => [
* [
* 'map' => [
* 'assoc' => '',
* 'bind' => '',
* 'match' => '',
* 'table' => ''
* ],
* 'query' => []
* ]
* ]
* ];
**/
class War_DB {
private $db;
public $db_info;
private $query_builder;
private $help;
private $safe_table = [];
private static $instance = null;
private static $db_host;
private function __construct( $db_info = false ){
// Set passed $db connection or default to WP DB connection
$this->db_info = ( ! $db_info || empty( $db_info ) || ! is_array( $db_info ) ) ? $this->get_wp_db_info() : $db_info;
// Set db_host for future checking
self::$db_host = $this->db_info[ 'db_host' ];
// Create MySQL Connection
$this->db = $this->connect_to_mysql();
// Setup other War Classes
$this->query_builder = new Query_Builder;
$this->help = new Global_Helpers;
}
//Initialize the War_DB Class
public static function init( $db_info = false ){
if( self::$instance === null ) self::$instance = new War_DB( $db_info );
if( $db_info && $db_info[ 'db_host' ] !== self::$db_host ) self::$instance = new War_DB( $db_info );
return self::$instance;
}
// Check if a table already exists
public function table_check( $table = false, $throw = true ){
if( ! $table ) return $table;
if( is_array( $table ) ) $table = array_values( $table )[0];
if( in_array( $table, $this->safe_table ) ) return true;
$query = 'SHOW TABLES LIKE "' . $table . '"';
$check = $this->db_call( $query )->fetch_row()[0];
if( $check === NULL && $throw ) throw new \Exception( get_class() . ': Table ' . $table . ' doesn\'t exist from Table Check Method' );
if( $check === NULL && ! $throw ) return false;
$this->safe_table[] = $table;
return true;
}
public function select_one( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Select One Method' );
$query_map = (object)$query_map;
$query = $this->query_builder->select( $query_map );
return $this->db_call( $query )->fetch_row()[0];
}
public function select_row( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Select Row Method' );
$query_map = (object)$query_map;
//Check My Table
$this->table_check( $query_map->table );
//Build the Query String
$query = $this->query_builder->select( $query_map );
//Return One Row from the results
return $this->db_call( $query )->fetch_row();
}
public function select_all( $query_map = array(), $table_check = true ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Select All Method' );
$query_map = (object)$query_map;
//Check My Table
if( $table_check ) $this->table_check( $query_map->table );
//Build me a Select Query!
$query = $this->query_builder->select( $query_map );
//Call initial results
$db_call = $this->db_call( $query );
//Return all the results
$result = $db_call->fetch_all( MYSQLI_ASSOC );
$db_call->free();
return $this->help->numberfy( $result );
return $result;
}
public function select_query( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Select Query Method' );
$query_map = (object)$query_map;
$query = $this->query_builder->select( $query_map );
return $this->db_call( $query )->fetch_all( MYSQLI_ASSOC );
}
public function insert( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Insert Method' );
$query_map = (object)$query_map;
//Check My Table
$this->table_check( $query_map->table );
if( ! property_exists( $query_map, 'update' ) || ! is_bool( $query_map->update ) ) $query_map->update = false;
// Get the right query
if( property_exists( $query_map, 'data' ) ) $query = $this->query_builder->insert_from_data( $query_map );
if( property_exists( $query_map, 'query' ) ) $query = $this->query_builder->insert_from_query( $query_map );
$result = $this->db_call( $query );
if( ! $result ) return $result;
return $this->db->affected_rows;
}
public function update( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Update Method' );
$query_map = (object)$query_map;
//Check My Table
$this->table_check( $query_map->table );
if( property_exists( $query_map, 'data' ) ) $query = $this->query_builder->update_from_data( $query_map );
if( property_exists( $query_map, 'query' ) ) $query = $this->query_builder->update_from_query( $query_map );
$result = $this->db_call( $query );
if( ! $result ) return $result;
return $this->db->affected_rows;
}
public function delete( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Delete Method' );
$query_map = (object)$query_map;
//Check My Table
$this->table_check( $query_map->table );
$query = $this->query_builder->delete( $query_map );
$result = $this->db_call( $query );
if( ! $result ) return $result;
return $this->db->affected_rows;
}
public function alter_table( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Alter Table Method' );
$query_map = (object)$query_map;
//Check My Table
$this->table_check( $query_map->table );
$query = $this->query_builder->alter( $query_map );
$result = $this->db_call( $query );
if( ! $result ) return $result;
return $this->db->affected_rows;
}
public function create_table( $query_map = array() ){
if( empty( $query_map ) ) throw new \Exception( get_class() . ': Missing a Proper Query Map for Create Table Method' );
$query_map = (object)$query_map;
//Check My Table
$check = $this->table_check( $query_map->table, false ); // Don't throw an exception
if( $check ) return $check;
$query = $this->query_builder->create_table( $query_map );
$result = $this->db_call( $query );
if( ! $result ) return $result;
return $this->db->affected_rows;
}
public function query( $query_string = false ){
if( ! $query_string || ! is_string( $query_string ) ) throw new \Exception( get_class() . ': Missing Query String for Query Method' );
return $this->db_call( $query_string );
}
//Simple Call to mysql. The Query should already be safe to run by now
// Also, no need to process the results, just send it back (unless it errored )
private function db_call( $query = false ){
if( ! $query ) throw new \Exception( get_class() . ': No Query Provided for DB Call Method' );
if( ! is_string( $query ) ) throw new \Exception( get_class() . ': Query Provided is Not A String for DB Call Method' );
// echo "$query\n\n";
$result = $this->db->query( $query );
if( ! $result ) throw new \Exception( get_class() . ': ' . $this->db->error . ' QUERY: ' . $query );
return $result;
}
//Get creds from wp_config.php, return default connection to wp db
private function get_wp_db_info(){
$db_user = ( DB_USER !== NULL ) ? DB_USER : NULL;
$db_password = ( DB_PASSWORD !== NULL ) ? DB_PASSWORD : NULL;
$db_host = ( DB_HOST !== NULL ) ? DB_HOST : NULL;
$db_name = ( DB_NAME !== NULL ) ? DB_NAME : NULL;
//Use WordPress $table_prefix as a last resort
global $table_prefix;
return [
'db_user' => $db_user,
'db_password' => $db_password,
'db_name' => $db_name,
'db_host' => $db_host,
'table_prefix' => $table_prefix
];
}
private function connect_to_mysql(){
if( ! property_exists( $this, 'db_info' ) ) throw new \Exception( get_class() . ': No DB Information Provided for Connect To MySQL Method' );
$db_info = (object)$this->db_info;
if( ! property_exists( $db_info, 'db_port' ) ) $db_info->db_port = NULL; //Default mysql port
$db = mysqli_init();
$db->options( <API key>, 1 );
if( property_exists( $db_info, 'ssl' ) && is_array( $db_info->ssl ) )
$db->ssl_set( $db_info->ssl[0], $db_info->ssl[1], $db_info->ssl[2], $db_info->ssl[3], $db_info->ssl[4] );
$db->real_connect(
$db_info->db_host,
$db_info->db_user,
$db_info->db_password,
$db_info->db_name,
$db_info->db_port
);
if( $db->connect_errno ){
mysqli_close( $db );
throw new \Exception( get_class() . ': DB Call Method Failed to connect to Mysql: (' . $db->connect_errno . ') ' . $db->connect_error );
}
return $db;
}
} // END War_DB Class |
package edu.psu.compbio.seqcode.gse.projects.readdb;
import java.io.IOException;
import java.util.List;
import net.sf.samtools.AlignmentBlock;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.SAMFileReader.<API key>;
import net.sf.samtools.util.CloseableIterator;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import edu.psu.compbio.seqcode.gse.utils.RealValuedHistogram;
public class SAMStats {
private Double totalReads = 0.0, totalHits=0.0, LHits=0.0, RHits=0.0;
private Double singleEnd=0.0, properPair=0.0, pairMapped=0.0, notPrimary=0.0;
private Double junctions=0.0;
private Double uniquelyMapped=0.0;
private Double weight=0.0;
private Integer readLen =-1;
private Double pairedEndSameChr=0.0, pairedEndDiffChr=0.0;
private Boolean bowtie1=false, bowtie2=false;
private RealValuedHistogram histo;
public static void main(String args[]) throws IOException, ParseException {
Options options = new Options();
options.addOption("i","insdist",false,"print insert size distribution");
options.addOption("s","stats",false,"print mapping stats");
options.addOption("l","readlen",false,"read length");
options.addOption("c","readcount",false,"read count");
options.addOption("bt2",false,"input is from bowtie2");
options.addOption("bt1",false,"input is from bowtie1 (tested for --best --strata -m 1)");
CommandLineParser parser = new GnuParser();
CommandLine cl = parser.parse( options, args, false );
SAMStats s = new SAMStats(cl.hasOption("bt1"), cl.hasOption("bt2"));
if(cl.hasOption("insdist"))
s.printInsertDistrib();
if(cl.hasOption("stats"))
s.printStats();
if(cl.hasOption("readlen"))
s.printReadLength();
if(cl.hasOption("readcount"))
s.printReadCount();
}
public SAMStats(boolean bowtie1, boolean bowtie2){
this.bowtie1 = bowtie1;
this.bowtie2 = bowtie2;
histo = new RealValuedHistogram(0, 1000, 100);
SAMFileReader reader = new SAMFileReader(System.in);
reader.<API key>(<API key>.SILENT);
CloseableIterator<SAMRecord> iter = reader.iterator();
while (iter.hasNext()) {
SAMRecord record = iter.next();
if(readLen==-1)
readLen = record.getReadLength();
if(bowtie1)
processBT1SAMRecord(record);
else if(bowtie2)
processBT2SAMRecord(record);
else
processSAMRecord(record);
}
iter.close();
reader.close();
}
public void processSAMRecord(SAMRecord r){
totalReads++;
if(!r.getReadUnmappedFlag()){
totalHits++;
int count = 1; //Have to figure out something for BWA when reporting multiple alignments
if(r.getIntegerAttribute("NH")!=null)
count = r.getIntegerAttribute("NH");
if(count==1 && r.getMappingQuality()!=0) //Second clause for BWA
uniquelyMapped++;
weight += 1/(float)count;
if(r.getReadPairedFlag()){
if(r.getMateUnmappedFlag()){
singleEnd++;
}else{
pairMapped++;
if(r.<API key>().equals(r.getReferenceName())){
pairedEndSameChr++;
}else{
pairedEndDiffChr++;
}
}
}else{
singleEnd++;
}
List<AlignmentBlock> blocks = r.getAlignmentBlocks();
if(blocks.size()>=2){
junctions+=blocks.size()-1;
}
if(!r.<API key>()){
if(!r.getReadPairedFlag() || r.getFirstOfPairFlag()){
LHits++;
if(r.getReadPairedFlag() && r.getProperPairFlag()){
properPair++;
if(!r.<API key>() && r.<API key>()){
double dist = (r.<API key>()+r.getReadLength())-r.getAlignmentStart();
histo.addValue(dist);
}
}
}else if(r.getSecondOfPairFlag()){
RHits++;
}
}else{
notPrimary++;
}
}
}
public void processBT1SAMRecord(SAMRecord r){
totalReads++;
if(!r.getReadUnmappedFlag())
if(r.getIntegerAttribute("XM")!=null){
int xm = r.getIntegerAttribute("XM");
if(xm!=0)
weight++;
}
else{
totalHits++;
int count =1; //TODO: Fix this if using bowtie for multi-mapping reads
boolean currUnique = true;
if(count==1 && currUnique){
uniquelyMapped++;
}
weight += 1/(float)count;
if(r.getReadPairedFlag()){
if(r.getMateUnmappedFlag()){
singleEnd++;
}else{
pairMapped++;
if(r.<API key>().equals(r.getReferenceName())){
pairedEndSameChr++;
}else{
pairedEndDiffChr++;
}
}
}else{
singleEnd++;
}
List<AlignmentBlock> blocks = r.getAlignmentBlocks();
if(blocks.size()>=2){
junctions+=blocks.size()-1;
}
if(!r.<API key>()){
if(!r.getReadPairedFlag() || r.getFirstOfPairFlag()){
LHits++;
if(r.getReadPairedFlag() && r.getProperPairFlag()){
properPair++;
if(!r.<API key>() && r.<API key>()){
double dist = (r.<API key>()+r.getReadLength())-r.getAlignmentStart();
histo.addValue(dist);
}
}
}else if(r.getSecondOfPairFlag()){
RHits++;
}
}else{
notPrimary++;
}
}
}
public void processBT2SAMRecord(SAMRecord r){
totalReads++;
if(!r.getReadUnmappedFlag()){
totalHits++;
int count =1; //TODO: Fix this if using bowtie2 for multi-mapping reads
int primAScore = r.getIntegerAttribute("AS");
int secAScore=-1000000;
if(r.getIntegerAttribute("XS")!=null)
secAScore = r.getIntegerAttribute("XS");
boolean currUnique = primAScore > secAScore ? true : false;
if(count==1 && currUnique){
uniquelyMapped++;
}
weight += 1/(float)count;
if(r.getReadPairedFlag()){
if(r.getMateUnmappedFlag()){
singleEnd++;
}else{
pairMapped++;
if(r.<API key>().equals(r.getReferenceName())){
pairedEndSameChr++;
}else{
pairedEndDiffChr++;
}
}
}else{
singleEnd++;
}
List<AlignmentBlock> blocks = r.getAlignmentBlocks();
if(blocks.size()>=2){
junctions+=blocks.size()-1;
}
if(!r.<API key>()){
if(!r.getReadPairedFlag() || r.getFirstOfPairFlag()){
LHits++;
if(r.getReadPairedFlag() && r.getProperPairFlag()){
properPair++;
if(!r.<API key>() && r.<API key>()){
double dist = (r.<API key>()+r.getReadLength())-r.getAlignmentStart();
histo.addValue(dist);
}
}
}else if(r.getSecondOfPairFlag()){
RHits++;
}
}else{
notPrimary++;
}
}
}
public void printReadLength(){
System.out.println(readLen);
}
public void printReadCount(){
System.out.println(String.format("%.0f",+totalReads));
}
public void printInsertDistrib(){
histo.printContents();
}
public void printStats(){
System.out.println("\nTotalHits:\t"+String.format("%.0f",+totalHits));
System.out.println("MappedSeq:\t"+String.format("%.0f",weight));
System.out.println("UniquelyMapped:\t"+String.format("%.0f",uniquelyMapped));
System.out.println("SingleEndMapped:\t"+String.format("%.0f",singleEnd));
if(pairMapped>0){
System.out.println("LeftHits:\t"+String.format("%.0f",LHits));
System.out.println("RightHits:\t"+String.format("%.0f",RHits));
System.out.println("PairedEndMapped:\t"+String.format("%.0f",pairMapped));
System.out.println("ProperPairs:\t"+String.format("%.0f",properPair));
System.out.println("Junctions:\t"+String.format("%.0f",junctions));
System.out.println("<API key>:\t"+String.format("%.0f",pairedEndSameChr));
System.out.println("<API key>:\t"+String.format("%.0f",pairedEndDiffChr));
System.out.println("NotPrimary:\t"+String.format("%.0f",notPrimary));
}
}
} |
--SAFETRIM
-- function _provision(self,socket,first_rec)
local self, socket, first_rec = ...
local crypto, file, json, node, table = crypto, file, sjson, node, table
local stripdebug, gc = node.stripdebug, collectgarbage
local buf = {}
gc(); gc()
local function getbuf() -- upval: buf, table
if #buf > 0 then return table.remove(buf, 1) end -- else return nil
end
-- Process a provisioning request record
local function receiveRec(socket, rec) -- upval: self, buf, crypto
-- Note that for 2nd and subsequent responses, we assme that the service has
-- "authenticated" itself, so any protocol errors are fatal and lkely to
-- cause a repeating boot, throw any protocol errors are thrown.
local config, file, log = self.config, file, self.log
local cmdlen = (rec:find('\n',1, true) or 0) - 1
local cmd,hash = rec:sub(1,cmdlen-6), rec:sub(cmdlen-5,cmdlen)
if cmdlen < 16 or
hash ~= crypto.toHex(crypto.hmac("MD5",cmd,self.secret):sub(-3)) then
return error("Invalid command signature")
end
local s; s, cmd = pcall(json.decode, cmd)
local action,resp = cmd.a, {s = "OK"}
local chunk
if action == "ls" then
for name,len in pairs(file.list()) do
resp[name] = len
end
elseif action == "mv" then
if file.exists(cmd.from) then
if file.exists(cmd.to) then file.remove(cmd.to) end
if not file.rename(cmd.from,cmd.to) then
resp.s = "Rename failed"
end
end
else
if action == "pu" or action == "cm" or action == "dl" then
-- These commands have a data buffer appended to the received record
if cmd.data == #rec - cmdlen - 1 then
buf[#buf+1] = rec:sub(cmdlen +2)
else
error(("Record size mismatch, %u expected, %u received"):format(
cmd.data or "nil", #buf - cmdlen - 1))
end
end
if action == "cm" then
stripdebug(2)
local lcf,msg = load(getbuf, cmd.name)
if not msg then
gc(); gc()
local code, name = string.dump(lcf), cmd.name:sub(1,-5) .. ".lc"
local s = file.open(name, "w+")
if s then
for i = 1, #code, 1024 do
s = s and file.write(code:sub(i, ((i+1023)>#code) and i+1023 or #code))
end
file.close()
if not s then file.remove(name) end
end
if s then
resp.lcsize=#code
print("Updated ".. name)
else
msg = "file write failed"
end
end
if msg then
resp.s, resp.err = "compile fail", msg
end
buf = {}
elseif action == "dl" then
local s = file.open(cmd.name, "w+")
if s then
for i = 1, #buf do
s = s and file.write(buf[i])
end
file.close()
end
if s then
print("Updated ".. cmd.name)
else
file.remove(cmd.name)
resp.s = "write failed"
end
buf = {}
elseif action == "ul" then
if file.open(cmd.name, "r") then
file.seek("set", cmd.offset)
chunk = file.read(cmd.len)
file.close()
end
elseif action == "restart" then
cmd.a = nil
cmd.secret = self.secret
file.open(self.prefix.."config.json", "w+")
file.writeline(json.encode(cmd))
file.close()
socket:close()
print("Restarting to load new application")
node.restart() -- reboot just schedules a restart
return
end
end
self.socket_send(socket, resp, chunk)
gc()
end
-- Replace the receive CB by the provisioning version and then tailcall this to
-- process this first record.
socket:on("receive", receiveRec)
return receiveRec(socket, first_rec) |
package br.gov.servicos.editor.usuarios.token;
import br.gov.servicos.editor.usuarios.Usuario;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.experimental.Wither;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Wither
@Table(name = "Tokens")
@EqualsAndHashCode
public class Token implements Serializable {
@Id
@Column(unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "usuario_id")
private Usuario usuario;
@Column(nullable = false)
private String token;
@Column(nullable = false)
private LocalDateTime dataCriacao;
@Column(nullable = false)
private Integer tentativasSobrando;
public <API key>() {
return tentativasSobrando == 0 ? this : <API key>(tentativasSobrando - 1);
}
} |
import Stream from "stream"
import reducer from "../lib/reducer"
import React from "react" // eslint-disable-line no-unused-vars
import {shallow} from "enzyme"
import {GherkinDocument, Feature} from "../lib/cucumber_react"
class ReactOutput extends Stream.Writable {
constructor() {
super({objectMode: true})
this.state = reducer()
}
_write(event, _, callback) {
this.state = reducer(this.state, event)
callback()
}
getFeatureName() {
const node = this.state.getIn(['sources', 'features/hello.feature'])
const gherkinDocumentComp = shallow(<GherkinDocument node={node}/>)
const featureComp = gherkinDocumentComp.find(Feature)
return featureComp.prop('node').name
}
}
module.exports = ReactOutput |
\hypertarget{<API key>}{}\section{R\+TC Add 1 Second Parameter Definitions}
\label{<API key>}\index{R\+T\+C Add 1 Second Parameter Definitions@{R\+T\+C Add 1 Second Parameter Definitions}}
\subsection*{Macros}
\begin{DoxyCompactItemize}
\item
\#define {\bfseries R\+T\+C\+\_\+\+S\+H\+I\+F\+T\+A\+D\+D1\+S\+\_\+\+R\+E\+S\+ET}~((uint32\+\_\+t)0x00000000)\hypertarget{group___r_t_c_ex___add__1___second___parameter___definitions_gaadc96f8fbcb4a576dc126c8a78476864}{}\label{group___r_t_c_ex___add__1___second___parameter___definitions_gaadc96f8fbcb4a576dc126c8a78476864}
\item
\#define {\bfseries R\+T\+C\+\_\+\+S\+H\+I\+F\+T\+A\+D\+D1\+S\+\_\+\+S\+ET}~((uint32\+\_\+t)0x80000000)\hypertarget{group___r_t_c_ex___add__1___second___parameter___definitions_gac22d753caa7eae6b1f4564eba3727900}{}\label{group___r_t_c_ex___add__1___second___parameter___definitions_gac22d753caa7eae6b1f4564eba3727900}
\end{DoxyCompactItemize}
\subsection{Detailed Description} |
#!/usr/bin/env ruby
# encoding: UTF-8
require 'helper'
require 'oflow'
class TrackerTest < ::MiniTest::Test
def test_tracker_new
t = ::OFlow::Tracker.create('here')
t2 = ::OFlow::Tracker.create('here')
refute_equal(t.id, t2.id, 'id must be unique')
assert_equal('here', t.track[0].location)
end
def test_tracker_track
t = ::OFlow::Tracker.create('here')
t2 = t.receive('there', 'op1')
assert_equal('here', t.track[0].location)
assert_equal('here', t2.track[0].location)
assert_equal('there', t2.track[1].location)
end
def test_tracker_merge
t = ::OFlow::Tracker.create('here')
# 2 different paths
t2 = t.receive('there', 'op1')
t3 = t.receive('everywhere', 'op2')
# should not happen but should handle merging when not back to a common place
t4 = t2.merge(t3)
assert_equal('here', t4.track[0].location)
assert_equal(true, t4.track[1].is_a?(Array))
assert_equal(2, t4.track[1].size)
assert_equal('there', t4.track[1][0][0].location)
assert_equal('everywhere', t4.track[1][1][0].location)
# back to a common location
t2 = t2.receive('home', 'op1')
t3 = t3.receive('home', 'op1')
t4 = t2.merge(t3)
assert_equal('here', t4.track[0].location)
assert_equal(true, t4.track[1].is_a?(Array))
assert_equal(2, t4.track[1].size)
assert_equal('there', t4.track[1][0][0].location)
assert_equal('everywhere', t4.track[1][1][0].location)
assert_equal('home', t4.track[2].location)
end
end # TrackerTest |
module Maimailog
module Crawler
class Status < Base
def fetch(id, password)
page = login(id, password)
Maimailog::Data::Status.new(name(page), rating(page), rating_max(page))
end
private
def name(page)
elm = page.search('//div[@class="status_name"]//font[@class="blue"]')
elm.empty? ? '' : elm[0].text.strip
end
def rating(page)
elm = page.search('//div[@class="status_data"]/font[@class="blue"]')
elm.empty? ? '' : elm[1].text.strip[/\d+\.\d+/].to_f
end
def rating_max(page)
elm = page.search('//div[@class="status_data"]/font[@class="blue"]')
elm.empty? ? '' : elm[1].text.strip[/ \d+\.\d+/].to_f
end
end
end
end |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>So, What is Jekyll? – presequences</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Transform your plain text into static websites and blogs. Simple, static, and blog-aware.">
<meta name="author" content="Andrew Miller">
<meta name="keywords" content="jekyll, pixyll">
<link rel="canonical" href="http://presequences.com/jekyll/pixyll/2014/06/09/so-what-is-jekyll/">
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/pixyll.css" type="text/css">
<!-- Fonts -->
<link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<!-- Open Graph -->
<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="So, What is Jekyll?">
<meta property="og:description" content="Description goes here">
<meta property="og:url" content="http://presequences.com/jekyll/pixyll/2014/06/09/so-what-is-jekyll/">
<meta property="og:site_name" content="presequences">
</head>
<body class="">
<div class="site-wrap">
<header class="site-header px2 px-responsive">
<div class="mt2 wrap">
<div class="measure">
<a href="http://presequences.com" class="site-title">presequences</a>
<nav class="site-nav right">
<a href="/about/">About</a>
<!-- <a href="/projects/">Projects</a> -->
</nav>
<div class="clearfix"></div>
<div class="social-icons">
<div class="left">
<a class="fa fa-github" href="https://github.com/andrewpmiller"></a>
<a class="fa fa-rss" href="/feed.xml"></a>
<a class="fa fa-twitter" href="https://twitter.com/andrewpmiller"></a>
<a class="fa fa-envelope" href="mailto:andrew@miller-co.com"></a>
<a class="fa fa-linkedin" href="https:
</div>
<div class="right">
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</header>
<div class="post p2 p-responsive wrap" role="main">
<div class="measure">
<div class="post-header mb2">
<h1>So, What is Jekyll?</h1>
<span class="post-meta">Jun 9, 2014</span><br>
<span class="post-meta small">1 minute read</span>
</div>
<article class="post-content">
<p>Jekyll is a tool for transforming your plain text into static websites and
blogs. It is simple, static, and blog-aware. Jekyll uses the
<a href="http://docs.shopify.com/themes/liquid-basics">Liquid</a> templating
language and has builtin <a href="http://daringfireball.net/projects/markdown/">Markdown</a>
and <a href="http://en.wikipedia.org/wiki/Textile_(markup_language)">Textile</a> support.</p>
<p>It also ties in nicely to <a href="https://pages.github.com/">Github Pages</a>.</p>
<p>Learn more about Jekyll on their <a href="http://jekyllrb.com/">website</a>.</p>
</article>
</div>
</div>
</div>
<footer class="footer">
<div class="p2 wrap">
<div class="measure mt1 center">
<small>
Crafted with <3 by <a href="http:
</> available on <a href="https://github.com/johnotander/pixyll">Github</a>.
</small>
</div>
</div>
</footer>
<script>
(function(i,s,o,g,r,a,m){i['<API key>']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','
ga('create', 'UA-53431135-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html> |
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as _ from 'underscore';
import { Letter } from './letter';
export namespace Signature {
export interface Props {
template: ITemplateModel;
user: IUserDetails;
}
export interface State {
name: string,
signatureHtml: string;
}
}
export class Signature extends React.Component<Signature.Props, Signature.State> {
constructor(props?: Signature.Props, context?: any) {
super(props, context);
this.state = {
name: '',
signatureHtml: ''
}
}
public componentDidMount() {
this.assembleSignature.bind(this)(this.props.template, this.props.user);
}
public <API key>(nextProps: Signature.Props) {
this.assembleSignature.bind(this)(nextProps.template, nextProps.user);
}
private assembleSignature(template: ITemplateModel, data: IUserDetails) {
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
let signature = _.template(template.html)
let result = signature(data);
this.setState({
signatureHtml: result,
name: template.name
})
}
public render() {
return (
<div>
<div className="letter">
<div className="ribbon red"><span>{this.state.name}</span></div>
<Letter />
<div className="letter-signature" <API key>={{ __html: this.state.signatureHtml }} />
</div>
</div>
)
}
} |
import { GlobalStore, useDevToggle } from "app/store/GlobalStore"
import { useEffect } from "react"
import { setupSentry } from "./sentrySetup"
export function useErrorReporting() {
const environment = GlobalStore.useAppState((store) => store.artsyPrefs.environment.env)
const <API key> = useDevToggle("<API key>")
const captureExceptions = !__DEV__ ? true : <API key>
useEffect(() => {
if (captureExceptions) {
setupSentry({ environment })
}
}, [environment, captureExceptions])
} |
<?php
/**
* Implements <API key>().
*
* @param $form
* The form.
* @param $form_state
* The form state.
*/
function <API key>(&$form, &$form_state) {} |
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD module
define(factory);
} else {
// Browser global
root.Meny = factory();
}
} (this, function () {
// Date.now polyfill
if (typeof Date.now !== 'function') Date.now = function () { return new Date().getTime(); };
var Meny = {
// Creates a new instance of Meny
create: function (options) {
return (function () {
// Make sure the required arguments are defined
if (!options || !options.menuElement || !options.contentsElement) {
throw 'You need to specify which menu and contents elements to use.';
}
// Make sure the menu and contents have the same parent
if (options.menuElement.parentNode !== options.contentsElement.parentNode) {
throw 'The menu and contents elements must have the same parent.';
}
// Constants
var POSITION_T = 'top',
POSITION_R = 'right',
POSITION_B = 'bottom',
POSITION_L = 'left';
// Feature detection for 3D transforms
var <API key> = 'WebkitPerspective' in document.body.style ||
'MozPerspective' in document.body.style ||
'msPerspective' in document.body.style ||
'OPerspective' in document.body.style ||
'perspective' in document.body.style;
// Default options, gets extended by passed in arguments
var config = {
width: 300,
height: 300,
position: POSITION_L,
threshold: 40,
angle: 30,
overlap: 6,
transitionDuration: '0.5s',
transitionEasing: 'ease',
gradient: 'rgba(0,0,0,0.20) 0%, rgba(0,0,0,0.65) 100%)',
mouse: true,
touch: true
};
// Cache references to DOM elements
var dom = {
menu: options.menuElement,
contents: options.contentsElement,
wrapper: options.menuElement.parentNode,
cover: null
};
// State and input
var indentX = dom.wrapper.offsetLeft,
indentY = dom.wrapper.offsetTop,
touchStartX = null,
touchStartY = null,
touchMoveX = null,
touchMoveY = null,
isOpen = false,
isMouseDown = false;
// Precalculated transform and style states
var menuTransformOrigin,
menuTransformClosed,
menuTransformOpened,
menuStyleClosed,
menuStyleOpened,
<API key>,
<API key>,
<API key>,
contentsStyleClosed,
contentsStyleOpened;
var originalStyles = {},
addedEventListeners = [];
// Ongoing animations (for fallback mode)
var menuAnimation,
contentsAnimation,
coverAnimation;
configure(options);
/**
* Initializes Meny with the specified user options,
* may be called multiple times as configuration changes.
*/
function configure(o) {
// Extend the default config object with the passed in
// options
Meny.extend(config, o);
setupPositions();
setupWrapper();
setupCover();
setupMenu();
setupContents();
bindEvents();
}
/**
* Prepares the transforms for the current positioning
* settings.
*/
function setupPositions() {
menuTransformOpened = '';
<API key> = '';
menuAngle = config.angle;
contentsAngle = config.angle / -2;
switch (config.position) {
case POSITION_T:
// Primary transform:
menuTransformOrigin = '50% 0%';
menuTransformClosed = 'rotateX( ' + menuAngle + 'deg ) translateY( -100% ) translateY( ' + config.overlap + 'px )';
<API key> = '50% 0';
<API key> = 'translateY( ' + config.height + 'px ) rotateX( ' + contentsAngle + 'deg )';
// Position fallback:
menuStyleClosed = { top: '-' + (config.height - config.overlap) + 'px' };
menuStyleOpened = { top: '0px' };
contentsStyleClosed = { top: '0px' };
contentsStyleOpened = { top: config.height + 'px' };
break;
case POSITION_R:
// Primary transform:
menuTransformOrigin = '100% 50%';
menuTransformClosed = 'rotateY( ' + menuAngle + 'deg ) translateX( 100% ) translateX( -2px ) scale( 1.01 )';
<API key> = '100% 50%';
<API key> = 'translateX( -' + config.width + 'px ) rotateY( ' + contentsAngle + 'deg )';
// Position fallback:
menuStyleClosed = { right: '-' + (config.width - config.overlap) + 'px' };
menuStyleOpened = { right: '0px' };
contentsStyleClosed = { left: '0px' };
contentsStyleOpened = { left: '-' + config.width + 'px' };
break;
case POSITION_B:
// Primary transform:
menuTransformOrigin = '50% 100%';
menuTransformClosed = 'rotateX( ' + -menuAngle + 'deg ) translateY( 100% ) translateY( -' + config.overlap + 'px )';
<API key> = '50% 100%';
<API key> = 'translateY( -' + config.height + 'px ) rotateX( ' + -contentsAngle + 'deg )';
// Position fallback:
menuStyleClosed = { bottom: '-' + (config.height - config.overlap) + 'px' };
menuStyleOpened = { bottom: '0px' };
contentsStyleClosed = { top: '0px' };
contentsStyleOpened = { top: '-' + config.height + 'px' };
break;
default:
// Primary transform:
menuTransformOrigin = '100% 50%';
menuTransformClosed = 'translateX( -100% ) translateX( ' + config.overlap + 'px ) scale( 1.01 ) rotateY( ' + -menuAngle + 'deg )';
<API key> = '0 50%';
<API key> = 'translateX( ' + config.width + 'px ) rotateY( ' + -contentsAngle + 'deg )';
// Position fallback:
menuStyleClosed = { left: '-' + (config.width - config.overlap) + 'px' };
menuStyleOpened = { left: '0px' };
contentsStyleClosed = { left: '0px' };
contentsStyleOpened = { left: config.width + 'px' };
break;
}
}
/**
* The wrapper element holds the menu and contents.
*/
function setupWrapper() {
// Add a class to allow for custom styles based on
// position
Meny.addClass(dom.wrapper, 'meny-' + config.position);
originalStyles.wrapper = dom.wrapper.style.cssText;
dom.wrapper.style[Meny.prefix('perspective')] = '800px';
dom.wrapper.style[Meny.prefix('perspectiveOrigin')] = <API key>;
}
/**
* The cover is used to obfuscate the contents while
* Meny is open.
*/
function setupCover() {
if (dom.cover) {
dom.cover.parentNode.removeChild(dom.cover);
}
dom.cover = document.createElement('div');
// Disabled until a falback fade in animation is added
dom.cover.style.position = 'absolute';
dom.cover.style.display = 'block';
dom.cover.style.width = '100%';
dom.cover.style.height = '100%';
dom.cover.style.left = 0;
dom.cover.style.top = 0;
dom.cover.style.zIndex = 1000;
dom.cover.style.visibility = 'hidden';
dom.cover.style.opacity = 0;
// Silence unimportant errors in IE8
try {
dom.cover.style.background = 'rgba( 0, 0, 0, 0.4 )';
dom.cover.style.background = '-ms-linear-gradient(' + config.position + ',' + config.gradient;
dom.cover.style.background = '-moz-linear-gradient(' + config.position + ',' + config.gradient;
dom.cover.style.background = '-<API key>(' + config.position + ',' + config.gradient;
}
catch (e) { }
if (<API key>) {
dom.cover.style[Meny.prefix('transition')] = 'all ' + config.transitionDuration + ' ' + config.transitionEasing;
}
dom.contents.appendChild(dom.cover);
}
/**
* The meny element that folds out upon activation.
*/
function setupMenu() {
// Shorthand
var style = dom.menu.style;
switch (config.position) {
case POSITION_T:
style.width = '100%';
style.height = config.height + 'px';
break;
case POSITION_R:
style.right = '0';
style.width = config.width + 'px';
style.height = '100%';
break;
case POSITION_B:
style.bottom = '0';
style.width = '100%';
style.height = config.height + 'px';
break;
case POSITION_L:
style.width = config.width + 'px';
style.height = '100%';
break;
}
originalStyles.menu = style.cssText;
style.position = 'fixed';
style.display = 'block';
style.zIndex = 1;
if (<API key>) {
style[Meny.prefix('transform')] = menuTransformClosed;
style[Meny.prefix('transformOrigin')] = menuTransformOrigin;
style[Meny.prefix('transition')] = 'all ' + config.transitionDuration + ' ' + config.transitionEasing;
}
else {
Meny.extend(style, menuStyleClosed);
}
}
/**
* The contents element which gets pushed aside while
* Meny is open.
*/
function setupContents() {
// Shorthand
var style = dom.contents.style;
originalStyles.contents = style.cssText;
if (<API key>) {
style[Meny.prefix('transform')] = <API key>;
style[Meny.prefix('transformOrigin')] = <API key>;
style[Meny.prefix('transition')] = 'all ' + config.transitionDuration + ' ' + config.transitionEasing;
}
else {
style.position = style.position.match(/relative|absolute|fixed/gi) ? style.position : 'relative';
Meny.extend(style, contentsStyleClosed);
}
}
/**
* Attaches all input event listeners.
*/
function bindEvents() {
if ('ontouchstart' in window) {
if (config.touch) {
Meny.bindEvent(document, 'touchstart', onTouchStart);
Meny.bindEvent(document, 'touchend', onTouchEnd);
}
else {
Meny.unbindEvent(document, 'touchstart', onTouchStart);
Meny.unbindEvent(document, 'touchend', onTouchEnd);
}
}
if (config.mouse) {
Meny.bindEvent(document, 'mousedown', onMouseDown);
Meny.bindEvent(document, 'mouseup', onMouseUp);
Meny.bindEvent(document, 'mousemove', onMouseMove);
}
else {
Meny.unbindEvent(document, 'mousedown', onMouseDown);
Meny.unbindEvent(document, 'mouseup', onMouseUp);
Meny.unbindEvent(document, 'mousemove', onMouseMove);
}
}
/**
* Expands the menu.
*/
function open() {
if (!isOpen) {
isOpen = true;
Meny.addClass(dom.wrapper, 'meny-active');
dom.cover.style.height = dom.contents.scrollHeight + 'px';
dom.cover.style.visibility = 'visible';
// Use transforms and transitions if available...
if (<API key>) {
// 'webkitAnimationEnd oanimationend msAnimationEnd animationend transitionend'
Meny.bindEventOnce(dom.wrapper, 'transitionend', function () {
Meny.dispatchEvent(dom.menu, 'opened');
});
dom.cover.style.opacity = 1;
dom.contents.style[Meny.prefix('transform')] = <API key>;
dom.menu.style[Meny.prefix('transform')] = menuTransformOpened;
}
// ...fall back on JS animation
else {
menuAnimation && menuAnimation.stop();
menuAnimation = Meny.animate(dom.menu, menuStyleOpened, 500);
contentsAnimation && contentsAnimation.stop();
contentsAnimation = Meny.animate(dom.contents, contentsStyleOpened, 500);
coverAnimation && coverAnimation.stop();
coverAnimation = Meny.animate(dom.cover, { opacity: 1 }, 500);
}
Meny.dispatchEvent(dom.menu, 'open');
}
}
/**
* Collapses the menu.
*/
function close() {
if (isOpen) {
isOpen = false;
Meny.removeClass(dom.wrapper, 'meny-active');
// Use transforms and transitions if available...
if (<API key>) {
// 'webkitAnimationEnd oanimationend msAnimationEnd animationend transitionend'
Meny.bindEventOnce(dom.wrapper, 'transitionend', function () {
Meny.dispatchEvent(dom.menu, 'closed');
});
dom.cover.style.visibility = 'hidden';
dom.cover.style.opacity = 0;
dom.contents.style[Meny.prefix('transform')] = <API key>;
dom.menu.style[Meny.prefix('transform')] = menuTransformClosed;
}
// ...fall back on JS animation
else {
menuAnimation && menuAnimation.stop();
menuAnimation = Meny.animate(dom.menu, menuStyleClosed, 500);
contentsAnimation && contentsAnimation.stop();
contentsAnimation = Meny.animate(dom.contents, contentsStyleClosed, 500);
coverAnimation && coverAnimation.stop();
coverAnimation = Meny.animate(dom.cover, { opacity: 0 }, 500, function () {
dom.cover.style.visibility = 'hidden';
Meny.dispatchEvent(dom.menu, 'closed');
});
}
Meny.dispatchEvent(dom.menu, 'close');
}
}
/**
* Unbinds Meny and resets the DOM to the state it
* was at before Meny was initialized.
*/
function destroy() {
dom.wrapper.style.cssText = originalStyles.wrapper
dom.menu.style.cssText = originalStyles.menu;
dom.contents.style.cssText = originalStyles.contents;
if (dom.cover && dom.cover.parentNode) {
dom.cover.parentNode.removeChild(dom.cover);
}
Meny.unbindEvent(document, 'touchstart', onTouchStart);
Meny.unbindEvent(document, 'touchend', onTouchEnd);
Meny.unbindEvent(document, 'mousedown', onMouseDown);
Meny.unbindEvent(document, 'mouseup', onMouseUp);
Meny.unbindEvent(document, 'mousemove', onMouseMove);
for (var i in addedEventListeners) {
this.removeEventListener(addedEventListeners[i][0], addedEventListeners[i][1]);
}
addedEventListeners = [];
}
INPUT:
function onMouseDown(event) {
isMouseDown = true;
}
function onMouseMove(event) {
// Prevent opening/closing when mouse is down since
// the user may be selecting text
if (!isMouseDown) {
var x = event.clientX - indentX,
y = event.clientY - indentY;
switch (config.position) {
case POSITION_T:
if (y > config.height) {
close();
}
else if (y < config.threshold) {
open();
}
break;
case POSITION_R:
var w = dom.wrapper.offsetWidth;
if (x < w - config.width) {
close();
}
else if (x > w - config.threshold) {
open();
}
break;
case POSITION_B:
var h = dom.wrapper.offsetHeight;
if (y < h - config.height) {
close();
}
else if (y > h - config.threshold) {
open();
}
break;
case POSITION_L:
if (x > config.width) {
close();
}
else if (x < config.threshold) {
open();
}
break;
}
}
}
function onMouseUp(event) {
isMouseDown = false;
}
function onTouchStart(event) {
touchStartX = event.touches[0].clientX - indentX;
touchStartY = event.touches[0].clientY - indentY;
touchMoveX = null;
touchMoveY = null;
Meny.bindEvent(document, 'touchmove', onTouchMove);
}
function onTouchMove(event) {
touchMoveX = event.touches[0].clientX - indentX;
touchMoveY = event.touches[0].clientY - indentY;
var swipeMethod = null;
// Check for swipe gestures in any direction
if (Math.abs(touchMoveX - touchStartX) > Math.abs(touchMoveY - touchStartY)) {
if (touchMoveX < touchStartX - config.threshold) {
swipeMethod = onSwipeRight;
}
else if (touchMoveX > touchStartX + config.threshold) {
swipeMethod = onSwipeLeft;
}
}
else {
if (touchMoveY < touchStartY - config.threshold) {
swipeMethod = onSwipeDown;
}
else if (touchMoveY > touchStartY + config.threshold) {
swipeMethod = onSwipeUp;
}
}
if (swipeMethod && swipeMethod()) {
event.preventDefault();
}
}
function onTouchEnd(event) {
Meny.unbindEvent(document, 'touchmove', onTouchMove);
// If there was no movement this was a tap
if (touchMoveX === null && touchMoveY === null) {
onTap();
}
}
function onTap() {
var isOverContent = (config.position === POSITION_T && touchStartY > config.height) ||
(config.position === POSITION_R && touchStartX < dom.wrapper.offsetWidth - config.width) ||
(config.position === POSITION_B && touchStartY < dom.wrapper.offsetHeight - config.height) ||
(config.position === POSITION_L && touchStartX > config.width);
if (isOverContent) {
close();
}
}
function onSwipeLeft() {
if (config.position === POSITION_R && isOpen) {
close();
return true;
}
else if (config.position === POSITION_L && !isOpen) {
open();
return true;
}
}
function onSwipeRight() {
if (config.position === POSITION_R && !isOpen) {
open();
return true;
}
else if (config.position === POSITION_L && isOpen) {
close();
return true;
}
}
function onSwipeUp() {
if (config.position === POSITION_B && isOpen) {
close();
return true;
}
else if (config.position === POSITION_T && !isOpen) {
open();
return true;
}
}
function onSwipeDown() {
if (config.position === POSITION_B && !isOpen) {
open();
return true;
}
else if (config.position === POSITION_T && isOpen) {
close();
return true;
}
}
API:
return {
configure: configure,
open: open,
close: close,
destroy: destroy,
isOpen: function () {
return isOpen;
},
/**
* Forward event binding to the menu DOM element.
*/
addEventListener: function (type, listener) {
addedEventListeners.push([type, listener]);
dom.menu && Meny.bindEvent(dom.menu, type, listener);
},
removeEventListener: function (type, listener) {
dom.menu && Meny.unbindEvent(dom.menu, type, listener);
}
};
})();
},
/**
* Helper method, changes an element style over time.
*/
animate: function (element, properties, duration, callback) {
return (function () {
// Will hold start/end values for all properties
var interpolations = {};
// Format properties
for (var p in properties) {
interpolations[p] = {
start: parseFloat(element.style[p]) || 0,
end: parseFloat(properties[p]),
unit: (typeof properties[p] === 'string' && properties[p].match(/px|em|%/gi)) ? properties[p].match(/px|em|%/gi)[0] : ''
};
}
var animationStartTime = Date.now(),
animationTimeout;
// Takes one step forward in the animation
function step() {
// Ease out
var progress = 1 - Math.pow(1 - ((Date.now() - animationStartTime) / duration), 5);
// Set style to interpolated value
for (var p in interpolations) {
var property = interpolations[p];
element.style[p] = property.start + ((property.end - property.start) * progress) + property.unit;
}
// Continue as long as we're not done
if (progress < 1) {
animationTimeout = setTimeout(step, 1000 / 60);
}
else {
callback && callback();
stop();
}
}
// Cancels the animation
function stop() {
clearTimeout(animationTimeout);
}
// Starts the animation
step();
API:
return {
stop: stop
};
})();
},
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
*/
extend: function (a, b) {
for (var i in b) {
a[i] = b[i];
}
},
/**
* Prefixes a style property with the correct vendor.
*/
prefix: function (property, el) {
var propertyUC = property.slice(0, 1).toUpperCase() + property.slice(1),
vendors = ['Webkit', 'Moz', 'O', 'ms'];
for (var i = 0, len = vendors.length; i < len; i++) {
var vendor = vendors[i];
if (typeof (el || document.body).style[vendor + propertyUC] !== 'undefined') {
return vendor + propertyUC;
}
}
return property;
},
/**
* Adds a class to the target element.
*/
addClass: function (element, name) {
element.className = element.className.replace(/\s+$/gi, '') + ' ' + name;
},
/**
* Removes a class from the target element.
*/
removeClass: function (element, name) {
element.className = element.className.replace(name, '');
},
/**
* Adds an event listener in a browser safe way.
*/
bindEvent: function (element, ev, fn) {
if (element.addEventListener) {
element.addEventListener(ev, fn, false);
}
else {
element.attachEvent('on' + ev, fn);
}
},
/**
* Removes an event listener in a browser safe way.
*/
unbindEvent: function (element, ev, fn) {
if (element.removeEventListener) {
element.removeEventListener(ev, fn, false);
}
else {
element.detachEvent('on' + ev, fn);
}
},
bindEventOnce: function (element, ev, fn) {
var me = this;
var listener = function () {
me.unbindEvent(element, ev, listener);
fn.apply(this, arguments);
};
this.bindEvent(element, ev, listener);
},
/**
* Dispatches an event of the specified type from the
* menu DOM element.
*/
dispatchEvent: function (element, type, properties) {
if (element) {
var event = document.createEvent("HTMLEvents", 1, 2);
event.initEvent(type, true, true);
Meny.extend(event, properties);
element.dispatchEvent(event);
}
},
/**
* Retrieves query string as a key/value hash.
*/
getQuery: function () {
var query = {};
location.search.replace(/[A-Z0-9]+?=([\w|:|\/\.]*)/gi, function (a) {
query[a.split('=').shift()] = a.split('=').pop();
});
return query;
}
};
return Meny;
})); |
class CreatePhotos < ActiveRecord::Migration
def self.up
create_table :photos do |t|
t.text :flickr_response
t.string :flickr_id
t.datetime :added_at
t.string :owner
t.timestamps
end
add_index :photos, :flickr_id
add_index :photos, :added_at
add_index :photos, [:owner, :added_at]
end
def self.down
remove_index :photos, :flickr_id
remove_index :photos, :added_at
remove_index :photos, column: [:owner, :added_at]
drop_table :photos
end
end |
<html><body>
<h4>Windows 10 x64 (19041.208) 2004</h4><br>
<h2><API key></h2>
<font face="arial"> +0x000 StackSegmentTable : <a href="./_RTL_HASH_TABLE.html">_RTL_HASH_TABLE</a><br>
+0x010 StackEntryTable : <a href="./_RTL_HASH_TABLE.html">_RTL_HASH_TABLE</a><br>
+0x020 StackEntryTableLock : <a href="./_RTL_SRWLOCK.html">_RTL_SRWLOCK</a><br>
+0x028 SegmentTableLock : <a href="./_RTL_SRWLOCK.html">_RTL_SRWLOCK</a><br>
+0x030 Allocate : Ptr64 void* <br>
+0x038 Free : Ptr64 void <br>
+0x040 AllocatorContext : Ptr64 Void<br>
</font></body></html> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>metacoq-erasure: Not compatible </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.2 / metacoq-erasure - 1.0~beta2+8.11</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
metacoq-erasure
<small>
1.0~beta2+8.11
<span class="label label-info">Not compatible </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-02-06 22:40:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-06 22:40:21 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 <API key> of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matthieu.sozeau@inria.fr"
homepage: "https://metacoq.github.io/metacoq"
dev-repo: "git+https://github.com/MetaCoq/metacoq.git#coq-8.11"
bug-reports: "https://github.com/MetaCoq/metacoq/issues"
authors: ["Abhishek Anand <aa755@cs.cornell.edu>"
"Simon Boulier <simon.boulier@inria.fr>"
"Cyril Cohen <cyril.cohen@inria.fr>"
"Yannick Forster <forster@ps.uni-saarland.de>"
"Fabian Kunze <fkunze@fakusb.de>"
"Gregory Malecha <gmalecha@gmail.com>"
"Matthieu Sozeau <matthieu.sozeau@inria.fr>"
"Nicolas Tabareau <nicolas.tabareau@inria.fr>"
"Théo Winterhalter <theo.winterhalter@inria.fr>"
]
license: "MIT"
build: [
["sh" "./configure.sh"]
[make "-j%{jobs}%" "-C" "erasure"]
]
install: [
[make "-C" "erasure" "install"]
]
depends: [
"ocaml" {>= "4.07.1"}
"coq" {>= "8.11" & < "8.12~"}
"<API key>" {= version}
"coq-metacoq-pcuic" {= version}
"<API key>" {= version}
]
synopsis: "Implementation and verification of an erasure procedure for Coq"
description: """
MetaCoq is a meta-programming framework for Coq.
The Erasure module provides a complete specification of Coq's so-called
\"extraction\" procedure, starting from the PCUIC calculus and targeting
untyped call-by-value lambda-calculus.
The `erasure` function translates types and proofs in well-typed terms
into a dummy `tBox` constructor, following closely P. Letouzey's PhD
thesis.
"""
# url {
# checksum: "md5=<API key>"
url {
src: "https://github.com/MetaCoq/metacoq/archive/v1.0-beta2-8.11.tar.gz"
checksum: "sha256=<SHA256-like>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-metacoq-erasure.1.0~beta2+8.11 coq.8.8.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.2).
The following dependencies couldn't be met:
- coq-metacoq-erasure -> coq-metacoq-pcuic = 1.0~beta2+8.11 -> coq >= 8.11
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-erasure.1.0~beta2+8.11</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html> |
<header class="navbar navbar-inverse bs-docs-nav navbar-fixed-top" role="banner">
<div class="container ">
<div class="navbar-header">
<button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="./" class="navbar-brand">Bootstrap 3 Menu Generator</a>
</div>
<nav class="collapse navbar-collapse bs-navbar-collapse" role="navigation">
<ul class="nav navbar-nav">
<li>
<a href="#">Getting started</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li><a href="#">Separated link</a></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
<li>
<a href="#">Components</a>
</li>
<li>
<a href="#">JavaScript</a>
</li>
<li class="active">
<a href="#">Customize</a>
</li>
</ul>
</nav>
</div>
</header> |
import { testApiCall } from 'utils/testUtils';
import * as C from '../constants';
import * as actions from '../actions';
describe('Spa actions', () => {
testApiCall('<API key>', C.<API key>, actions);
testApiCall('updateUsersRequest', C.<API key>, actions);
testApiCall('<API key>', C.<API key>, actions);
describe('setReportKey', () => {
it('should set the report key', () => {
const key = 'test';
const expected = {
type: C.SET_REPORT_KEY,
payload: key,
};
expect(actions.setReportKey(key)).toEqual(expected);
});
});
describe('setReportFilter', () => {
it('should set the report filter', () => {
const filter = {
test: 'testing..',
};
const expected = {
type: C.SET_REPORT_FILTER,
payload: filter,
};
expect(actions.setReportFilter(filter)).toEqual(expected);
});
});
}); |
<!DOCTYPE html><html lang="en-us" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Wowchemy 5.0.0-beta.1 for Hugo">
<meta name="description" content="Head of Computational Biology">
<link rel="alternate" hreflang="en-us" href="http://lpantano.github.io/author/p.-sliz/">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<meta name="theme-color" content="#2962ff">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.9.0/css/academicons.min.css" integrity="sha512-W4yqoT1+8NLkinBLBZko+<API key>/<API key>/HRvg==" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="<API key>=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/<API key>=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/github.min.css" crossorigin="anonymous" title="hl-light">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.css" integrity="<API key>/<API key>==" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.2/lazysizes.min.js" integrity="<API key>+<API key>/XjTUg==" crossorigin="anonymous" async></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap">
<link rel="stylesheet" href="/css/wowchemy.min.<API key>.css">
<link rel="alternate" href="/author/p.-sliz/index.xml" type="application/rss+xml" title="My bits">
<link rel="manifest" href="/index.webmanifest">
<link rel="icon" type="image/png" href="/images/<API key>.png">
<link rel="apple-touch-icon" type="image/png" href="/images/<API key>.png">
<link rel="canonical" href="http://lpantano.github.io/author/p.-sliz/">
<meta property="twitter:card" content="summary">
<meta property="twitter:site" content="@lopantano">
<meta property="twitter:creator" content="@lopantano">
<meta property="og:site_name" content="My bits">
<meta property="og:url" content="http://lpantano.github.io/author/p.-sliz/">
<meta property="og:title" content="P. Sliz | My bits">
<meta property="og:description" content="Head of Computational Biology"><meta property="og:image" content="http://lpantano.github.io/images/<API key>.png">
<meta property="twitter:image" content="http://lpantano.github.io/images/<API key>.png"><meta property="og:locale" content="en-us">
<meta property="og:updated_time" content="2017-01-01T00:00:00+00:00">
<title>P. Sliz | My bits</title>
</head>
<body id="top" data-spy="scroll" data-offset="70" data-target="#TableOfContents" class="page-wrapper ">
<script src="/js/wowchemy-init.js"></script>
<aside class="search-results" id="search">
<div class="container">
<section class="search-header">
<div class="row no-gutters <API key> mb-3">
<div class="col-6">
<h1>Search</h1>
</div>
<div class="col-6 col-search-close">
<a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a>
</div>
</div>
<div id="search-box">
<input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
autocomplete="off" autocorrect="off" spellcheck="false" type="search" class="form-control">
</div>
</section>
<section class="<API key>">
<div id="search-hits">
</div>
</section>
</div>
</aside>
<div class="page-header">
<nav class="navbar navbar-expand-lg navbar-light <API key>" id="navbar-main">
<div class="container">
<div class="d-none d-lg-inline-flex">
<a class="navbar-brand" href="/">My bits</a>
</div>
<button type="button" class="navbar-toggler" data-toggle="collapse"
data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<div class="<API key> d-inline-flex d-lg-none">
<a class="navbar-brand" href="/">My bits</a>
</div>
<div class="navbar-collapse main-menu-item collapse <API key>" id="navbar-content">
<ul class="navbar-nav d-md-inline-flex">
<li class="nav-item">
<a class="nav-link " href="/#about"><span>Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#posts"><span>Posts</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#talks"><span>Talks</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#featured"><span>Publications</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#contact"><span>Contact</span></a>
</li>
</ul>
</div>
<ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2">
<li class="nav-item">
<a class="nav-link js-search" href="#" aria-label="Search"><i class="fas fa-search" aria-hidden="true"></i></a>
</li>
<li class="nav-item dropdown theme-dropdown">
<a href="#" class="nav-link" data-toggle="dropdown" aria-haspopup="true" aria-label="Display preferences">
<i class="fas fa-moon" aria-hidden="true"></i>
</a>
<div class="dropdown-menu">
<a href="#" class="dropdown-item js-set-theme-light">
<span>Light</span>
</a>
<a href="#" class="dropdown-item js-set-theme-dark">
<span>Dark</span>
</a>
<a href="#" class="dropdown-item js-set-theme-auto">
<span>Automatic</span>
</a>
</div>
</li>
</ul>
</div>
</nav>
</div>
<div class="page-body">
<div class="universal-wrapper pt-3">
<h1>P. Sliz</h1>
</div>
<section id="profile-page" class="pt-5">
<div class="container">
<div class="article-widget content-widget-hr">
<h3>Latest</h3>
<ul>
<li>
<a href="/publication/ransey-2017/">Comparative analysis of LIN28-RNA binding sites identified at single nucleotide resolution</a>
</li>
</ul>
</div>
</div>
</section>
</div>
<div class="page-footer">
<div class="container">
<footer class="site-footer">
<p class="powered-by">
</p>
<p class="powered-by">
Published with
<a href="https:
the free, <a href="https://github.com/wowchemy/<API key>" target="_blank" rel="noopener">
open source</a> website builder that empowers creators.
</p>
</footer>
</div>
</div>
<div id="modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Cite</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<pre><code class="tex hljs"></code></pre>
</div>
<div class="modal-footer">
<a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank">
<i class="fas fa-copy"></i> Copy
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank">
<i class="fas fa-download"></i> Download
</a>
<div id="modal-error"></div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/<API key>/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js" integrity="<API key>/<API key>=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js" integrity="<API key>/iI=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="<API key>/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/instant.page/5.1.0/instantpage.min.js" integrity="sha512-1+qUtKoh9XZW7j+<API key>+cvxXjP1Z54RxZuzstR/<API key>==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/highlight.min.js" integrity="sha512-TDKKr+<API key>+<API key>+Y+m2XVKyOCD85ybtlZDmw==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/r.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.js" integrity="<API key>/RgVdi/<API key>==" crossorigin="anonymous"></script>
<script>const code_highlighting = true;</script>
<script>
const search_config = {"indexURI":"/index.json","minLength":1,"threshold":0.3};
const i18n = {"no_results":"No results found","placeholder":"Search...","results":"results found"};
const content_type = {
'post': "Posts",
'project': "Projects",
'publication' : "Publications",
'talk' : "Talks",
'slides' : "Slides"
};
</script>
<script id="<API key>" type="text/x-template">
<div class="search-hit" id="summary-{{key}}">
<div class="search-hit-content">
<div class="search-hit-name">
<a href="{{relpermalink}}">{{title}}</a>
<div class="article-metadata search-hit-type">{{type}}</div>
<p class="<API key>">{{snippet}}</p>
</div>
</div>
</div>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="<API key>+<API key>=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="<API key>=" crossorigin="anonymous"></script>
<script src="/js/wowchemy.min.<API key>.js"></script>
</body>
</html> |
<!DOCTYPE html><html lang="en-us" >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="generator" content="Wowchemy 5.0.0-beta.1 for Hugo">
<meta name="description" content="Head of Computational Biology">
<link rel="alternate" hreflang="en-us" href="http://lpantano.github.io/author/ewan-m-smith/">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<meta name="theme-color" content="#2962ff">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.9.0/css/academicons.min.css" integrity="sha512-W4yqoT1+8NLkinBLBZko+<API key>/<API key>/HRvg==" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" integrity="<API key>=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/<API key>=" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/github.min.css" crossorigin="anonymous" title="hl-light">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.css" integrity="<API key>/<API key>==" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.2/lazysizes.min.js" integrity="<API key>+<API key>/XjTUg==" crossorigin="anonymous" async></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CRoboto:400,400italic,700%7CRoboto+Mono&display=swap">
<link rel="stylesheet" href="/css/wowchemy.min.<API key>.css">
<link rel="alternate" href="/author/ewan-m-smith/index.xml" type="application/rss+xml" title="My bits">
<link rel="manifest" href="/index.webmanifest">
<link rel="icon" type="image/png" href="/images/<API key>.png">
<link rel="apple-touch-icon" type="image/png" href="/images/<API key>.png">
<link rel="canonical" href="http://lpantano.github.io/author/ewan-m-smith/">
<meta property="twitter:card" content="summary">
<meta property="twitter:site" content="@lopantano">
<meta property="twitter:creator" content="@lopantano">
<meta property="og:site_name" content="My bits">
<meta property="og:url" content="http://lpantano.github.io/author/ewan-m-smith/">
<meta property="og:title" content="Ewan M Smith | My bits">
<meta property="og:description" content="Head of Computational Biology"><meta property="og:image" content="http://lpantano.github.io/images/<API key>.png">
<meta property="twitter:image" content="http://lpantano.github.io/images/<API key>.png"><meta property="og:locale" content="en-us">
<meta property="og:updated_time" content="2014-01-01T00:00:00+00:00">
<title>Ewan M Smith | My bits</title>
</head>
<body id="top" data-spy="scroll" data-offset="70" data-target="#TableOfContents" class="page-wrapper ">
<script src="/js/wowchemy-init.js"></script>
<aside class="search-results" id="search">
<div class="container">
<section class="search-header">
<div class="row no-gutters <API key> mb-3">
<div class="col-6">
<h1>Search</h1>
</div>
<div class="col-6 col-search-close">
<a class="js-search" href="#"><i class="fas fa-times-circle text-muted" aria-hidden="true"></i></a>
</div>
</div>
<div id="search-box">
<input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
autocomplete="off" autocorrect="off" spellcheck="false" type="search" class="form-control">
</div>
</section>
<section class="<API key>">
<div id="search-hits">
</div>
</section>
</div>
</aside>
<div class="page-header">
<nav class="navbar navbar-expand-lg navbar-light <API key>" id="navbar-main">
<div class="container">
<div class="d-none d-lg-inline-flex">
<a class="navbar-brand" href="/">My bits</a>
</div>
<button type="button" class="navbar-toggler" data-toggle="collapse"
data-target="#navbar-content" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<div class="<API key> d-inline-flex d-lg-none">
<a class="navbar-brand" href="/">My bits</a>
</div>
<div class="navbar-collapse main-menu-item collapse <API key>" id="navbar-content">
<ul class="navbar-nav d-md-inline-flex">
<li class="nav-item">
<a class="nav-link " href="/#about"><span>Home</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#posts"><span>Posts</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#talks"><span>Talks</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#featured"><span>Publications</span></a>
</li>
<li class="nav-item">
<a class="nav-link " href="/#contact"><span>Contact</span></a>
</li>
</ul>
</div>
<ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2">
<li class="nav-item">
<a class="nav-link js-search" href="#" aria-label="Search"><i class="fas fa-search" aria-hidden="true"></i></a>
</li>
<li class="nav-item dropdown theme-dropdown">
<a href="#" class="nav-link" data-toggle="dropdown" aria-haspopup="true" aria-label="Display preferences">
<i class="fas fa-moon" aria-hidden="true"></i>
</a>
<div class="dropdown-menu">
<a href="#" class="dropdown-item js-set-theme-light">
<span>Light</span>
</a>
<a href="#" class="dropdown-item js-set-theme-dark">
<span>Dark</span>
</a>
<a href="#" class="dropdown-item js-set-theme-auto">
<span>Automatic</span>
</a>
</div>
</li>
</ul>
</div>
</nav>
</div>
<div class="page-body">
<div class="universal-wrapper pt-3">
<h1>Ewan M Smith</h1>
</div>
<section id="profile-page" class="pt-5">
<div class="container">
<div class="article-widget content-widget-hr">
<h3>Latest</h3>
<ul>
<li>
<a href="/publication/meijer-2014/">Regulation of miRNA strand selection: follow the leader?</a>
</li>
</ul>
</div>
</div>
</section>
</div>
<div class="page-footer">
<div class="container">
<footer class="site-footer">
<p class="powered-by">
</p>
<p class="powered-by">
Published with
<a href="https:
the free, <a href="https://github.com/wowchemy/<API key>" target="_blank" rel="noopener">
open source</a> website builder that empowers creators.
</p>
</footer>
</div>
</div>
<div id="modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Cite</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<pre><code class="tex hljs"></code></pre>
</div>
<div class="modal-footer">
<a class="btn btn-outline-primary my-1 js-copy-cite" href="#" target="_blank">
<i class="fas fa-copy"></i> Copy
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href="#" target="_blank">
<i class="fas fa-download"></i> Download
</a>
<div id="modal-error"></div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha256-9/<API key>/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js" integrity="<API key>/<API key>=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js" integrity="<API key>/iI=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="<API key>/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/instant.page/5.1.0/instantpage.min.js" integrity="sha512-1+qUtKoh9XZW7j+<API key>+cvxXjP1Z54RxZuzstR/<API key>==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/highlight.min.js" integrity="sha512-TDKKr+<API key>+<API key>+Y+m2XVKyOCD85ybtlZDmw==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.2.0/languages/r.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.min.js" integrity="<API key>/RgVdi/<API key>==" crossorigin="anonymous"></script>
<script>const code_highlighting = true;</script>
<script>
const search_config = {"indexURI":"/index.json","minLength":1,"threshold":0.3};
const i18n = {"no_results":"No results found","placeholder":"Search...","results":"results found"};
const content_type = {
'post': "Posts",
'project': "Projects",
'publication' : "Publications",
'talk' : "Talks",
'slides' : "Slides"
};
</script>
<script id="<API key>" type="text/x-template">
<div class="search-hit" id="summary-{{key}}">
<div class="search-hit-content">
<div class="search-hit-name">
<a href="{{relpermalink}}">{{title}}</a>
<div class="article-metadata search-hit-type">{{type}}</div>
<p class="<API key>">{{snippet}}</p>
</div>
</div>
</div>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js" integrity="<API key>+<API key>=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js" integrity="<API key>=" crossorigin="anonymous"></script>
<script src="/js/wowchemy.min.<API key>.js"></script>
</body>
</html> |
#ifndef _QTNETWORK_H_
#define _QTNETWORK_H_
#include "QtNetwork/qauthenticator.h"
#include "QtNetwork/qhostaddress.h"
#include "QtNetwork/qhostinfo.h"
#include "QtNetwork/qnetworkinterface.h"
#include "QtNetwork/qnetworkproxy.h"
#include "QtNetwork/qurlinfo.h"
#include "QtNetwork/<API key>.h"
#include "QtNetwork/<API key>.h"
#include "QtNetwork/qnetworksession.h"
#include "QtNetwork/<API key>.h"
#include "QtNetwork/qftp.h"
#include "QtNetwork/qhttp.h"
#include "QtNetwork/qhttpmultipart.h"
#include "QtNetwork/<API key>.h"
#include "QtNetwork/qnetworkcookie.h"
#include "QtNetwork/qnetworkcookiejar.h"
#include "QtNetwork/qnetworkdiskcache.h"
#include "QtNetwork/qnetworkreply.h"
#include "QtNetwork/qnetworkrequest.h"
#include "QtNetwork/qssl.h"
#include "QtNetwork/qsslcertificate.h"
#include "QtNetwork/qsslcipher.h"
#include "QtNetwork/qsslconfiguration.h"
#include "QtNetwork/qsslerror.h"
#include "QtNetwork/qsslkey.h"
#include "QtNetwork/qsslsocket.h"
#include "QtNetwork/qabstractsocket.h"
#include "QtNetwork/qlocalserver.h"
#include "QtNetwork/qlocalsocket.h"
#include "QtNetwork/qtcpserver.h"
#include "QtNetwork/qtcpsocket.h"
#include "QtNetwork/qudpsocket.h"
#endif |
# Development Guide
In this document, we will introduce **ASP.NET Zero Power Tools** and explain it. ASP.NET Zero Power Tools minimizes the effort for creating CRUD pages. It generates all the layers from the database to the user interface by just defining an entity.
> ASP.NET Zero Power Tools supports ASP.NET Zero v5.0.0 and above versions.
## How To Use It?
You can use ASP.NET Zero Power Tools in two ways:
1. as a Visual Studio Extension
2. Using its DLL files directly with a command line.
Visual Studio Extension is available for Windows version of Visual Studio. Mac and Linux users can use DLL of ASP.NET Zero Power Tools to generate CRUD pages.
## How It Works?
DLLs (that are inside the ```aspnet-core\AspNetZeroRadTool``` folder in your solution) do all the work. The extension is just a user interface. Since the tool is built with .NET Core, **Mac** or **Linux** users can safely use it without the user interface.
Using ASP.NET Zero Power Tools on Mac and Linux requires a bit more effort. You have to create a [ JSON file](https://aspnetzero.com/Documents/<API key>) as input for code generation manually. For using ASP.NET Zero Power Power Tools in Mac or Linux, please check [Development Guide(Mac/Linux) document](<API key>).
Visual Studio extension of ASP.NET Zero Power Tools also uses this DLL file for code generation.
## Edit Pre-defined Templates
Power Tools uses text templates for code generation, and these templates are located inside ```/AspNetZeroRadTool/FileTemplates``` directory in your project's root directory. Each template is split into three files:
* **MainTemplate.txt**: Power Tools uses this template for main code generation.
* **PartialTemplates.txt**: Power Tools renders some placeholders in MainTemplate.txt conditionally. These conditional templates are stored in PartialTemplates.txt.
* **TemplateInfo.txt**: Stores information about the template like path and condition.
If you want to edit any file, copy it in the same directory and change it's an extension to ```.custom.txt``` from ```.txt```. For example, you can create ```MainTemplate.custom.txt``` to override ```MainTemplate.txt``` in the same directory. Please don't make any changes to the original templates.
## Create A New Template
You can also create new templates for code generation. Power Tools will generate new files based on your new templates during code generation. To create a new template, do the same process as editing a pre-defined template.
Power Tools discovers templates in the ```/FileTemplates``` directory every time it is run. So, restarting Power Tools will find your newly created templates.
## Change Destination Path Of New Files
To change the destination path of a template, find the template folder of it in "AspNetZeroRadTool/FileTemplates" directory and edit the content of **TemplateInfo.txt** file. |
// <API key>.h
// wetan-oc
typedef NS_ENUM(NSUInteger, WTcellButton) {
defaultButton_enum,
diffButton_enum,
nptButton_enum,
};
#import <UIKit/UIKit.h>
#import "WTAssignItemModel.h"
@protocol <API key> <NSObject>
@optional
- (void)assignButtonClick:(WTcellButton)type WTid:(NSString *)idstr value:(NSString *)value index:(NSUInteger )index;
@end
@interface <API key> : UITableViewCell
@property (strong, nonatomic) WTAssignItemModel *WTmodel;
@property (assign, nonatomic) NSUInteger index;
@property (assign, nonatomic) id<<API key>> delegate;
@end |
import assert from 'assert'
import { digest } from 'json-hash'
import * as is from './is'
// S.R. Petrick, "A Direct Determination of the Irredundant Forms of a Boolean Function from the Set of Prime Implicants"
// Technical Report AFCRC-TR-56-110, Air Force Cambridge Research Center, Cambridge, Mass., Apr. 1956.
export function patrics (minterms) {
// Get prime implicants.
let F = {}
for (let minterm of minterms) {
if (minterm[2] !== 'v') {
if (!F[minterm[0]]) {
F[minterm[0]] = minterm[3]
}
}
}
let P = []
let PO = {}
let alpha = '<API key>'
let ALPHA = '<API key>'
for (let k in F) {
let v = F[k]
let pk = k.split('').map(function (e, i) {
return { '0': ALPHA[i], '1': alpha[i], '-': null }[e] }
).filter((e) => e).join('')
P.push([ pk, v ])
for (let pi of v) {
PO[pi] = true
}
}
let PI = Object.keys(PO).map((e) => parseInt(e)).sort()
// console.log('P:')
// P.forEach(function (p, i) {
// console.log(`P${i}`, p[0], p[1].join(', '))
// console.log('PI:')
// console.log(PI)
let PR = PI.map(function (pi) {
let r = []
P.forEach(function (e, i) {
if (e[1].indexOf(pi) !== -1) {
r.push(i)
}
})
return r.map((e) => `P${e}`)
})
// console.log('PR:', PR.map((e) => `(${e.join(' + ')})`).join(' '))
let PM = PR.map((e) => e.map((f) => [f]))
while (PM.length > 1) {
let p = PM.pop()
p.forEach((e) => {
e.forEach((e2) => {
PM.forEach((f) => {
f.forEach((g) => {
if (g.indexOf(e2) === -1) {
g.push(e2)
}
})
})
})
})
}
// return PM[0].map((e) => e.join('')).join('+')
// console.log('PM0:', PM[0].map((e) => e.join('*')).join(' + '))
return PM[0].map((e) => {
return e.map((f) => {
return P[parseInt(f.substr(1))][0]
}).join('')
}).join('+')
}
export function patrics2 (minterms) {
let P = patrics(minterms)
let alpha = '<API key>'
let ALPHA = '<API key>'
let or = P.split('+').map(function (p) {
let and = p.split('').map((e) => alpha.indexOf(e)).filter((e) => e !== -1)
let nor = p.split('').map((e) => ALPHA.indexOf(e)).filter((e) => e !== -1)
let r = {}
if (and.length > 0) {
r.$and = and
}
if (nor.length > 0) {
r.$nor = nor
}
if (Object.keys(r).length > 0) {
return r
} else {
return null
}
})
if (or.length > 0) {
if (or.length === 1) {
return or[0]
} else {
return { $or: or }
}
} else {
return null
}
}
// Minterm expansion.
export function mintermexp (minterms) {
function diff (a, b) {
let r = []
let n = 0
let f = false
for (let i = 0; i < a.length; i++) {
if ((a[i] === '0' && b[i] === '1') || (a[i] === '1' && b[i] === '0')) {
r.push('-')
if (++n > 1) {
f = true
break
}
} else {
if (a[i] === b[i]) {
r.push(a[i])
} else {
f = true
break
}
}
}
if (f) {
return false
} else {
return r.join('')
}
}
function combine1 (i) {
let r = []
for (; i < minterms.length; i++) {
let o = minterms[i][1]
for (let j = i + 1; j < minterms.length; j++) {
let od = minterms[j][1] - o
if (od === 0) {
continue
}
if (od === 1) {
let d = diff(minterms[i][0], minterms[j][0])
if (d) {
let _1s = d.split('').filter((e) => e === '1').length
minterms[i][2] = 'v'
minterms[j][2] = 'v'
let k = []
for (let z of [ minterms[i][3], minterms[j][3] ]) {
for (let l of z) {
if (k.indexOf(l) === -1) {
k.push(l)
}
}
}
r.push([ d, _1s, ' ', k ])
}
} else {
break
}
}
}
// r.sort((a, b) => a[1] - b[1])
for (let e of r) {
minterms.push(e)
}
return i
}
{
let i = 0
while (true) {
let j = combine1(i)
if (i == j) {
break
} else {
i = j
}
}
}
}
// Generate initial minterms.
export function minterms (q, n) {
let r = []
for (let i = 0; i < 2 ** n; i++) {
// String binary representation.
let s = new Array(n).fill('0').map((e, j) => ((1 << j) & i) ? '1' : '0' ).join('')
// Number of 1s.
let _1s = s.split('').filter((e) => e === '1').length
if (itest(q, i)) {
r.push([ s, _1s, ' ', [ i ] ])
}
}
// Sort by count of 1s.
r.sort((a, b) => a[1] - b[1])
return r
}
export function itest2 (qa, qb, n) {
let r = true
for (let i = 0; i < 2 ** n; i++) {
let ra = itest(qa, i)
let rb = itest(qb, i)
if (ra !== rb) {
let s = new Array(n).fill('0').map((e, j) => ((1 << j) & i) ? '1' : '0' ).join('')
console.error(`${ra} !== ${rb} for ${s}`)
r = false
break
}
}
return r
}
// Perform query test using binary as input.
// @param [Object] q Index map query, ie. `{ $and: [ 0, { $or: [ 1, 2 ] } ] }`
// @param [Number] i Binary input, ie. `0b101` means 0 - true, 1 - false, 2 - true.
// @return [Boolean] True if criteria is satisfied, false otherwise.
export function itest (q, i) {
let r = false
if (is.number(q)) {
r = (1 << q) & i ? true : false
} else {
r = [ '$and', '$or', '$nor', '$not' ].every(
function (k) {
let r = true
if (is.none(q[k])) {
r = true
} else {
switch (k) {
case '$and':
r = q[k].every((e) => itest(e, i))
break
case '$or':
r = q[k].some((e) => itest(e, i))
break
case '$nor':
r = q[k].every((e) => !itest(e, i))
break
case '$not':
r = !itest(q[k], i)
break
}
}
return r
}
)
}
return r
}
// Map query to fragments.
export function map (q, f) {
let r = null
if (is.plain(q)) {
r = {}
let d = {}
// Split fragment and query parts.
for (let [ k, v ] of kvs(q)) {
if ([ '$and', '$or', '$nor' ].indexOf(k) !== -1) {
r[k] = map(v, f)
} else {
d[k] = v
}
}
if (!is.leaf(d)) {
let fd = f(d)
if (is.leaf(r)) {
r = fd
} else {
r = { $and: [ fd, r ] }
}
}
} else {
if (is.array(q)) {
r = q.map((e) => map(e, f))
} else {
r = f(q)
}
}
return r
}
export function unmap (q, fs) {
let r = null
if (is.plain(q)) {
r = {}
for (let [ k, v ] of kvs(q)) {
r[k] = unmap(v, fs)
}
} else {
if (is.array(q)) {
r = q.map((e) => unmap(e, fs))
} else {
r = fs[q][1]
}
}
return r
}
export function minimize (qr) {
let fs = []
let q = map(qr, (e) => {
let d = digest(e)
let i = fs.findIndex((f) => f[0] == d)
if (i === -1) {
i = fs.length
fs.push([ d, e ])
}
return i
})
let minterms_ = minterms(q, fs.length)
mintermexp(minterms_)
let p = patrics2(minterms_)
assert.ok((itest2(q, p, fs.length)))
let r = unmap(p, fs)
let rks = Object.keys(r)
if (rks.length === 1 && rks[0] === '$and' && r[rks[0]].length === 1) {
r = r[rks[0]][0]
}
return r
}
export function biconditional (a, b) {
return (!!a ^ !!b) ? false : true
}
// Decode query key from ' $foo' -> '$foo'. Encoding allows to refer to document
// attributes which would conflict with ops.
export function decoded (qk) {
let r = qk
let trim = false
loop:
for (let i = 0; i < qk.length; i++) {
switch (qk[i]) {
case ' ':
trim = true
continue loop
case '$':
if (trim) {
r = qk.substr(1)
}
break loop
default:
break loop
}
}
return r
}
// Arrize path by splitting 'foo.bar' -> [ 'foo', 'bar' ], unless string starts
// with ' ' then ' foo.bar' -> [ 'foo.bar' ].
export function split (a) {
let r = undefined
if (a[0] === ' ') {
r = [ a.substring(1) ]
} else {
r = a.split('.')
}
return r
}
// Resolve key path on an object.
export function resolve (a, path) {
let stack = split(path)
let last = []
if (stack.length > 0) {
last.unshift(stack.pop())
}
let k = undefined
let e = a
if (!is.none(e)) {
while (!is.none(k = stack.shift())) {
if (!is.none(e[k])) {
e = e[k]
} else {
stack.unshift(k)
break
}
}
}
// Pull all unresolved components into last.
while (!is.none((k = stack.pop()))) {
last.unshift(k)
}
return [ e, last ]
}
export function arrize (a) {
return Array.isArray(a) ? a : [ a ]
}
export function* kvs (a) {
if (is.object(a)) {
for (let k of Object.keys(a)) {
if (a.hasOwnProperty(k)) {
yield [k, a[k]]
}
}
}
} |
<?php
namespace NEWS\BlogBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class NEWSBlogBundle extends Bundle
{
} |
<?php
use Speelpenning\Authentication\User;
class UserControllerTest extends TestCase
{
/**
* @var User
*/
protected $user;
public function setUp()
{
parent::setUp();
$this->artisan('migrate:refresh');
$this->user = User::register('John Doe', 'john.doe@example.com', 'some-valid-password');
}
public function <API key>()
{
$this->visit(route('authentication::user.create'))
->see(trans('authentication::user.name'))
->see(trans('authentication::user.optional'))
->see(trans('authentication::user.email'))
->see(trans('authentication::user.password'))
->see(trans('authentication::user.<API key>'))
->see(trans('authentication::user.create'));
}
public function <API key>()
{
config(['authentication.registration.userName' => 'off']);
$this->visit(route('authentication::user.create'))
->dontSee('<label for="name">' . trans('authentication::user.name') . '</label>');
}
public function <API key>()
{
config(['authentication.registration.userName' => 'required']);
$this->visit(route('authentication::user.create'))
->see(trans('authentication::user.name'))
->dontSee(trans('authentication::user.optional'))
->press(trans('authentication::user.create'))
->see('The name field is required.');
}
public function <API key>()
{
$this->visit(route('authentication::user.create'))
->press(trans('authentication::user.create'))
->see('The email field is required.')
->see('The password field is required.');
}
public function <API key>()
{
$this->visit(route('authentication::user.create'))
->type('<API key>', 'email')
->press(trans('authentication::user.create'))
->see('The email must be a valid email address.');
}
public function <API key>()
{
$this->visit(route('authentication::user.create'))
->type($this->user->email, 'email')
->type($this->user->password, 'password')
->type($this->user->password, '<API key>')
->press(trans('authentication::user.create'));
$this->visit(route('authentication::user.create'))
->type($this->user->email, 'email')
->type($this->user->password, 'password')
->type($this->user->password, '<API key>')
->press(trans('authentication::user.create'))
->see('The email has already been taken.');
}
public function <API key>()
{
$this->visit(route('authentication::user.create'))
->type($this->user->password, 'password')
->press(trans('authentication::user.create'))
->see('The password confirmation does not match.');
}
public function <API key>()
{
$this->visit(route('authentication::user.create'))
->type(1234, 'password')
->type(1234, '<API key>')
->press(trans('authentication::user.create'))
->see('The password must be at least 8 characters.');
}
public function test<API key>()
{
config(['authentication.password.minLength' => 10]);
$this->visit(route('authentication::user.create'))
->type(1234, 'password')
->type(1234, '<API key>')
->press(trans('authentication::user.create'))
->see('The password must be at least 10 characters.');
}
public function <API key>()
{
config(['authentication.registration.redirectUri' => route('authentication::user.create')]);
$this->visit(route('authentication::user.create'))
->type($this->user->name, 'name')
->type($this->user->email, 'email')
->type($this->user->password, 'password')
->type($this->user->password, '<API key>')
->press(trans('authentication::user.create'))
->seePageIs(route('authentication::user.create'));
}
public function <API key>()
{
$this->visit(route('authentication::user.create'))
->type($this->user->name, 'name')
->type($this->user->email, 'email')
->press(trans('authentication::user.create'))
->seeInField('name', $this->user->name)
->seeInField('email', $this->user->email);
}
public function <API key>()
{
config(['authentication.registration.allowPublic' => 'false']);
$this->get(route('authentication::user.create'))
-><API key>(403);
}
} |
<?php
/*
Safe sample
input : use proc_open to read /tmp/tainted.txt
sanitize : cast via + = 0.0
construction : interpretation with simple quote
*/
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "/tmp/error-output.txt", "a")
);
$cwd = '/tmp';
$process = proc_open('more /tmp/tainted.txt', $descriptorspec, $pipes, $cwd, NULL);
if (is_resource($process)) {
fclose($pipes[0]);
$tainted = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
}
$tainted += 0.0 ;
$var = header("Location: pages/'$tainted'.php");
?> |
import React from 'react';
export default function NotFound() {
return (
<div className="main">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ETG.Orleans.Attributes;
using ETG.Orleans.CodeGen.Utils;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
namespace ETG.Orleans.CodeGen.CodeGenParticipants
{
using SF = SyntaxFactory;
public class SwmrGrainsGenerator : ICodeGenParticipant
{
private const string <API key> = "ReadReplicaCount";
private const string <API key> = "StatelessWorker";
private SemanticModel _semanticModel;
public async Task<CodeGenResult> CodeGen(Workspace workspace, Project project)
{
<API key> cu = SF.CompilationUnit();
var usings = new HashSet<string>();
bool copyUsings = false;
foreach (Document document in project.Documents)
{
SyntaxTree syntaxTree = await document.GetSyntaxTreeAsync();
_semanticModel = await document.<API key>();
IEnumerable<<API key>> classes =
syntaxTree.GetRoot().DescendantNodes().OfType<<API key>>();
foreach (var classNode in classes)
{
if (!RoslynUtils.IsPublic(classNode)) continue;
ITypeSymbol swmrInterface = FindSwmrInterface(classNode);
if (swmrInterface == null)
{
continue;
}
var namespaceNode = classNode.Parent as <API key>;
if (namespaceNode == null)
{
throw new Exception("A grain must be declared inside a namespace");
}
usings.UnionWith(syntaxTree.GetRoot().DescendantNodes().OfType<<API key>>().Select(usingDirective => usingDirective.Name.ToString()));
int replicaCount = GetReadReplicaCount(swmrInterface);
<API key> namespaceDclr = SF.<API key>(SF.IdentifierName(namespaceNode.Name.ToString())).WithUsings(namespaceNode.Usings);
namespaceDclr = namespaceDclr.AddMembers(
GenerateWriteGrain(classNode, swmrInterface, replicaCount),
GenerateReadGrain(classNode, swmrInterface, replicaCount),
<API key>(classNode, swmrInterface)
);
usings.UnionWith(namespaceNode.Usings.Select(@using => @using.Name.ToString()));
cu = cu.AddMembers(namespaceDclr);
// only copy the usings if at least one class was generated
copyUsings = true;
}
}
if (copyUsings)
{
usings.UnionWith(GetCommonUsings());
}
return new CodeGenResult(Formatter.Format(cu, workspace).ToString(), usings);
}
private <API key> <API key>(<API key> grainClass, ITypeSymbol swmrInterface)
{
string <API key> = SwmrUtils.<API key>(grainClass.Identifier.Text);
string <API key> = SwmrUtils.<API key>(swmrInterface.Name);
<API key> readReplicaGrain = <API key>(<API key>).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", <API key> }));
string grainStateTypeName = <API key>(grainClass);
readReplicaGrain = readReplicaGrain.AddMembers(SF.FieldDeclaration(SF.VariableDeclaration(SF.ParseTypeName(grainStateTypeName), SF.SeparatedList(new[] { SF.VariableDeclarator(SF.Identifier("State")) }))).AddModifiers(SF.Token(SyntaxKind.PrivateKeyword)));
readReplicaGrain = readReplicaGrain.AddMembers(<API key>(swmrInterface));
foreach (ISymbol member in swmrInterface.GetMembers())
{
IMethodSymbol methodSymbol = member as IMethodSymbol;
if (methodSymbol == null || !IsReadOnlyMethod(methodSymbol))
{
continue;
}
<API key> methodImpl = RoslynUtils.FindImplementation(methodSymbol, grainClass);
readReplicaGrain = readReplicaGrain.AddMembers(methodImpl.WithLeadingTrivia(SF.EndOfLine("")));
}
readReplicaGrain = readReplicaGrain.AddMembers(<API key>(grainStateTypeName));
return readReplicaGrain;
}
private static <API key> <API key>(ITypeSymbol swmrInterface)
{
return RoslynUtils.ParseMethod(string.Format(
@"
public override async Task OnActivateAsync()
{{
string grainId = SwmrUtils.GetGrainId(this.GetPrimaryKeyString());
{0} grain = GrainFactory.GetGrain<{0}>(grainId);
await SetState(await grain.GetState());
await base.OnActivateAsync();
}}", swmrInterface.Name));
}
public <API key> <API key>(string grainStateTypeName)
{
return RoslynUtils.ParseMethod(string.Format(
@"
public Task SetState(GrainState state)
{{
State = state as {0};
return TaskDone.Done;
}}", grainStateTypeName));
}
private static IEnumerable<string> GetCommonUsings()
{
return new[] { "System.Linq", "ETG.Orleans.Swmr", "System.Collections.Generic", "Orleans.Concurrency" };
}
private static <API key> GenerateReadGrain(<API key> grainClass, ITypeSymbol swmrInterface, int readReplicaCount)
{
string readGrainName = SwmrUtils.<API key>(grainClass.Identifier.Text);
string readerInterfaceName = SwmrUtils.<API key>(swmrInterface.Name);
<API key> readGrain = <API key>(readGrainName).WithAttributeLists(AttributeUtils.AttributeListList(AttributeUtils.Attribute(<API key>))).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", readerInterfaceName }));
readGrain = RoslynUtils.AddField(readGrain, "ITopology<string>", "_topology");
readGrain = readGrain.AddMembers(<API key>(readReplicaCount));
string <API key> = SwmrUtils.<API key>(swmrInterface.Name);
foreach (ISymbol member in swmrInterface.GetMembers())
{
IMethodSymbol methodSymbol = member as IMethodSymbol;
if (methodSymbol == null || !IsReadOnlyMethod(methodSymbol))
{
continue;
}
MethodInspector methodInspector = new MethodInspector(methodSymbol);
string parameters = "string sessionId";
if (methodInspector.MethodParams.Any())
{
parameters = string.Join(", ", methodInspector.MethodParams.Select(param => string.Format("{0} {1}", param.Value, param.Key))) + " ," + parameters;
}
var method = RoslynUtils.ParseMethod(string.Format(
@"
public {0} {1}({2})
{{
string sessionNode = _topology.GetNode(sessionId);
var readReplica = GrainFactory.GetGrain<{3}>(sessionNode);
return readReplica.{1}({4});
}}", methodInspector.ReturnType, methodInspector.MethodName, parameters, <API key>, string.Join(", ", methodInspector.MethodParams.Keys)));
readGrain =
readGrain.AddMembers(
method.WithLeadingTrivia(SF.EndOfLine("")));
}
return readGrain;
}
private static <API key> GenerateWriteGrain(<API key> grainClass, ITypeSymbol swmrInterface, int readReplicaCount)
{
string grainName = grainClass.Identifier.Text;
string writerGrainName = SwmrUtils.<API key>(grainName);
string writerInterfaceName = SwmrUtils.<API key>(swmrInterface.Name);
<API key> writerGrain = <API key>(writerGrainName).WithBaseList(RoslynUtils.BaseList(new[] { "Grain", writerInterfaceName }));
writerGrain = RoslynUtils.AddField(writerGrain, "ITopology<string>", "_topology");
writerGrain = writerGrain.AddMembers(<API key>(readReplicaCount));
string <API key> = SwmrUtils.<API key>(swmrInterface.Name);
foreach (ISymbol member in swmrInterface.GetMembers())
{
IMethodSymbol methodSymbol = member as IMethodSymbol;
if (methodSymbol == null || IsReadOnlyMethod(methodSymbol) || new MethodInspector(methodSymbol).MethodName == "GetState")
{
continue;
}
MethodInspector methodInspector = new MethodInspector(methodSymbol);
<API key> methodImpl = <API key>(methodInspector);
methodImpl = SwmrUtils.<API key>(methodImpl).AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.AsyncKeyword)).WithSemicolonToken(SF.Token(SyntaxKind.None));
BlockSyntax statmentBlock = SF.Block();
statmentBlock = AddStatement(statmentBlock, "string grainId = this.GetPrimaryKeyString();");
statmentBlock = AddStatement(statmentBlock, string.Format("{0} grain = GrainFactory.GetGrain<{0}>(grainId);", swmrInterface.Name));
statmentBlock = AddStatement(statmentBlock, String.Format("{0} await grain.{1}({2});", methodInspector.ReturnType != "Task"? "var result =" : "", methodInspector.MethodName, string.Join(", ", methodInspector.MethodParams.Keys)));
statmentBlock = AddStatement(statmentBlock, "GrainState state = await grain.GetState();");
statmentBlock = AddStatement(statmentBlock, "string sessionNode = _topology.GetNode(sessionId);");
statmentBlock = AddStatement(statmentBlock, "IEnumerable<string> otherNodes = _topology.Nodes.Where(node => node != sessionNode);");
<API key> forEachStatement = SF.ForEachStatement(
SF.PredefinedType(SF.Token(SyntaxKind.StringKeyword)),
SF.Identifier("node"),
SF.IdentifierName("otherNodes"),
SF.Block(SF.ParseStatement(<API key>(<API key>, @"node")))
);
statmentBlock = statmentBlock.AddStatements(forEachStatement);
statmentBlock =
AddStatement(statmentBlock, (string.Format("{0} {1}", "await",
<API key>(<API key>, @"sessionNode"))));
if (methodInspector.ReturnType != "Task")
{
statmentBlock = AddStatement(statmentBlock, "return result;");
}
methodImpl = methodImpl.WithBody(statmentBlock);
writerGrain = writerGrain.AddMembers(methodImpl);
}
return writerGrain;
}
private static BlockSyntax AddStatement(BlockSyntax statementBlock, string statement)
{
return statementBlock.AddStatements(SF.ParseStatement(statement + "\n"));
}
private static <API key> <API key>(int readReplicaCount)
{
return RoslynUtils.ParseMethod(string.Format(
@"
public override async Task OnActivateAsync()
{{
_topology = SwmrUtils.CreateTopology(this.GetPrimaryKeyString(), {0});
await base.OnActivateAsync();
}}", readReplicaCount));
}
private static <API key> <API key>(MethodInspector methodInspector)
{
<API key> methodDclr = SF.MethodDeclaration(SF.ParseTypeName(methodInspector.ReturnType), SF.Identifier(methodInspector.MethodName));
foreach (KeyValuePair<string, string> keyValuePair in methodInspector.MethodParams)
{
string paramType = keyValuePair.Value;
string paramName = keyValuePair.Key;
methodDclr = RoslynUtils.<API key>(methodDclr, RoslynUtils.CreateParameter(paramType, paramName));
}
return methodDclr;
}
private static bool IsReadOnlyMethod(IMethodSymbol methodSymbol)
{
return AttributeUtils.FindAttributeOfType(methodSymbol, typeof(ReadOnlyAttribute)) != null;
}
private static string <API key>(string grainInterfaceName, string grainIdVariableName)
{
return string.Format("GrainFactory.GetGrain<{0}>({1}).SetState(state);", grainInterfaceName, grainIdVariableName);
}
private static <API key> <API key>(string className)
{
return SF.ClassDeclaration(SF.Identifier(className)).AddModifiers(SF.Token(SyntaxKind.PublicKeyword));
}
private int GetReadReplicaCount(ITypeSymbol swmrInterface)
{
return Convert.ToInt32(FindSwrmAttribute(swmrInterface).NamedArguments.First(pair => pair.Key == <API key>).Value.Value);
}
private ITypeSymbol FindSwmrInterface(<API key> classNode)
{
if (classNode.BaseList != null)
{
foreach (BaseTypeSyntax type in classNode.BaseList.Types)
{
TypeInfo typeInfo = _semanticModel.GetTypeInfo(type.Type);
ITypeSymbol typeSymbol = typeInfo.Type;
if (typeSymbol != null)
{
if (FindSwrmAttribute(typeSymbol) != null)
{
return typeSymbol;
}
}
}
}
return null;
}
private string <API key>(<API key> classNode)
{
if (classNode.BaseList != null)
{
foreach (BaseTypeSyntax type in classNode.BaseList.Types)
{
TypeInfo typeInfo = _semanticModel.GetTypeInfo(type.Type);
INamedTypeSymbol typeSymbol = typeInfo.Type as INamedTypeSymbol;
if (typeSymbol != null)
{
if (typeSymbol.Name == "Grain")
{
return typeSymbol.TypeArguments.First().Name;
}
}
}
}
return null;
}
private static AttributeData FindSwrmAttribute(ISymbol typeSymbol)
{
return AttributeUtils.FindAttributeOfType(typeSymbol, typeof(<API key>));
}
}
} |
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using ASPNET.Models;
using System.Configuration;
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
namespace ASPNET
{
public partial class Startup
{
const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context, user manager and signin manager to use a single instance per request
app.<API key>(<API key>.Create);
app.<API key><<API key>>(<API key>.Create);
app.<API key><<API key>>(<API key>.Create);
app.<API key><<API key>>(<API key>.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.<API key>(new Cookie<API key>
{
AuthenticationType = <API key>.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new Cookie<API key>
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = <API key>.OnValidateIdentity<<API key>, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.<API key>(manager))
}
});
app.<API key>(<API key>.ExternalCookie);
// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.<API key>(<API key>.TwoFactorCookie, TimeSpan.FromMinutes(5));
// Enables the application to remember the second login verification factor such as phone or email.
// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
// This is similar to the RememberMe option when you log in.
app.<API key>(<API key>.<API key>);
// Uncomment the following lines to enable logging in with third party login providers
// Microsoft : Create application
//app.<API key>(
// clientId: "",
// clientSecret: "");
if (!string.IsNullOrEmpty(<API key>.AppSettings.Get("MicrosoftClientId")))
{
var msaccountOptions = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccount<API key>()
{
ClientId = <API key>.AppSettings.Get("MicrosoftClientId"),
Client<API key>.AppSettings.Get("<API key>"),
Provider = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccount<API key>()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:microsoftaccount:access_token", context.AccessToken, XmlSchemaString, "Microsoft"));
return Task.FromResult(0);
}
}
};
app.<API key>(msaccountOptions);
}
// Twitter : Create a new application
//app.Use<TwitterConsumerkey>(
// consumerKey: <API key>.AppSettings.Get("<TwitterConsumerkey>"),
// consumer<API key>.AppSettings.Get("<TwitterConsumerkey>"));
if (!string.IsNullOrEmpty(<API key>.AppSettings.Get("<TwitterConsumerkey>")))
{
var twitterOptions = new Microsoft.Owin.Security.Twitter.<TwitterConsumerkey>
{
ConsumerKey = <API key>.AppSettings.Get("<TwitterConsumerkey>"),
Consumer<API key>.AppSettings.Get("<TwitterConsumerkey>"),
Provider = new Microsoft.Owin.Security.Twitter.<TwitterConsumerkey>
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:<TwitterConsumerkey>", context.AccessToken, XmlSchemaString, "Twitter"));
return Task.FromResult(0);
}
}
};
app.Use<TwitterConsumerkey>(twitterOptions);
}
// Facebook : Create New App
//app.<API key>(
// appId: <API key>.AppSettings.Get("FacebookAppId"),
// app<API key>.AppSettings.Get("FacebookAppSecret"));
if (!string.IsNullOrEmpty(<API key>.AppSettings.Get("FacebookAppId")))
{
var facebookOptions = new Microsoft.Owin.Security.Facebook.Facebook<API key>
{
AppId = <API key>.AppSettings.Get("FacebookAppId"),
App<API key>.AppSettings.Get("FacebookAppSecret"),
Provider = new Microsoft.Owin.Security.Facebook.Facebook<API key>
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
foreach (var x in context.User)
{
var claimType = string.Format("urn:facebook:{0}", x.Key);
string claimValue = x.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook"));
}
return Task.FromResult(0);
}
}
};
facebookOptions.Scope.Add("email");
app.<API key>(facebookOptions);
}
// Google Plus : Create New App
app.<API key>(new GoogleO<API key>()
{
ClientId = <API key>.AppSettings.Get("GooglePlusClientID"),
Client<API key>.AppSettings.Get("<API key>")
});
}
}
} |
.navbar-inverse .navbar-brand {
color: #F0F0F0;
}
.navbar-inverse .navbar-toggle {
border-color: #0080FF;
}
.navbar-inverse .navbar-toggle:hover, .navbar-inverse .navbar-toggle:focus {
background-color: #0080FF;
}
.navbar-inverse {
background-image: linear-gradient(to bottom, #0080FF 0%, #0080B0 100%);
}
.navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .active > a {
background-image: linear-gradient(to bottom, #0080FF 0%, #0080B0 100%);
}
.navbar-brand, .navbar-inverse .navbar-nav > li > a {
color: #F0F0F0;
}
.btn {
padding: 4px 4px;
}
label.radio-item {
font-weight: normal;
margin-bottom: 0;
}
.page-header {
text-align: center;
font-size: 24px;
padding-bottom: 2px;
margin: 2px 0 2px;
border-bottom: 1px solid #eee;
}
div.up-right {
position: absolute;
right: 10px;
top: 60px;
}
div.up-left {
position: absolute;
left: 10px;
top: 60px;
}
.content {
margin-top: 50px;
}
.undecorated-link:hover {
text-decoration: none;
}
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
.ng-invalid.ng-dirty {
border-color: #FA787E;
}
.ng-valid.ng-dirty {
border-color: #78FA89;
} |
layout: default
permalink: /examples/repositories/changesets.html
title: Branch restrictions
# Changesets
Manage changesets resources on a repository. Unauthenticated calls for these resources only return values for public repositories.
Prepare:
{% include auth.md var_name="changesets" class_ns="Repositories\Changesets" %}
Get a list of changesets associated with a repository:
php
$changesets->all($account_name, $repo_slug, 'aea95f1', 20);
Get an individual changeset:
php
$changesets->get($account_name, $repo_slug, 'aea95f1');
Get statistics associated with an individual changeset:
php
$changesets->diffstat($account_name, $repo_slug, '4ba1a4a');
Get the diff associated with a changeset:
php
$changesets->diff($account_name, $repo_slug, '4ba1a4a');
Get the likes on an individual changeset
NOTE: Because of a ( [bug](https://bitbucket.org/gentlero/bitbucket-api/issue/1/<API key>) ) in the API,
implementation for this method is missing for the moment.
-
# Related:
* [Authentication]({{ site.url }}/examples/authentication.html)
* [Changeset comments](changesets/comments.html)
* [BB Wiki](https://confluence.atlassian.com/display/BITBUCKET/changesets+Resource#<API key>) |
## Compiling The DOM with Element Directives
*DOM compilation*`$compile`
`myDirective`
js
myModule.directive('myDirective', function() {
return {
};
});
*directive definition object*keyvaluekey`compile`*compilation function*
`compile`traversing DOM
js
myModule.directive('myDirective', function() {
return {
compile: function(element) {
}
};
});
DOM
angular2html
<my-directive></my-directive>
injector
js
function <API key>() {
var args = arguments;
return createInjector(['ng', function($compileProvider) {
$compileProvider.directive.apply($compileProvider, args);
}]);
}
moduleinjector:`ng``$compileProvider`
js
it('compiles element directives from a single element', function() {
var injector = <API key>('myDirective', function() {
return {
compile: function(element) {
element.data('hasCompiled', true);
}
};
});
injector.invoke(function($compile) {
var el = $('<my-directive></my-directive>');
$compile(el);
expect(el.data('hasCompiled')).toBe(true);
});
});
`CompileProvider`
`CompileProvider``$get``$compile`
js
this.$get = function() {
function compile($compileNodes) {
}
return compile;
};
DOM
`compile``compileNodes`
js
this.$get = function() {
function compile($compileNodes) {
return compileNodes($compileNodes);
}
function compileNodes($compileNodes) {
}
return compile;
};
`compileNodes`jQuery`collectDirectives`
js
function compileNodes($compileNodes) {
_.forEach($compileNodes, function(node) {
var directives = collectDirectives(node);
});
}
function collectDirectives(node) {
}
`collectDirectives`DOM
js
function collectDirectives(node) {
var directives = [];
var normalizedNodeName = _.camelCase(nodeName(node).toLowerCase());
addDirective(directives, normalizedNodeName);
return directives;
}
`nodeName``addDirective`
`nodeName``compile.js`DOMDOMjQuery
js
function nodeName(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
}
`addDirective``compile.js``$get``hasDirectives`
ibjector
js
function addDirective(directives, name) {
if (hasDirectives.hasOwnProperty(name)) {
directives.push.apply(directives, $injector.get(name + 'Directive'));
}
}
`push.apply``$injector``apply``directives`
`addDirective``$injector``$get`
js
this.$get = ['$injector', function($injector) {
}];
`compileNodes`
js
function compileNodes($compileNodes) {
_.forEach($compileNodes, function(node) {
var directives = collectDirectives(node);
<API key>(directives, node);
});
}
function <API key>(directives, compileNode) {
}
`compile`jQuery`compile`
js
function <API key>(directives, compileNode) {
var $compileNode = $(compileNode);
_.forEach(directives, function(directive) {
if (directive.compile) {
directive.compile($compileNode);
}
});
}
`compile.js`jQuery:
js
'use strict';
var _ = require('lodash');
var $ = require('jquery');
DOM
1.
2. `compile`
`compile.js`
js |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import os.path
import tokenize
from StringIO import StringIO
def find_fold_points(block):
"""
Returns a list of (start_row, end_row, indent) tuples that denote fold
locations. Basically anywhere that there's an indent.
"""
token_whitelist = (tokenize.NL,
tokenize.NEWLINE,
tokenize.INDENT,
tokenize.DEDENT,
tokenize.COMMENT,
)
# temporary code that allows for running a block or a full file
if os.path.isfile(block):
with open(block) as open_file:
token_block = tokenize.generate_tokens(open_file)
else:
token_block = tokenize.generate_tokens(StringIO(block).readline)
indent_level = 0
nl_counter = 0
comment_counter = 0
indents = []
result = []
for toknum, _, srowcol, _, _ in token_block:
# Account for comments at the start of a block and newlines at the
# end of a block.
if toknum == tokenize.NL:
nl_counter += 1
if toknum == tokenize.COMMENT:
comment_counter += 1
if toknum == tokenize.INDENT:
indent_level += 1
indents.append(srowcol[0] - 1 - comment_counter)
if toknum == tokenize.DEDENT:
# the next DEDENT belongs to the most recent INDENT, so we pop off
# the last indent from the stack
indent_level -= 1
matched_indent = indents.pop()
result.append((matched_indent,
srowcol[0] - 1 - nl_counter,
indent_level + 1))
if toknum not in token_whitelist:
nl_counter = 0
comment_counter = 0
if len(indents) != 0:
raise ValueError("Number of DEDENTs does not match number of INDENTs.")
return result
if __name__ == "__main__":
pass |
/* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Matrix data structure:
matrix = require( 'dstructs-matrix' ),
// Module to be tested:
binomcoef = require( './../lib/deepset.js' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'deepset binomcoef', function tests() {
it( 'should export a function', function test() {
expect( binomcoef ).to.be.a( 'function' );
});
it( 'should evaluate the binomcoef function when y is a scalar and deep set', function test() {
var data, actual, expected;
data = [
{'x':4},
{'x':6},
{'x':8},
{'x':10}
];
actual = binomcoef( data, 2, 'x' );
expected = [
{'x':6},
{'x':15},
{'x':28},
{'x':45}
];
assert.strictEqual( data, actual );
assert.deepEqual( data, expected );
// Custom separator...
data = [
{'x':[9,4]},
{'x':[9,6]},
{'x':[9,8]},
{'x':[9,10]}
];
data = binomcoef( data, 2, 'x/1', '/' );
expected = [
{'x':[9,6]},
{'x':[9,15]},
{'x':[9,28]},
{'x':[9,45]}
];
assert.deepEqual( data, expected );
});
it( 'should evaluate the binomcoef function when y is an array and deep set', function test() {
var data, actual, expected, y;
data = [
{'x':2},
{'x':4},
{'x':6},
{'x':8}
];
y = [ 8, 6, 4, 2 ];
actual = binomcoef( data, y, 'x' );
expected = [
{'x':0},
{'x':0},
{'x':15},
{'x':28}
];
assert.strictEqual( data, actual );
assert.deepEqual( data, expected );
// Custom separator...
data = [
{'x':[9,2]},
{'x':[9,4]},
{'x':[9,6]},
{'x':[9,8]}
];
data = binomcoef( data, y, 'x/1', '/' );
expected = [
{'x':[9,0]},
{'x':[9,0]},
{'x':[9,15]},
{'x':[9,28]}
];
assert.deepEqual( data, expected );
});
it( 'should return an empty array if provided an empty array', function test() {
var arr = [];
assert.deepEqual( binomcoef( arr, 1, 'x' ), [] );
assert.deepEqual( binomcoef( arr, 1, 'x', '/' ), [] );
});
it( 'should handle non-numeric values by setting the element to NaN', function test() {
var data, actual, expected, y;
// raising to a non-numeric value
data = [
{'x':[9,null]},
{'x':[9,1]},
{'x':[9,true]},
{'x':[9,3]}
];
actual = binomcoef( data, null, 'x.1' );
expected = [
{'x':[9,NaN]},
{'x':[9,NaN]},
{'x':[9,NaN]},
{'x':[9,NaN]}
];
assert.deepEqual( data, expected );
// raising to a scalar
data = [
{'x':[9,null]},
{'x':[9,1]},
{'x':[9,true]},
{'x':[9,3]}
];
actual = binomcoef( data, 1, 'x.1' );
expected = [
{'x':[9,NaN]},
{'x':[9,1]},
{'x':[9,NaN]},
{'x':[9,3]}
];
assert.deepEqual( data, expected );
data = [
{'x':[9,null]},
{'x':[9,1]},
{'x':[9,true]},
{'x':[9,3]}
];
y = [ 0, 1, 2, 3];
actual = binomcoef( data, y, 'x.1' );
expected = [
{'x':[9,NaN]},
{'x':[9,1]},
{'x':[9,NaN]},
{'x':[9,1]}
];
assert.deepEqual( data, expected );
data = [
{'x':[9,null]},
{'x':[9,1]},
{'x':[9,true]},
{'x':[9,3]}
];
y = new Int32Array( [0,1,2,3] );
actual = binomcoef( data, y, 'x.1' );
expected = [
{'x':[9,NaN]},
{'x':[9,1]},
{'x':[9,NaN]},
{'x':[9,1]}
];
assert.deepEqual( data, expected );
});
it( 'should throw an error if provided a matrix as y argument', function test() {
var data, y;
data = [
{'x':[9,0]},
{'x':[9,1]},
{'x':[9,2]},
{'x':[9,3]}
];
y = matrix( new Int32Array( [1,2,3,4] ), [2,2] );
expect( foo ).to.throw( Error );
function foo() {
binomcoef(data, y, 'x.1' );
}
});
}); |
// GlueMotorCore.h
// GlueMotorCore
#import <Foundation/Foundation.h>
@class GlueMotorCore;
#pragma mark - <API key>
@protocol <API key> <NSObject>
@optional
// called just before the next PWM cycle will be started so set the Pulse Width from this delegate method will minimize the latency
// NOTE: this delegate method will be called in Audio Queue thread, so don't call the UI related API from there.
- (void)<API key>:(GlueMotorCore *)glueMotor;
@end
#pragma mark - GlueMotorCore
@interface GlueMotorCore : NSObject
@property (weak, nonatomic) id<<API key>> delegate;
@property (nonatomic) BOOL <API key>;
+ (id)sharedInstance;
+ (NSUInteger)supportedServoCount;
// pulseWidth: in seconds (e.g. 0.0015 = 1.5ms = center position), 0.0 = PWM OFF
// servoIndex: 0 (L) or 1 (R)
- (void)setPulseWidth:(NSTimeInterval)pulseWidth forServo:(NSUInteger)servoIndex;
- (NSTimeInterval)pulseWidthForServo:(NSUInteger)servoIndex;
// value: 0.0 ~ 1.0
- (void)setPWMVolume:(float)volume;
@end |
# <API key>: true
class <API key>
include Sidekiq::Worker
def perform(survey_score_id, operator, weight)
survey_score = SurveyScore.find survey_score_id
score_datum = survey_score.score_data.where(operator: operator, weight: weight).first
score_datum ||= ScoreDatum.create(survey_score_id: survey_score_id, operator: operator, weight: weight)
survey_score.generate_score_data(score_datum)
end
end |
var _ = require('underscore');
var Move = require('../../models/move');
var Interaction = require('interaction');
module.exports = new Interaction({
run: function (options, cb) {
var move = new Move(_.pick(options, 'type'));
if (!move.isValid()) return cb(400);
var user = options.game.get('users').get(options.user);
if (!user) {
if (move.get('type') !== 'up') return cb(403);
user = options.game.spawn(options.user);
}
user.applyMove(move);
cb(null, move);
}
}); |
module Treetop
module Compiler
class Repetition < ParsingExpression
def compile(address, builder, parent_expression)
super
repeated_expression = parent_expression.atomic
begin_comment(parent_expression)
use_vars :result, :accumulator, :start_index
builder.loop do
<API key>
repeated_expression.compile(<API key>, builder)
builder.if__ <API key>? do
<API key>
end
builder.else_ do
builder.break
end
if max && !max.empty?
builder.if_ "#{accumulator_var}.size == #{max.text_value}" do
builder.break
end
end
end
end
def inline_module_name
parent_expression.inline_module_name
end
def <API key> parent_expression
assign_result "instantiate_node(#{node_class_name},input, #{start_index_var}...index, #{accumulator_var})"
<API key> parent_expression
end
end
class ZeroOrMore < Repetition
def compile(address, builder, parent_expression)
super
<API key> parent_expression
end_comment(parent_expression)
end
def max
nil
end
end
class OneOrMore < Repetition
def compile(address, builder, parent_expression)
super
builder.if__ "#{accumulator_var}.empty?" do
reset_index
assign_failure start_index_var
end
builder.else_ do
<API key> parent_expression
end
end_comment(parent_expression)
end
def max
nil
end
def expected
parent_expression.atomic.expected && '"at least one "+'+parent_expression.atomic.expected
end
end
class OccurrenceRange < Repetition
def compile(address, builder, parent_expression)
super
if !min.empty? && min.text_value.to_i != 0
# We got some, but fewer than we wanted. There'll be a failure reported already
builder.if__ "#{accumulator_var}.size < #{min.text_value}" do
reset_index
assign_failure start_index_var
end
builder.else_ do
clean_unsaturated
<API key> parent_expression
end
else
clean_unsaturated
<API key> parent_expression
end
end_comment(parent_expression)
end
# remove the last terminal_failure if we merely failed to reach the maximum
def clean_unsaturated
if !max.empty? && max.text_value.to_i > 0
builder.if_ "#{accumulator_var}.size < #{max.text_value}" do
builder << '@terminal_failures.pop' # Ignore the last failure.
end
end
end
def expected
parent_expression.atomic.expected && "at least #{min.text_value} "+parent_expression.atomic.expected
end
end
end
end |
html {
font-family: helvetica, arial, freesans, clean, sans-serif;
margin: 0;
}
body {
margin: 0;
}
#en_tete {
height: 40px;
font-size: small;
background-color: #fafafa;
background-image: -moz-linear-gradient(#fafafa, #eaeaea);
border-bottom: 1px solid #cacaca;
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 10px rgba(0, 0, 0, 0.1);
}
#en_tete .menu {
float: right;
}
#en_tete #login {
font-weight: bold;
}
#en_tete a {
color: inherit;
text-decoration: none;
}
#wrapper_contenu {
padding: 0.6em 1em;
}
#menu_lateral {
float: left;
width: 170px;
padding: 0.5em 0.8em;
font-size: small;
background-color: #fafafa;
background-image: -moz-linear-gradient(#fafafa, #eaeaea);
border: 1px solid #cacaca;
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.4), 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 4px 4px 4px 4px;
}
#menu_lateral ul {
margin: 0;
padding: 0;
list-style: none;
}
#menu_lateral li.titre {
font-weight: bold;
color: #4183c4;
text-shadow: 1px 1px 1px lightgray;
}
#menu_lateral a {
color: inherit;
text-decoration: none;
}
#menu_lateral a:hover {
color: #4183c4;
}
/**
* Contenu
*
**/
#contenu {
margin-left: 198px;
padding: 0.6em 1.2em;
}
#contenu h3 {
margin: 0 0 0.6em 0;
color: #4183c4;
text-shadow: 2px 2px 4px lightgray;
}
#contenu p {
text-indent: 1em;
}
form {
margin: 0;
padding: 0;
overflow: auto;
}
form.saisie_plein_ecran {
width: 780px;
}
form.saisie_plein_ecran #col_une_sur_deux {
width: 365px;
float: left;
clear: both;
}
form.saisie_plein_ecran #col_deux_sur_deux {
margin-left: 370px;
}
form.saisie_plein_ecran #col_etendue {
margin: 0.6em 0;
width: 100%;
clear: both;
}
form #titre_f {
margin-bottom: 0.2em;
padding: 0.2em;
border: solid 2px lightgray;
border-radius: 4px 4px 4px 4px;
background-image: -moz-linear-gradient(#eaeaea, #fafafa);
}
form #titre_f label {
font-weight: bold;
width: 70px;
}
form #titre_f input {
margin: 0 0 0 0.4em;
}
form #corps_f {
padding: 0.5em 0.8em;
overflow: auto;
border: solid 2px lightgray;
background-image: -moz-linear-gradient(#fafafa, #eaeaea);
/*background-color: #9cbc2c;*/
border-radius: 4px 4px 4px 4px;
}
form #pied_f {
margin-top: 0.2em;
padding: 1em;
background: -moz-linear-gradient(#fafafa, #eaeaea) repeat scroll 0 0 transparent;
border: solid 2px lightgray;
border-radius: 4px 4px 4px 4px;
}
input,
select,
textarea {
margin-bottom: 0.3em;
margin-left: 0.8em;
padding: 0.2em 0.3em;
font: inherit;
font-size: small;
border: 1px solid lightgray;
border-radius: 3px 3px 3px 3px;
background: url('../images/forms/bg-input.png') repeat-x left top #efefef;
}
input.colle,
select.colle,
textarea.colle {
margin: 0;
}
label.required {
font-weight: bold;
}
input:focus,
select:focus,
textarea:focus {
border-color: #4183c4;
box-shadow: 0 0 3px #0459b7;
outline: none; /* Pour Chrome */
background: #efefef;
}
input[type=submit] {
margin: 0;
color: inherit;
box-shadow: 2px 2px 1px #4b4b6b;
cursor: pointer;
}
input[type=submit]#b_oui:hover,
input[type=submit]#b_oui:focus {
border-color: lawngreen;
box-shadow: 0 0 15px lawngreen;
outline: none; /* Pour Chrome */
}
input[type=submit]#b_non:hover,
input[type=submit]#b_non:focus {
border-color: #aa3333;
box-shadow: 0 0 15px red;
outline: none; /* Pour Chrome */
}
input[type=submit]#b_normand:hover,
input[type=submit]#b_normand:focus {
border-color: darkorange;
box-shadow: 0 0 15px darkorange;
outline: none; /* Pour Chrome */
}
form label {
margin-top: 0.15em;
width: 110px;
display: block;
float: left;
font-size: small;
text-align: right;
color: #777777;
cursor: pointer;
}
label.focus {
color: #4183c4;
}
label.focus:after {
content: ' »';
color: #4183c4;
}
fieldset {
border: #9cbfea 2px solid;
border-color: rgba(156, 191, 234, .6);
border-radius: 5px;
background-color: #cbddf3;
background-color: rgba(203, 221, 243, .3);
}
fieldset legend {
font-weight: bold;
font-size: small;
color: #777777;
}
form table {
width: 100%;
/*border-collapse: collapse; Dans le html directement (cellspacing), pb avec border-radius*/
border: solid 2px lightgray;
border-bottom-width: 1px;
color: dimgray;
font-size: small;
border-radius: 3px;
}
form thead tr {
background-color: #cbddf3;
}
form thead tr th {
border-right: solid 1px lightgray;
border-bottom: solid 1px lightgray;
}
form th {
padding: 0.3em 0.6em;
}
form tbody tr {
border-bottom: solid 1px lightgray;
}
form td:not(:last-child) {
padding: 0.4em;
border-right: solid 1px lightgray;
}
form td {
border-bottom: solid 1px lightgray;
}
form table input,
form table select,
form table textarea {
margin: 0;
}
form input[type=number] {
text-align: right;
}
/**
* Divers
**/
.cache {
display: none;
} |
<?php
namespace Piplin\Bus\Observers;
use Illuminate\Contracts\Events\Dispatcher;
use Piplin\Bus\Events\<API key>;
use Piplin\Bus\Events\<API key>;
use Piplin\Models\ServerLog;
/**
* Event observer for ServerLog model.
*/
class ServerLogObserver
{
/**
* @var Dispatcher
*/
private $dispatcher;
/**
* @param Dispatcher $dispatcher
*/
public function __construct(Dispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Called when the model is updated.
*
* @param ServerLog $log
*/
public function updated(ServerLog $log)
{
$this->dispatcher->dispatch(new <API key>($log));
if ($log->isDirty('output')) {
$this->dispatcher->dispatch(new <API key>($log));
}
}
} |
using CameraControl.Core;
using CameraControl.Core.Classes;
using CameraControl.Core.Scripting.ScriptCommands;
using CameraControl.Devices;
using CameraControl.Devices.Classes;
using CameraControl.Plugins.<API key>;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MahApps.Metro.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Xml;
using Microsoft.WindowsAPICodePack.Dialogs;
using ImageMagick;
namespace Macrophotography.ViewModel
{
public class <API key> : MacroStackViewModel
{
#region Variables
private <API key><Prop> _Props = new <API key><Prop>();
private <API key><StackTask> _StackTasks = new <API key><StackTask>();
private <API key><<API key>> _TaskIndicatorCodes = new <API key><<API key>>(); // populate combos with
private <API key><<API key>> <API key> = new <API key><<API key>>(); // populate SubStacks combos with
private <API key><<API key>> <API key> = new <API key><<API key>>(); // populate SubStacks combos with
private <API key><<API key>> <API key> = new <API key><<API key>>(); // populate combos with
private <API key><<API key>> <API key> = new <API key><<API key>>(); // populate combos with
private <API key><string> _output = new <API key><string>();
private <API key> <API key> = new <API key>();
private <API key> <API key> = new <API key>();
private <API key> <API key> = new <API key>();
private <API key> <API key> = new <API key>();
private <API key> <API key> = new <API key>();
private StackTask _ActualStackTask = new StackTask();
private PluginSetting _pluginSetting;
private Process _ZereneProcess;
private int _EstimatedRadius = 10;
private int _SmoothingRadius = 5;
private int _ContrastThreshold = 90;
private bool _IsDMap;
private bool _IsDMap2 = true;
private bool _IsDMap3 = false;
private bool _IsProjetFolder;
/*private bool _IsSubStack;
private bool _IsNotSubStack;
private bool _IsStackSubs;
private bool _IsJustStackSubs;
private bool _IsNotJustStackSubs = true;
private bool _ProcessSubStacks;
private bool _SinglePassStack = true;*/
private bool _IsJpeg;
private bool _IsTiff = true;
private string _FileType = "tif";
private string _ProjetFolder = "";
/*private string _SourceFolder = "";
private string _SingleFolder = "";
private string _StacksFolder = "";
private string _SubStacksFolder = "";*/
//private string <API key> = ServiceProvider.Settings.DefaultSession.Name + "\\SubStacks";
private string _OutputImageNames;
private string _launchCommand;
private string _ZereneCommand;
private StringBuilder _taskName = new StringBuilder();
private int _Items;
private int _Stack_items = 20;
private int _Stack_overlap = 10;
private int _Stack_item = 0;
private int _Tasknumber = 0;
private int _ProgressBarValue = 0;
private int <API key> = 100;
//public int item = 0;
#endregion
#region <API key>
public <API key><Prop> Props
{
get { return _Props; }
set
{
_Props = value;
<API key>(() => Props);
}
}
public <API key><StackTask> StackTasks
{
get { return _StackTasks; }
set
{
_StackTasks = value;
<API key>(() => StackTasks);
}
}
public <API key><<API key>> TaskIndicatorCodes // populate combos with
{
get { return _TaskIndicatorCodes; }
set
{
_TaskIndicatorCodes = value;
<API key>(() => TaskIndicatorCodes);
}
}
public <API key><<API key>> <API key> // populate combos with
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public <API key><<API key>> <API key> // populate combos with
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public <API key><<API key>> <API key> // populate combos with
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public <API key><<API key>> <API key> // populate combos with
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public <API key><string> output // populate Output Log ListBox
{
get { return _output; }
set
{
_output = value;
<API key>(() => output);
}
}
public <API key> ActualTaskIndicator
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => ActualTaskIndicator);
}
}
public <API key> <API key>
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public <API key> <API key>
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public <API key> <API key>
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public <API key> <API key>
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}
public StackTask ActualStackTask
{
get { return _ActualStackTask; }
set
{
_ActualStackTask = value;
<API key>(() => ActualStackTask);
}
}
public PluginSetting PluginSetting
{
get
{
if (_pluginSetting == null)
{
_pluginSetting = ServiceProvider.Settings["CombineZp"];
}
return _pluginSetting;
}
}
public int EstimatedRadius
{
get { return _EstimatedRadius; }
set
{
_EstimatedRadius = value;
<API key>(() => EstimatedRadius);
}
}
public int SmoothingRadius
{
get { return _SmoothingRadius; }
set
{
_SmoothingRadius = value;
<API key>(() => SmoothingRadius);
}
}
public int ContrastThreshold
{
get { return _ContrastThreshold; }
set
{
_ContrastThreshold = value;
<API key>(() => ContrastThreshold);
}
}
public bool IsDMap
{
get { return _IsDMap; }
set
{
_IsDMap = value;
<API key>(() => IsDMap);
}
}
public bool IsDMap2
{
get { return _IsDMap2; }
set
{
_IsDMap2 = value;
<API key>(() => IsDMap2);
}
}
public bool IsDMap3
{
get { return _IsDMap3; }
set
{
_IsDMap3 = value;
<API key>(() => IsDMap3);
}
}
public bool IsProjetFolder
{
get { return _IsProjetFolder; }
set
{
_IsProjetFolder = value;
<API key>(() => IsProjetFolder);
}
}
/*public bool IsJustStackSubs
{
get { return _IsJustStackSubs; }
set
{
_IsJustStackSubs = value;
<API key>(() => IsJustStackSubs);
<API key>(() => IsNotJustStackSubs);
ProcessSubStacks = IsJustStackSubs | IsStackSubs ? true : false;
IsNotSubStack = IsJustStackSubs ? true : false;
IsStackSubs = IsJustStackSubs ? false : false;
}
}
public bool IsNotJustStackSubs
{
get { return _IsNotJustStackSubs; }
set
{
_IsNotJustStackSubs = value;
<API key>(() => IsNotJustStackSubs);
<API key>(() => IsJustStackSubs);
}
}
public bool IsSubStack
{
get { return _IsSubStack; }
set
{
_IsSubStack = value;
<API key>(() => IsSubStack);
<API key>(() => IsNotSubStack);
}
}
public bool IsNotSubStack
{
get { return _IsNotSubStack; }
set
{
_IsNotSubStack = value;
<API key>(() => IsNotSubStack);
<API key>(() => IsSubStack);
}
}
public bool IsStackSubs
{
get { return _IsStackSubs; }
set
{
_IsStackSubs = value;
<API key>(() => IsStackSubs);
<API key>(() => IsNotStackSubs);
ProcessSubStacks = IsJustStackSubs | IsStackSubs ? true : false;
}
}
public bool IsNotStackSubs
{
get { return !IsStackSubs; }
}
public bool ProcessSubStacks
{
get { return _ProcessSubStacks; }
set
{
_ProcessSubStacks = value;
<API key>(() => ProcessSubStacks);
}
}
public bool SinglePassStack
{
get { return _SinglePassStack; }
set
{
_SinglePassStack = value;
<API key>(() => SinglePassStack);
}
} */
public bool IsJpeg
{
get { return _IsJpeg; }
set
{
_IsJpeg = value;
<API key>(() => IsJpeg);
<API key>(() => IsTiff);
UpDateTiff();
}
}
public bool IsTiff
{
get { return _IsTiff; }
set
{
_IsTiff = value;
<API key>(() => IsTiff);
<API key>(() => IsJpeg);
UpDateTiff();
}
}
public string FileType
{
get { return _FileType; }
set
{
_FileType = value;
<API key>(() => FileType);
}
}
public string ProjetFolder
{
get { return _ProjetFolder; }
set
{
_ProjetFolder = value;
<API key>(() => ProjetFolder);
}
}
/*public string SourceFolder
{
get { return _SourceFolder; }
set
{
_SourceFolder = value;
<API key>(() => SourceFolder);
}
}
public string SingleFolder
{
get { return _SingleFolder; }
set
{
_SingleFolder = value;
<API key>(() => SingleFolder);
}
}
public string StacksFolder
{
get { return _StacksFolder; }
set
{
_StacksFolder = value;
<API key>(() => StacksFolder);
}
}
public string SubStacksFolder
{
get { return _SubStacksFolder; }
set
{
_SubStacksFolder = value;
<API key>(() => SubStacksFolder);
}
}*/
/*public string <API key>
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => <API key>);
}
}*/
public string OutputImageNames
{
get { return _OutputImageNames; }
set
{
_OutputImageNames = value;
<API key>(() => OutputImageNames);
}
}
public string launchCommand
{
get { return _launchCommand; }
set
{
_launchCommand = value;
<API key>(() => launchCommand);
}
}
public string ZereneCommand
{
get { return _ZereneCommand; }
set
{
_ZereneCommand = value;
<API key>(() => ZereneCommand);
}
}
/*public StringBuilder taskName
{
get { return _taskName; }
set
{
_taskName = value;
<API key>(() => taskName);
}
}*/
public int Stack_items // Number of Photos in each SubSlab
{
get { return _Stack_items; }
set
{
_Stack_items = value;
<API key>(() => Stack_items);
}
}
public int Stack_item // Actual Photo in the SubSlab
{
get { return _Stack_item; }
set
{
_Stack_item = value;
<API key>(() => Stack_item);
}
}
public int Stack_overlap // Number of Photos of overlap
{
get { return _Stack_overlap; }
set
{
_Stack_overlap = value;
<API key>(() => Stack_overlap);
}
}
public int Items // Total Number of Photos to Stack ("Files" Collection)
{
get { return _Items; }
set
{
_Items = value;
<API key>(() => Items);
}
}
public int Tasknumber // Total Number of SubSlabTasks
{
get { return _Tasknumber; }
set
{
_Tasknumber = value;
<API key>(() => Tasknumber);
}
}
public int ProgressBarValue
{
get { return _ProgressBarValue; }
set
{
_ProgressBarValue = value;
<API key>(() => ProgressBarValue);
}
}
public int ProgressBarMaxValue
{
get { return <API key>; }
set
{
<API key> = value;
<API key>(() => ProgressBarMaxValue);
}
}
#endregion
#region Commands
public RelayCommand UpDateDMapCommand { get; set; }
public RelayCommand UpDateDMap2Command { get; set; }
public RelayCommand UpDateDMap3Command { get; set; }
public RelayCommand <API key> { get; set; }
public RelayCommand <API key> { get; set; }
public RelayCommand AddTaskCommand { get; set; }
public RelayCommand DeleteTaskCommand { get; set; }
public RelayCommand MoveUpTaskCommand { get; set; }
public RelayCommand MoveDownTaskCommand { get; set; }
public RelayCommand MakeBatchCommand { get; set; }
public RelayCommand OpenBatchCommand { get; set; }
public RelayCommand CopyBatchCommand { get; set; }
public CameraControl.Core.Classes.RelayCommand<object> SelectAllCommand { get; private set; }
public CameraControl.Core.Classes.RelayCommand<object> SelectNoneCommand { get; private set; }
public CameraControl.Core.Classes.RelayCommand<object> SelectInverCommand { get; private set; }
public RelayCommand <API key> { get; set; }
/*public RelayCommand <API key> { get; set; }
public RelayCommand <API key> { get; set; }
public RelayCommand <API key> { get; set; }*/
public RelayCommand <API key> { get; set; }
#endregion
#region Classes
public class Prop
{
public string PropertyName { get; set; }
public string SubpropertyName { get; set; }
public string Subpropertyvalue { get; set; }
//public bool substack { get; set; }
}
public class StackTask
{
public string TaskName { get; set; }
public int TaskNumber { get; set; }
public int <API key> { get; set; }
public int <API key> { get; set; }
public int <API key> { get; set; }
public string SourceFolder { get; set; }
public string <API key> { get; set; }
public string ProjetFolder { get; set; }
public bool Substack { get; set; }
public string FileType { get; set; }
public int Number { get; set; }
public int Overlap { get; set; }
public int EstimatedRadius { get; set; }
public int SmoothingRadius { get; set; }
public int ContrastThreshold { get; set; }
}
public class <API key>
{
public String Text { get; set; }
public int Value { get; set; }
public String Name { get; set; }
}
public class <API key>
{
public String Text { get; set; }
public int Value { get; set; }
}
public class <API key>
{
public String Text { get; set; }
public int Value { get; set; }
}
#endregion
#region Task ListBox Management
public void NamingTask(string actualTaskIndicator)
{
taskName.Clear();
string taskSubs = IsNotSubStack == true ? "SimpleStack" : "SubStacks";
taskName.Append("Work");
taskName.Append(StackTasks.Count + 1);
taskName.Append(".- " + taskSubs + "_");
taskName.Append(actualTaskIndicator);
}
public void NamingSubTask(string actualTaskIndicator)
{
taskName.Clear();
taskName.Append("Work");
taskName.Append(StackTasks.Count + 1);
taskName.Append(".- Process SubStacks_");
taskName.Append(actualTaskIndicator);
}
private void AddTask()
{
if (IsProjetFolder == false | ProjetFolder != "")
{
if (IsJustStackSubs) // Just Stack SubStaks
{
if (StacksFolder != "" && SubStacksFolder != "" && StackTasks.Any(x => x.TaskName.Contains("SubStacks")))
{
NamingSubTask(<API key>.Name);
StackTasks.Add(new StackTask
{
TaskName = taskName.ToString(),
TaskNumber = StackTasks.Count,
<API key> = <API key>.Value,
<API key> = <API key>.Value,
//<API key> = ServiceProvider.Settings.DefaultSession.Name + "\\SubStacksOutput_" + StackTasks.Count.ToString(),
SourceFolder = StacksFolder,
<API key> = SubStacksFolder,
<API key> = <API key>.Value,
Substack = false,
FileType = FileType,
Number = Stack_items,
Overlap = Stack_overlap,
EstimatedRadius = EstimatedRadius,
SmoothingRadius = SmoothingRadius,
ContrastThreshold = ContrastThreshold
});
InfoAdd(<API key>.Name, FileType, EstimatedRadius, SmoothingRadius, ContrastThreshold);
}
else
{
}
}
else
{
if (IsSubStack)
{
if (IsStackSubs) // Make SubStacks + Process SubStacks
{
if (StacksFolder != "" && SubStacksFolder != "" && _tempdir != "")
{
NamingTask(<API key>.Name);
StackTasks.Add(new StackTask
{
TaskName = taskName.ToString(),
TaskNumber = StackTasks.Count,
<API key> = <API key>.Value,
<API key> = <API key>.Value,
SourceFolder = _tempdir,
<API key> = StacksFolder,
<API key> = <API key>.Value,
Substack = true,
FileType = FileType,
Number = Stack_items,
Overlap = Stack_overlap,
EstimatedRadius = EstimatedRadius,
SmoothingRadius = SmoothingRadius,
ContrastThreshold = ContrastThreshold
});
InfoAdd(<API key>.Name, FileType, EstimatedRadius, SmoothingRadius, ContrastThreshold);
NamingSubTask(<API key>.Name);
StackTasks.Add(new StackTask
{
TaskName = taskName.ToString(),
TaskNumber = StackTasks.Count,
<API key> = <API key>.Value,
<API key> = <API key>.Value,
SourceFolder = StacksFolder,
<API key> = SubStacksFolder,
//<API key> = ServiceProvider.Settings.DefaultSession.Name + "\\SubStacksOutput_" + StackTasks.Count.ToString(),
<API key> = <API key>.Value,
Substack = false,
FileType = FileType,
Number = Stack_items,
Overlap = Stack_overlap,
EstimatedRadius = EstimatedRadius,
SmoothingRadius = SmoothingRadius,
ContrastThreshold = ContrastThreshold
});
InfoAdd(<API key>.Name, FileType, EstimatedRadius, SmoothingRadius, ContrastThreshold);
}
else
{
OnProgressChange("Empty Folder Path ! ");
}
}
else // Just Make SubStacks
{
if (StacksFolder != "" && _tempdir != "")
{
NamingTask(<API key>.Name);
StackTasks.Add(new StackTask
{
TaskName = taskName.ToString(),
TaskNumber = StackTasks.Count,
<API key> = <API key>.Value,
<API key> = <API key>.Value,
SourceFolder = _tempdir,
<API key> = StacksFolder,
<API key> = <API key>.Value,
Substack = true,
FileType = FileType,
Number = Stack_items,
Overlap = Stack_overlap,
EstimatedRadius = EstimatedRadius,
SmoothingRadius = SmoothingRadius,
ContrastThreshold = ContrastThreshold
});
InfoAdd(<API key>.Name, FileType, EstimatedRadius, SmoothingRadius, ContrastThreshold);
}
else
{
OnProgressChange("Empty Folder Path ! ");
}
}
}
else // Make Single Pass Stack
{
if (_tempdir != "" && SingleFolder != "")
{
NamingTask(ActualTaskIndicator.Name);
StackTasks.Add(new StackTask
{
TaskName = taskName.ToString(),
TaskNumber = StackTasks.Count,
<API key> = <API key>.Value,
<API key> = <API key>.Value,
SourceFolder = _tempdir,
<API key> = SingleFolder,
<API key> = ActualTaskIndicator.Value,
Substack = false,
FileType = FileType,
Number = Stack_items,
Overlap = Stack_overlap,
EstimatedRadius = EstimatedRadius,
SmoothingRadius = SmoothingRadius,
ContrastThreshold = ContrastThreshold
});
InfoAdd(<API key>.Name, FileType, EstimatedRadius, SmoothingRadius, ContrastThreshold);
}
else
{
OnProgressChange("Empty Folder Path ! ");
}
}
}
}
}
private void DeleteTask()
{
StackTasks.Remove(ActualStackTask);
}
private void MoveUpTask()
{
int pos = StackTasks.IndexOf(ActualStackTask);
if (pos != 0) StackTasks.Move(pos, --pos);
}
private void MoveDownTask()
{
int pos = StackTasks.IndexOf(ActualStackTask);
if (pos != StackTasks.Count -1) StackTasks.Move(pos, ++pos);
}
#endregion
#region Folders
private void SetProjetFolder()
{
try
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
if (ProjetFolder != null | ProjetFolder != "")
{
ProjetFolder = ServiceProvider.Settings.DefaultSession.Folder + "\\ZereneProjet";
Directory.CreateDirectory(ProjetFolder);
}
dialog.SelectedPath = ProjetFolder;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
ProjetFolder = dialog.SelectedPath;
}
}
catch (Exception ex)
{
Log.Error("Error set ProjetFolder ", ex);
}
}
/*private void SetSingleFolder()
{
try
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
if (SingleFolder != null | SingleFolder != "")
{
SingleFolder = ServiceProvider.Settings.DefaultSession.Folder + "\\SinglePassStacks";
Directory.CreateDirectory(SingleFolder);
}
dialog.SelectedPath = SingleFolder;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
SingleFolder = dialog.SelectedPath;
}
}
catch (Exception ex)
{
Log.Error("Error set SingleFolder ", ex);
}
}
private void SetStacksFolder()
{
try
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
if (StacksFolder != null | StacksFolder != "")
{
StacksFolder = ServiceProvider.Settings.DefaultSession.Folder + "\\SubStacks";
Directory.CreateDirectory(StacksFolder);
}
dialog.SelectedPath = StacksFolder;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
StacksFolder = dialog.SelectedPath;
}
}
catch (Exception ex)
{
Log.Error("Error set StacksFolder ", ex);
}
}
private void SetSubStacksFolder()
{
try
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
if (SubStacksFolder != null | SubStacksFolder != "")
{
SubStacksFolder = ServiceProvider.Settings.DefaultSession.Folder + "\\StackSubStacks";
Directory.CreateDirectory(SubStacksFolder);
}
dialog.SelectedPath = SubStacksFolder;
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
SubStacksFolder = dialog.SelectedPath;
}
}
catch (Exception ex)
{
Log.Error("Error set SubStacksFolder ", ex);
}
}*/
#endregion
#region Make Zerene Batch XML File
private void PopulateCombos()
{
TaskIndicatorCodes.Add(new <API key> { Text = "Align & Stack All (PMax)", Value = 1, Name = "Ali&PMax" });
TaskIndicatorCodes.Add(new <API key> { Text = "Align & Stack All (DMap)", Value = 2, Name = "Ali&DMap" });
TaskIndicatorCodes.Add(new <API key> { Text = "Align All Frames", Value = 3, Name = "Ali" });
TaskIndicatorCodes.Add(new <API key> { Text = "Stack Selected (PMax)", Value = 4, Name = "SelecPMax" });
TaskIndicatorCodes.Add(new <API key> { Text = "Stack Selected (DMap)", Value = 5, Name = "SelecDMap" });
TaskIndicatorCodes.Add(new <API key> { Text = "Make Stereo Pair(s)", Value = 6, Name = "Stereo" });
TaskIndicatorCodes.Add(new <API key> { Text = "Mark Project as Demo", Value = 7, Name = "Demo" });
<API key>.Add(new <API key> { Text = "Stack Selected (PMax)", Value = 4, Name = "SelecPMax" });
<API key>.Add(new <API key> { Text = "Stack Selected (DMap)", Value = 5, Name = "SelecDMap" });
<API key>.Add(new <API key> { Text = "Make Stereo Pair(s)", Value = 6, Name = "Stereo" });
<API key>.Add(new <API key> { Text = "Align & Stack All (PMax)", Value = 1, Name = "Ali&PMax" });
<API key>.Add(new <API key> { Text = "Align & Stack All (DMap)", Value = 2, Name = "Ali&DMap" });
<API key>.Add(new <API key> { Text = "Make Stereo Pair(s)", Value = 6, Name = "Stereo" });
<API key>.Add(new <API key> { Text = "Do not save images separately (keep only in projects)", Value = 1 });
<API key>.Add(new <API key> { Text = "Save in source folders", Value = 2 });
/*var dialog = new System.Windows.Forms.OpenFileDialog();
dialog.InitialDirectory = _tempdir;
dialog.FileName = null;*/
string myPath = _tempdir;
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.FileName = myPath;
prc.Start();
}
private void CopyZereneBatchFile()
{
try
{
string SessionFolder = ServiceProvider.Settings.DefaultSession.Folder;
string fileName = "ZereneBatch.xml";
string sourcePath = _tempdir;
string targetPath = SessionFolder;
// Use Path class to manipulate file and directory paths.
string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);
// To copy a file to another location and
// overwrite the destination file if it already exists.
File.Copy(sourceFile, destFile, true);
}
catch (Exception ex)
{
Log.Error("Error copy ZereneBatchFile to Session Folder ", ex);
}
}
private void PopulatePreferences(int contrastThreshold, int estimatedRadius, int smoothingRadius, string fileType)
{
Props.Clear();
string BitsValue;
BitsValue = fileType=="tif" ? "16" : "8";
PreferenceAdd("<API key>", "BacklashMillimeters", "0.22");
PreferenceAdd("<API key>", "CommandLogging", "false");
PreferenceAdd("<API key>", "<API key>", "1.5875");
PreferenceAdd("<API key>", "EndPosition", "0");
PreferenceAdd("<API key>", "MaximumMmPerSecond", "2.0");
PreferenceAdd("<API key>", "<API key>", "3200");
PreferenceAdd("<API key>", "MovementRampTime", "2.0");
PreferenceAdd("<API key>", "NumberOfSteps", "5");
PreferenceAdd("<API key>", "PrecisionThreshold", "0.05");
PreferenceAdd("<API key>", "PrerunMillimeters", "0.0");
PreferenceAdd("<API key>", "RPPIndicatorLeft", "-100.0");
PreferenceAdd("<API key>", "RPPIndicatorRight", "+100.0");
PreferenceAdd("<API key>", "SettlingTime", "3.0");
PreferenceAdd("<API key>", "<API key>", "1");
PreferenceAdd("<API key>", "ShutterAfterTime", "2.0");
PreferenceAdd("<API key>", "ShutterBetweenTime", "1.0");
PreferenceAdd("<API key>", "ShutterPulseTime", "0.3");
PreferenceAdd("<API key>", "StartPosition", "0");
PreferenceAdd("<API key>", "StepSize", "0.1");
PreferenceAdd("<API key>", "<API key>", "1.0");
PreferenceAdd("<API key>", "StepSizesFile", "");
PreferenceAdd("AlignmentControl", "<API key>", "false");
PreferenceAdd("AlignmentControl", "<API key>", "false");
PreferenceAdd("AlignmentControl", "AllowRotation", "true");
PreferenceAdd("AlignmentControl", "AllowScale", "true");
PreferenceAdd("AlignmentControl", "AllowShiftX", "true");
PreferenceAdd("AlignmentControl", "AllowShiftY", "true");
PreferenceAdd("AlignmentControl", "<API key>", "false");
PreferenceAdd("AlignmentControl", "CorrectBrightness", "true");
PreferenceAdd("AlignmentControl", "MaxRelDegRotation", "20");
PreferenceAdd("AlignmentControl", "MaxRelPctScale", "20");
PreferenceAdd("AlignmentControl", "MaxRelPctShiftX", "20");
PreferenceAdd("AlignmentControl", "MaxRelPctShiftY", "20");
PreferenceAdd("AlignmentControl", "Order.Automatic", "false");
PreferenceAdd("AlignmentControl", "Order.NarrowFirst", "true");
PreferenceAdd("AllowReporting", "UsageStatistics", "false");
PreferenceAdd("BatchFileChooser", "LastDirectory", "");
PreferenceAdd("ColorManagement", "DebugPrintProfile", "false");
PreferenceAdd("ColorManagement", "InputOption", "UseAssumedProfile");
PreferenceAdd("ColorManagement", "InputOption.AssumedProfile", "Adobe RGB(1998)");
PreferenceAdd("ColorManagement", "ManageZSDisplays", "true");
PreferenceAdd("ColorManagement", "<API key>", "false");
PreferenceAdd("ColorManagement", "OutputOption", "CopyInput");
PreferenceAdd("DepthMapControl", "AlgorithmIdentifier", "1");
PreferenceAdd("DepthMapControl", "<API key>", "90.0");
PreferenceAdd("DepthMapControl", "<API key>", contrastThreshold.ToString() + ".0"); // Contrast Threshold
PreferenceAdd("DepthMapControl", "EstimationRadius", estimatedRadius.ToString()); //Estimation Radius
PreferenceAdd("DepthMapControl", "SaveDepthMapImage", "false");
PreferenceAdd("DepthMapControl", "<API key>", "");
PreferenceAdd("DepthMapControl", "SaveUsedPixelImages", "false");
PreferenceAdd("DepthMapControl", "SmoothingRadius", smoothingRadius.ToString()); //Smoothing Radius
PreferenceAdd("DepthMapControl", "<API key>", "false");
PreferenceAdd("DepthMapControl", "<API key>", "true");
PreferenceAdd("DepthMapControl", "<API key>", "0.5");
PreferenceAdd("FileIO", "<API key>", "false");
PreferenceAdd("Interpolator", "RenderingSelection", "Interpolator.Spline4x4");
PreferenceAdd("Interpolator", "ShowAdvanced", "false");
PreferenceAdd("LightroomPlugin", "<API key>", "");
PreferenceAdd("LightroomPlugin", "DefaultColorSpace", "AdobeRGB");
PreferenceAdd("LightroomPlugin", "<API key>", "");
PreferenceAdd("OutputImageNaming", "Template", "Slab {outseq} {method}");
PreferenceAdd("Precrop", "LimitsString", "");
PreferenceAdd("Precrop", "Selected", "false");
PreferenceAdd("<API key>", "LastDirectory", "");
PreferenceAdd("Prerotation", "Degrees", "0");
PreferenceAdd("Prerotation", "Selected", "false");
PreferenceAdd("Presize", "UserSetting.Scale", "1.0");
PreferenceAdd("Presize", "UserSetting.Selected", "false");
PreferenceAdd("Presize", "Working.Scale", "1.0");
PreferenceAdd("PyramidControl", "<API key>", "1");
PreferenceAdd("PyramidControl", "RetainUDRImage", "false");
PreferenceAdd("SaveImage", "BitsPerColor", BitsValue); //Tiff 8 vs 16 bits
PreferenceAdd("SaveImage", "CompressionQuality", "0.75"); //Jpeg file quallity
PreferenceAdd("SaveImage", "FileType", fileType); //Output File Type
PreferenceAdd("SaveImage", "<API key>", "true");
PreferenceAdd("SkewSequence", "FirstImage.MaximumShiftXPct", "-3.0");
PreferenceAdd("SkewSequence", "FirstImage.MaximumShiftYPct", "0.0");
PreferenceAdd("SkewSequence", "LastImage.MaximumShiftXPct", "3.0");
PreferenceAdd("SkewSequence", "LastImage.MaximumShiftYPct", "0.0");
PreferenceAdd("SkewSequence", "<API key>", "3");
PreferenceAdd("SkewSequence", "Selected", "false");
PreferenceAdd("StackingControl", "FrameSkipFactor", "1");
PreferenceAdd("StackingControl", "FrameSkipSelected", "false");
PreferenceAdd("StereoOrdering", "<API key>", "1");
PreferenceAdd("<API key>", "AcceptViaDelay", "false");
PreferenceAdd("<API key>", "<API key>", "2.0");
}
private void GenericTask(XmlTextWriter writer, int <API key>, string <API key>, int <API key>, bool substack, int number, int overlap)
{
Stack_item = 0;
//Tasknumber = !substack ? 1 : (Items / (number - overlap));
if (!substack)
{
Tasknumber = 1;
}
else
{
Tasknumber = Items / (number - overlap);
}
writer.WriteStartElement("Tasks");
writer.<API key>("length", Tasknumber.ToString());
for (int j = 0; j < Tasknumber; j++)
{
writer.WriteStartElement("Task");
writer.WriteStartElement("<API key>");
writer.<API key>("value", <API key>.ToString());
writer.WriteEndElement();
if (<API key> == 5 | <API key> == 4)
{
writer.WriteStartElement("<API key>");
writer.<API key>("value", <API key>);
writer.WriteEndElement();
}
PreferenceWrite(writer);
writer.WriteStartElement("TaskIndicatorCode");
writer.<API key>("value", <API key>.ToString());
writer.WriteEndElement();
if (substack == true)
{
writer.WriteStartElement("<API key>");
writer.<API key>("length", number.ToString());
for (int i = 0; i < number; i++)
{
if (Stack_item == Items)
{
break;
}
writer.WriteStartElement("SelectedInputIndex");
writer.<API key>("value", Stack_item.ToString());
writer.WriteEndElement();
Stack_item++;
//if (Stack_item == Items) return;
}
writer.WriteEndElement();
}
writer.WriteEndElement();
Stack_item -= overlap;
}
writer.WriteEndElement();
}
#endregion
public <API key>()
{
Output = new <API key><string>();
InitCommands();
PopulateCombos();
CreateTempDir(true);
<API key>();
ServiceProvider.FileTransfered += <API key>;
ServiceProvider.WindowsManager.Event += <API key>;
LoadZereneData();
UpDateDMapCommand = new RelayCommand(UpDateDMap);
UpDateDMap2Command = new RelayCommand(UpDateDMap2);
UpDateDMap3Command = new RelayCommand(UpDateDMap3);
<API key> = new RelayCommand(<API key>);
<API key> = new RelayCommand(UpDateStackItems);
AddTaskCommand = new RelayCommand(AddTask);
DeleteTaskCommand = new RelayCommand(DeleteTask);
MoveUpTaskCommand = new RelayCommand(MoveUpTask);
MoveDownTaskCommand = new RelayCommand(MoveDownTask);
MakeBatchCommand = new RelayCommand(MakeZereneBatchFile);
OpenBatchCommand = new RelayCommand(OpenZereneBatchFile);
CopyBatchCommand = new RelayCommand(CopyZereneBatchFile);
ReloadCommand = new RelayCommand(LoadZereneData);
PreviewCommand = new RelayCommand(Preview);
GenerateCommand = new RelayCommand(Generate);
StopCommand = new RelayCommand(Stop);
SelectAllCommand = new CameraControl.Core.Classes.RelayCommand<object>(delegate { ServiceProvider.Settings.DefaultSession.SelectAll(); });
SelectNoneCommand = new CameraControl.Core.Classes.RelayCommand<object>(delegate { ServiceProvider.Settings.DefaultSession.SelectNone(); });
SelectInverCommand = new CameraControl.Core.Classes.RelayCommand<object>(delegate { ServiceProvider.Settings.DefaultSession.SelectInver(); });
<API key> = new RelayCommand(SetProjetFolder);
<API key> = new RelayCommand(GetFileItemFormat);
}
public void LoadZereneData()
{
if (Session.Files.Count == 0 || ServiceProvider.Settings.SelectedBitmap.FileItem == null)
return;
var files = Session.GetSelectedFiles();
if (files.Count > 0)
{
Files = files;
}
else
{
Files = Session.GetSeries(ServiceProvider.Settings.SelectedBitmap.FileItem.Series);
}
Items = Files.Count;
}
private void <API key>(object sender, FileItem fileItem)
{
if (Files.Count > 0)
{
if (Files[0].Series != fileItem.Series)
{
Files.Clear();
}
}
Files.Add(fileItem);
}
private void <API key>(string cmd, object o)
{
}
public void UpDateDMap()
{
if (ActualTaskIndicator.Value == 2 || ActualTaskIndicator.Value == 5)
{
IsDMap = true;
}
else
IsDMap = false;
}
public void UpDateDMap2()
{
if (<API key>.Value == 5)
{
IsDMap2 = true;
}
else
IsDMap2 = false;
}
public void UpDateDMap3()
{
if (<API key>.Value == 5)
{
IsDMap3 = true;
}
else
IsDMap3 = false;
}
public void <API key>()
{
if (<API key>.Value == 103)
{
IsProjetFolder = true;
}
else
IsProjetFolder = false;
}
public void UpDateStackItems()
{
Stack_overlap = Stack_items / 2;
}
public void UpDateTiff()
{
FileType = IsTiff ? "tif" : "jpg";
OnProgressChange("OutPut format is: " + FileType);
}
#region Run Zerene Process
private void CreateTempDir(bool folder)
{
_tempdir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
if (folder == true) { Directory.CreateDirectory(_tempdir); }
OnProgressChange("Temporal Folder: " + _tempdir);
}
private void GetFileItemFormat()
{
foreach (FileItem fileItem in Files)
{
string source = fileItem.FileName;
MagickImageInfo info = new MagickImageInfo();
info.Read(source);
string format = info.Format.ToString();
string format2 = info.CompressionMethod.ToString();
OnProgressChange(fileItem.Name + " format is: " + format + "____" + format2);
}
}
public void CopyFiles(bool preview)
{
int counter = 0;
try
{
_filenames.Clear();
OnProgressChange("Copying files");
foreach (FileItem fileItem in Files)
{
OnProgressChange("Copying file " + fileItem.Name);
string source = preview ? fileItem.LargeThumb : fileItem.FileName;
MagickImageInfo info = new MagickImageInfo();
info.Read(source);
string format = info.Format.ToString();
if (format == "Jpeg")
{
string randomFile = Path.Combine(_tempdir, "image_" + counter.ToString("0000") + ".jpg");
<API key>.<API key>(fileItem, PluginSetting.<API key>, source, randomFile);
_filenames.Add(randomFile);
counter++;
}
if (format == "Tiff")
{
string randomFile = Path.Combine(_tempdir, "image_" + counter.ToString("0000") + ".tif");
using (MagickImage image = new MagickImage(source))
{
image.Format = MagickFormat.Tiff;
image.Write(randomFile);
}
_filenames.Add(randomFile);
counter++;
}
if (format != "Jpeg" && format != "Tiff")
{
OnProgressChange(fileItem.Name + "has invalid format, will not be copied");
}
if (_shouldStop)
{
OnActionDone();
return;
}
}
}
catch (Exception exception)
{
OnProgressChange("Error copy files " + exception.Message);
Log.Error("Error copy files ", exception);
_shouldStop = true;
}
}
private async void <API key>()
{
string userName = Environment.UserName;
string mLaunchCmdDir = "C:\\Users\\" + userName + "\\AppData\\Roaming\\ZereneStacker";
string fileName = "zerenstk.launchcmd";
string mLaunchCmdFile = Path.Combine(mLaunchCmdDir, fileName);
launchCommand = null;
try
{
using (StreamReader sr = new StreamReader(mLaunchCmdFile))
{
string line = await sr.ReadToEndAsync();
launchCommand = line;
}
}
catch (Exception exception)
{
OnProgressChange("Could not read the Zerene Command File" + exception.Message);
}
try
{
ZereneCommand = @"C:\Program Files\ZereneStacker\jre\bin\java.exe";
OnProgressChange("Zerene Command: " + ZereneCommand);
launchCommand = launchCommand.Replace(@"""C:\Program Files\ZereneStacker\jre\bin\javaw.exe""", ""); // to make SHOWPROGRESS lines available
launchCommand = launchCommand.Replace("-wasRestarted", ""); // to make SHOWPROGRESS lines available
string defaultCmd =
" -Xmx5000m -DjavaBits=64bitJava" +
" -Dlaunchcmddir=" + "\"" + mLaunchCmdDir + "\"" +
" -classpath \"C:\\Program Files\\ZereneStacker\\ZereneStacker.jar;" +
"C:\\Program Files\\ZereneStacker\\JREextensions\\*\"" +
" com.zerenesystems.stacker.gui.MainFrame";
launchCommand = defaultCmd;
launchCommand += " -noSplashScreen";
launchCommand += " -<API key>";
launchCommand += " -runMinimized";
launchCommand += " -<API key>=false";
launchCommand += " -<API key>";
launchCommand += " ";
launchCommand += _tempdir;
OnProgressChange("Launch Command: " + launchCommand);
}
catch (Exception exception)
{
OnProgressChange("Could not change Zerene Command File" + exception.Message);
}
}
public void ZereneStack()
{
try
{
OnProgressChange("Zerene is stacking images ..");
OnProgressChange("This may take few minutes too");
_resulfile = Path.Combine(_tempdir, Path.<API key>(Files[0].FileName) + Files.Count + ".jpg");
_resulfile = Path.Combine(Path.GetTempPath(), Path.GetFileName(_resulfile));
Process newprocess = new Process();
newprocess.StartInfo = new ProcessStartInfo()
{
FileName = ZereneCommand,
Arguments = launchCommand,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Minimized,
CreateNoWindow = true,
<API key> = true,
<API key> = true,
WorkingDirectory = Path.GetDirectoryName(_filenames[0])
};
newprocess.Start();
_ZereneProcess = newprocess;
newprocess.OutputDataReceived += <API key>;
newprocess.ErrorDataReceived += <API key>;
newprocess.BeginOutputReadLine();
newprocess.BeginErrorReadLine();
newprocess.WaitForExit();
/*if (File.Exists(_resulfile))
{
//string localfile = Path.Combine(Path.GetDirectoryName(_files[0].FileName),
// Path.GetFileName(_resulfile));
//File.Copy(_resulfile, localfile, true);
//ServiceProvider.Settings.DefaultSession.AddFile(localfile);
PreviewBitmap = BitmapLoader.Instance.LoadImage(_resulfile);
}
else
{
OnProgressChange("No output file something went wrong !");
}
_ZereneProcess = null;*/
}
catch (Exception exception)
{
OnProgressChange("Error copy files " + exception.Message);
Log.Error("Error copy files ", exception);
_shouldStop = true;
}
}
public void Init()
{
Output.Clear();
_shouldStop = false;
}
private void Preview()
{
Init();
Task.Factory.StartNew(PreviewTask);
}
private void Generate()
{
Init();
Task.Factory.StartNew(GenerateTask);
}
private void PreviewTask()
{
IsBusy = true;
CopyFiles(true);
if (!_shouldStop)
{
MakeZereneBatchFile();
CopyZereneBatchFile();
ZereneStack();
OnActionDone();
}
IsBusy = false;
}
private void GenerateTask()
{
IsBusy = true;
CopyFiles(false);
if (!_shouldStop)
{
MakeZereneBatchFile();
CopyZereneBatchFile();
ZereneStack();
}
/*if (File.Exists(_resulfile))
{
string newFile = Path.Combine(Path.GetDirectoryName(Files[0].FileName),
Path.<API key>(Files[0].FileName) + "_enfuse" + ".jpg");
newFile = PhotoUtils.GetNextFileName(newFile);
File.Copy(_resulfile, newFile, true);
if (ServiceProvider.Settings.DefaultSession.GetFile(newFile) == null)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
FileItem im = new FileItem(newFile);
im.Transformed = true;
ServiceProvider.Settings.DefaultSession.Files.Add(im);
}));
}
}*/
OnActionDone();
IsBusy = false;
}
private void Stop()
{
_shouldStop = true;
try
{
if (_ZereneProcess != null)
_ZereneProcess.Kill();
}
catch (Exception)
{
}
}
private void <API key>(object sender, <API key> e)
{
OnProgressChange(e.Data);
/*if (e.Data.Contains("SHOWPROGRESS: Done"))
{
//mProgressBar.setVisible(false);
}
else if (e.Data.Contains("SHOWPROGRESS: Show"))
{
//mProgressBar.setVisible(true);
}
else if (e.Data.Contains("SHOWPROGRESS: Indeterminate"))
{
//mProgressBar.setIndeterminate(true);
//mProgressBar.setStringPainted(false); // do not show progress as percent
} */
/*if (e.Data.Contains("SHOWPROGRESS: Max"))
{
string data = e.Data;
string lastFragment = data.Split('=').Last();
int val = int.Parse(lastFragment);
ProgressBarMaxValue = val;
//int max = int.Parse(e.Data.Replace("^.*=",""));
//mProgressBar.setMaximum(max);
//mProgressBar.setIndeterminate(false);
//mProgressBar.setStringPainted(true); // show progress as percent
} if (e.Data.Contains("SHOWPROGRESS: Current"))
{
string data = e.Data;
string lastFragment = data.Split('=').Last();
int val = int.Parse(lastFragment);
//int val = int.Parse(e.Data.Replace("^.*=", ""));
//mProgressBar.setValue(val);
//mProgressBar.setIndeterminate(false);
ProgressBarValue = val;
}*/
}
private void InfoAdd(string <API key>, string fileType, int estimatedRadius, int smoothingRadius, int contrastThreshold)
{
OnProgressChange("Added: " + <API key> + fileType + estimatedRadius.ToString() + smoothingRadius.ToString() + contrastThreshold.ToString());
}
#endregion
private void StackTaskWrite(XmlTextWriter writer, <API key> <API key>, string <API key>, <API key> taskIndicatorCode, int number, bool Is_substack)
{
int item = 0;
_Items = _filenames.Count;
for (int i = 0; i < _Items; i++)
writer.WriteStartElement("Task");
writer.WriteStartElement("<API key>");
writer.<API key>("value", <API key>.Value.ToString());
writer.WriteEndElement();
if (<API key>.Value == 5)
{
writer.WriteStartElement("<API key>");
writer.<API key>("value", <API key>);
writer.WriteEndElement();
}
PreferenceWrite(writer);
writer.WriteStartElement("TaskIndicatorCode");
writer.<API key>("value", taskIndicatorCode.Value.ToString());
writer.WriteEndElement();
if (Is_substack == true)
{
writer.WriteStartElement("<API key>");
writer.<API key>("length", number.ToString());
for (int j = 0; j < number; j++)
{
writer.WriteStartElement("SelectedInputIndex");
writer.<API key>("value", item.ToString());
writer.WriteEndElement();
item++;
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
private void AlignTask(XmlTextWriter writer)
{
writer.WriteStartElement("Task");
writer.WriteStartElement("<API key>");
writer.<API key>("value", "3");
writer.WriteEndElement();
//writer.WriteStartElement("Preferences");
//writer.WriteEndElement();
PreferenceWrite(writer);
writer.WriteStartElement("TaskIndicatorCode");
writer.<API key>("value", "3");
writer.WriteEndElement();
writer.WriteEndElement();
}
private void PMaxTask(XmlTextWriter writer)
{
writer.WriteStartElement("Task");
writer.WriteStartElement("<API key>");
writer.<API key>("value", "3");
writer.WriteEndElement();
//writer.WriteStartElement("Preferences");
//writer.WriteEndElement();
PreferenceWrite(writer);
writer.WriteStartElement("TaskIndicatorCode");
writer.<API key>("value", "1");
writer.WriteEndElement();
writer.WriteEndElement();
}
private void DMapTask(XmlTextWriter writer)
{
writer.WriteStartElement("Task");
writer.WriteStartElement("<API key>");
writer.<API key>("value", "3");
writer.WriteEndElement();
//writer.WriteStartElement("Preferences");
//writer.WriteEndElement();
PreferenceWrite(writer);
writer.WriteStartElement("TaskIndicatorCode");
writer.<API key>("value", "2");
writer.WriteEndElement();
writer.WriteEndElement();
}
private void TaskWrite2(XmlTextWriter writer)
{
writer.WriteStartElement("Task");
if (StackTasks != null)
{
foreach (var stacktask in StackTasks)
{
//writer.WriteStartElement(stacktask.PropertyName + "." + property.SubpropertyName);
//writer.<API key>("value", property.Subpropertyvalue);
//writer.WriteEndElement();
}
}
writer.WriteEndElement();
}
#endregion
}
} |
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {CacheableService} from './cacheable.service';
import {LoaderService} from './loader.service';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/forkJoin';
@Injectable()
export class ItemService extends CacheableService {
private base_path = '/data';
private extension = '.json';
constructor(
private http: Http,
private loader: LoaderService
) {
super();
}
getItem(path_parts: string[]): Observable<any> {
return this.getWithCache( this.build_path(path_parts), (path) => {
this.loader.start_request();
return this.http.get(path)
.map(response => {
this.loader.finish_request();
return response.json();
})
.catch(this.handleError)
});
}
getDescriptionChain(path_parts: string[]): Observable<any> {
let obs_chain: Observable<any>[] = [];
for (let i = path_parts.length - 1; i > 0; i
let desc_path = path_parts.slice(0, i);
desc_path.push('description');
obs_chain.unshift(this.getItem(desc_path));
}
return Observable.forkJoin(obs_chain);
}
private build_path(path_parts: string[]) {
return this.base_path + '/' + path_parts.join('/') + this.extension;
}
private handleError(error: any): Observable<string> {
this.loader.finish_request();
console.error('An error occurred', error);
return Observable.of(undefined);
}
} |
// This is a generated file. You can view the original //
// source in your browser if your browser supports source maps. //
// Source maps are supported by all recent versions of Chrome, Safari, //
// and Firefox, and by Internet Explorer 11. //
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var global = Package.meteor.global;
var meteorEnv = Package.meteor.meteorEnv;
/* Exports */
if (typeof Package === 'undefined') Package = {};
Package['mobile-experience'] = {};
})(); |
<!DOCTYPE html>
<HTML><head><TITLE>Manpage of CBQ</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">
</head>
<body>
<header class="site-header">
<div class="wrap"> <div class="site-title"><a href="/manpages/index.html">linux manpages</a></div>
<div class="site-description">{"type":"documentation"}</div>
</div>
</header>
<div class="page-content"><div class="wrap">
<H1>CBQ</H1>
Section: Linux (8)<BR>Updated: 8 December 2001<BR><A HREF="#index">Index</A>
<A HREF="/manpages/index.html">Return to Main Contents</A><HR>
<A NAME="lbAB"> </A>
<H2>NAME</H2>
CBQ - Class Based Queueing
<A NAME="lbAC"> </A>
<H2>SYNOPSIS</H2>
<B>tc qdisc ... dev</B>
dev
<B>( parent</B>
classid
<B>| root) [ handle </B>
major:
<B>] cbq avpkt</B>
bytes
<B>bandwidth</B>
rate
<B>[ cell </B>
bytes
<B>] [ ewma</B>
log
<B>] [ mpu</B>
bytes
<B>] </B>
<P>
<B>tc class ... dev</B>
dev
<B>parent </B>
major:[minor]
<B>[ classid </B>
major:minor
<B>] cbq allot</B>
bytes
<B>[ bandwidth </B>
rate
<B>] [ rate </B>
rate
<B>] prio</B>
priority
<B>[ weight</B>
weight
<B>] [ minburst </B>
packets
<B>] [ maxburst </B>
packets
<B>] [ ewma </B>
log
<B>] [ cell</B>
bytes
<B>] avpkt</B>
bytes
<B>[ mpu</B>
bytes
<B>] [ bounded isolated ] [ split</B>
handle
<B>& defmap</B>
defmap
<B>] [ estimator </B>
interval timeconstant
<B>]</B>
<P>
<A NAME="lbAD"> </A>
<H2>DESCRIPTION</H2>
Class Based Queueing is a classful qdisc that implements a rich
linksharing hierarchy of classes. It contains shaping elements as
well as prioritizing capabilities. Shaping is performed using link
idle time calculations based on the timing of dequeue events and
underlying link bandwidth.
<P>
<A NAME="lbAE"> </A>
<H2>SHAPING ALGORITHM</H2>
Shaping is done using link idle time calculations, and actions taken if
these calculations deviate from set limits.
<P>
When shaping a 10mbit/s connection to 1mbit/s, the link will
be idle 90% of the time. If it isn't, it needs to be throttled so that it
IS idle 90% of the time.
<P>
From the kernel's perspective, this is hard to measure, so CBQ instead
derives the idle time from the number of microseconds (in fact, jiffies)
that elapse between requests from the device driver for more data. Combined
with the knowledge of packet sizes, this is used to approximate how full or
empty the link is.
<P>
This is rather circumspect and doesn't always arrive at proper
results. For example, what is the actual link speed of an interface
that is not really able to transmit the full 100mbit/s of data,
perhaps because of a badly implemented driver? A PCMCIA network card
will also never achieve 100mbit/s because of the way the bus is
designed - again, how do we calculate the idle time?
<P>
The physical link bandwidth may be ill defined in case of not-quite-real
network devices like PPP over Ethernet or PPTP over TCP/IP. The effective
bandwidth in that case is probably determined by the efficiency of pipes
to userspace - which not defined.
<P>
During operations, the effective idletime is measured using an
exponential weighted moving average (EWMA), which considers recent
packets to be exponentially more important than past ones. The Unix
loadaverage is calculated in the same way.
<P>
The calculated idle time is subtracted from the EWMA measured one,
the resulting number is called 'avgidle'. A perfectly loaded link has
an avgidle of zero: packets arrive exactly at the calculated
interval.
<P>
An overloaded link has a negative avgidle and if it gets too negative,
CBQ throttles and is then 'overlimit'.
<P>
Conversely, an idle link might amass a huge avgidle, which would then
allow infinite bandwidths after a few hours of silence. To prevent
this, avgidle is capped at
<B>maxidle.</B>
<P>
If overlimit, in theory, the CBQ could throttle itself for exactly the
amount of time that was calculated to pass between packets, and then
pass one packet, and throttle again. Due to timer resolution constraints,
this may not be feasible, see the
<B>minburst</B>
parameter below.
<P>
<A NAME="lbAF"> </A>
<H2>CLASSIFICATION</H2>
Within the one CBQ instance many classes may exist. Each of these classes
contains another qdisc, by default
<B><A HREF="/manpages/index.html?8+tc-pfifo">tc-pfifo</A></B>(8).
<P>
When enqueueing a packet, CBQ starts at the root and uses various methods to
determine which class should receive the data. If a verdict is reached, this
process is repeated for the recipient class which might have further
means of classifying traffic to its children, if any.
<P>
CBQ has the following methods available to classify a packet to any child
classes.
<DL COMPACT>
<DT>(i)<DD>
<B>skb->priority class encoding.</B>
Can be set from userspace by an application with the
<B>SO_PRIORITY</B>
setsockopt.
The
<B>skb->priority class encoding</B>
only applies if the skb->priority holds a major:minor handle of an existing
class within this qdisc.
<DT>(ii)<DD>
tc filters attached to the class.
<DT>(iii)<DD>
The defmap of a class, as set with the
<B>split & defmap</B>
parameters. The defmap may contain instructions for each possible Linux packet
priority.
<P>
Each class also has a
<B>level.</B>
Leaf nodes, attached to the bottom of the class hierarchy, have a level of 0.
</DL>
<A NAME="lbAG"> </A>
<H2>CLASSIFICATION ALGORITHM</H2>
<P>
Classification is a loop, which terminates when a leaf class is found. At any
point the loop may jump to the fallback algorithm.
<P>
The loop consists of the following steps:
<DL COMPACT>
<DT>(i)<DD>
If the packet is generated locally and has a valid classid encoded within its
<B>skb->priority,</B>
choose it and terminate.
<P>
<DT>(ii)<DD>
Consult the tc filters, if any, attached to this child. If these return
a class which is not a leaf class, restart loop from the class returned.
If it is a leaf, choose it and terminate.
<DT>(iii)<DD>
If the tc filters did not return a class, but did return a classid,
try to find a class with that id within this qdisc.
Check if the found class is of a lower
<B>level</B>
than the current class. If so, and the returned class is not a leaf node,
restart the loop at the found class. If it is a leaf node, terminate.
If we found an upward reference to a higher level, enter the fallback
algorithm.
<DT>(iv)<DD>
If the tc filters did not return a class, nor a valid reference to one,
consider the minor number of the reference to be the priority. Retrieve
a class from the defmap of this class for the priority. If this did not
contain a class, consult the defmap of this class for the
<B>BEST_EFFORT</B>
class. If this is an upward reference, or no
<B>BEST_EFFORT </B>
class was defined,
enter the fallback algorithm. If a valid class was found, and it is not a
leaf node, restart the loop at this class. If it is a leaf, choose it and
terminate. If
neither the priority distilled from the classid, nor the
<B>BEST_EFFORT </B>
priority yielded a class, enter the fallback algorithm.
The fallback algorithm resides outside of the loop and is as follows.
<DT>(i)<DD>
Consult the defmap of the class at which the jump to fallback occured. If
the defmap contains a class for the
<B>priority</B>
of the class (which is related to the TOS field), choose this class and
terminate.
<DT>(ii)<DD>
Consult the map for a class for the
<B>BEST_EFFORT</B>
priority. If found, choose it, and terminate.
<DT>(iii)<DD>
Choose the class at which break out to the fallback algorithm occurred. Terminate.
The packet is enqueued to the class which was chosen when either algorithm
terminated. It is therefore possible for a packet to be enqueued *not* at a
leaf node, but in the middle of the hierarchy.
<P>
</DL>
<A NAME="lbAH"> </A>
<H2>LINK SHARING ALGORITHM</H2>
When dequeuing for sending to the network device, CBQ decides which of its
classes will be allowed to send. It does so with a Weighted Round Robin process
in which each class with packets gets a chance to send in turn. The WRR process
starts by asking the highest priority classes (lowest numerically -
highest semantically) for packets, and will continue to do so until they
have no more data to offer, in which case the process repeats for lower
priorities.
<P>
<B>CERTAINTY ENDS HERE, ANK PLEASE HELP</B>
<P>
Each class is not allowed to send at length though - they can only dequeue a
configurable amount of data during each round.
<P>
If a class is about to go overlimit, and it is not
<B>bounded</B>
it will try to borrow avgidle from siblings that are not
<B>isolated. </B>
This process is repeated from the bottom upwards. If a class is unable
to borrow enough avgidle to send a packet, it is throttled and not asked
for a packet for enough time for the avgidle to increase above zero.
<P>
<B>I REALLY NEED HELP FIGURING THIS OUT. REST OF DOCUMENT IS PRETTY CERTAIN</B>
<B>AGAIN.</B>
<P>
<A NAME="lbAI"> </A>
<H2>QDISC</H2>
The root qdisc of a CBQ class tree has the following parameters:
<P>
<DL COMPACT>
<DT>parent major:minor | root<DD>
This mandatory parameter determines the place of the CBQ instance, either at the
<B>root</B>
of an interface or within an existing class.
<DT>handle major:<DD>
Like all other qdiscs, the CBQ can be assigned a handle. Should consist only
of a major number, followed by a colon. Optional.
<DT>avpkt bytes<DD>
For calculations, the average packet size must be known. It is silently capped
at a minimum of 2/3 of the interface MTU. Mandatory.
<DT>bandwidth rate<DD>
To determine the idle time, CBQ must know the bandwidth of your underlying
physical interface, or parent qdisc. This is a vital parameter, more about it
later. Mandatory.
<DT>cell<DD>
The cell size determines he granularity of packet transmission time calculations. Has a sensible default.
<DT>mpu<DD>
A zero sized packet may still take time to transmit. This value is the lower
cap for packet transmission time calculations - packets smaller than this value
are still deemed to have this size. Defaults to zero.
<DT>ewma log<DD>
When CBQ needs to measure the average idle time, it does so using an
Exponentially Weighted Moving Average which smoothes out measurements into
a moving average. The EWMA LOG determines how much smoothing occurs. Defaults
to 5. Lower values imply greater sensitivity. Must be between 0 and 31.
A CBQ qdisc does not shape out of its own accord. It only needs to know certain
parameters about the underlying link. Actual shaping is done in classes.
<P>
</DL>
<A NAME="lbAJ"> </A>
<H2>CLASSES</H2>
Classes have a host of parameters to configure their operation.
<P>
<DL COMPACT>
<DT>parent major:minor<DD>
Place of this class within the hierarchy. If attached directly to a qdisc
and not to another class, minor can be omitted. Mandatory.
<DT>classid major:minor<DD>
Like qdiscs, classes can be named. The major number must be equal to the
major number of the qdisc to which it belongs. Optional, but needed if this
class is going to have children.
<DT>weight weight<DD>
When dequeuing to the interface, classes are tried for traffic in a
round-robin fashion. Classes with a higher configured qdisc will generally
have more traffic to offer during each round, so it makes sense to allow
it to dequeue more traffic. All weights under a class are normalized, so
only the ratios matter. Defaults to the configured rate, unless the priority
of this class is maximal, in which case it is set to 1.
<DT>allot bytes<DD>
Allot specifies how many bytes a qdisc can dequeue
during each round of the process. This parameter is weighted using the
renormalized class weight described above.
<P>
<DT>priority priority<DD>
In the round-robin process, classes with the lowest priority field are tried
for packets first. Mandatory.
<P>
<DT>rate rate<DD>
Maximum rate this class and all its children combined can send at. Mandatory.
<P>
<DT>bandwidth rate<DD>
This is different from the bandwidth specified when creating a CBQ disc. Only
used to determine maxidle and offtime, which are only calculated when
specifying maxburst or minburst. Mandatory if specifying maxburst or minburst.
<P>
<DT>maxburst<DD>
This number of packets is used to calculate maxidle so that when
avgidle is at maxidle, this number of average packets can be burst
before avgidle drops to 0. Set it higher to be more tolerant of
bursts. You can't set maxidle directly, only via this parameter.
<P>
<DT>minburst <DD>
As mentioned before, CBQ needs to throttle in case of
overlimit. The ideal solution is to do so for exactly the calculated
idle time, and pass 1 packet. However, Unix kernels generally have a
hard time scheduling events shorter than 10ms, so it is better to
throttle for a longer period, and then pass minburst packets in one
go, and then sleep minburst times longer.
<P>
The time to wait is called the offtime. Higher values of minburst lead
to more accurate shaping in the long term, but to bigger bursts at
millisecond timescales.
<P>
<DT>minidle<DD>
If avgidle is below 0, we are overlimits and need to wait until
avgidle will be big enough to send one packet. To prevent a sudden
burst from shutting down the link for a prolonged period of time,
avgidle is reset to minidle if it gets too low.
<P>
Minidle is specified in negative microseconds, so 10 means that
avgidle is capped at -10us.
<P>
<DT>bounded <DD>
Signifies that this class will not borrow bandwidth from its siblings.
<DT>isolated<DD>
Means that this class will not borrow bandwidth to its siblings
<P>
<DT>split major:minor & defmap bitmap[/bitmap]<DD>
If consulting filters attached to a class did not give a verdict,
CBQ can also classify based on the packet's priority. There are 16
priorities available, numbered from 0 to 15.
<P>
The defmap specifies which priorities this class wants to receive,
specified as a bitmap. The Least Significant Bit corresponds to priority
zero. The
<B>split</B>
parameter tells CBQ at which class the decision must be made, which should
be a (grand)parent of the class you are adding.
<P>
As an example, 'tc class add ... classid 10:1 cbq .. split 10:0 defmap c0'
configures class 10:0 to send packets with priorities 6 and 7 to 10:1.
<P>
The complimentary configuration would then
be: 'tc class add ... classid 10:2 cbq ... split 10:0 defmap 3f'
Which would send all packets 0, 1, 2, 3, 4 and 5 to 10:1.
<DT>estimator interval timeconstant<DD>
CBQ can measure how much bandwidth each class is using, which tc filters
can use to classify packets with. In order to determine the bandwidth
it uses a very simple estimator that measures once every
<B>interval</B>
microseconds how much traffic has passed. This again is a EWMA, for which
the time constant can be specified, also in microseconds. The
<B>time constant</B>
corresponds to the sluggishness of the measurement or, conversely, to the
sensitivity of the average to short bursts. Higher values mean less
sensitivity.
<P>
<P>
<P>
</DL>
<A NAME="lbAK"> </A>
<H2>SOURCES</H2>
<DL COMPACT>
<DT>o<DD>
Sally Floyd and Van Jacobson, "Link-sharing and Resource
Management Models for Packet Networks",
IEEE/ACM Transactions on Networking, Vol.3, No.4, 1995
<P>
<DT>o<DD>
Sally Floyd, "Notes on CBQ and Guarantee Service", 1995
<P>
<DT>o<DD>
Sally Floyd, "Notes on Class-Based Queueing: Setting
Parameters", 1996
<P>
<DT>o<DD>
Sally Floyd and Michael Speer, "Experimental Results
for Class-Based Queueing", 1998, not published.
<P>
<P>
<P>
</DL>
<A NAME="lbAL"> </A>
<H2>SEE ALSO</H2>
<B><A HREF="/manpages/index.html?8+tc">tc</A></B>(8)
<P>
<A NAME="lbAM"> </A>
<H2>AUTHOR</H2>
Alexey N. Kuznetsov, <<A HREF="mailto:kuznet@ms2.inr.ac.ru">kuznet@ms2.inr.ac.ru</A>>. This manpage maintained by
bert hubert <<A HREF="mailto:ahu@ds9a.nl">ahu@ds9a.nl</A>>
<P>
<P>
<P>
<HR>
<A NAME="index"> </A><H2>Index</H2>
<DL>
<DT><A HREF="#lbAB">NAME</A><DD>
<DT><A HREF="#lbAC">SYNOPSIS</A><DD>
<DT><A HREF="#lbAD">DESCRIPTION</A><DD>
<DT><A HREF="#lbAE">SHAPING ALGORITHM</A><DD>
<DT><A HREF="#lbAF">CLASSIFICATION</A><DD>
<DT><A HREF="#lbAG">CLASSIFICATION ALGORITHM</A><DD>
<DT><A HREF="#lbAH">LINK SHARING ALGORITHM</A><DD>
<DT><A HREF="#lbAI">QDISC</A><DD>
<DT><A HREF="#lbAJ">CLASSES</A><DD>
<DT><A HREF="#lbAK">SOURCES</A><DD>
<DT><A HREF="#lbAL">SEE ALSO</A><DD>
<DT><A HREF="#lbAM">AUTHOR</A><DD>
</DL>
<HR>
This document was created by
<A HREF="/manpages/index.html">man2html</A>,
using the manual pages.<BR>
Time: 05:34:30 GMT, December 24, 2015
</div></div>
</body>
</HTML> |
// Original from http://facebook.github.io/flux/docs/flux-utils.html#container
"use strict";
import {StoreGroup} from "material-flux";
import assert from "assert";
function assertBaseComponent(o) {
assert(
o.getStores,
'Components that use Container must implement `static getStores()`'
);
assert(
o.calculateState,
'Components that use Container must implement `static calculateState()`'
);
}
export default class Container {
/**
* Create Container of Base Component and return Container Component.
* @param Base
* @returns {React.Component}
*/
static create(Base) {
assertBaseComponent(Base);
// define as Container class
class ContainerComponent extends Base {
constructor(props) {
super(props);
this.state = Base.calculateState(null, props);
// initialize
this.<API key> = [];
}
componentDidMount() {
if (super.componentDidMount) {
super.componentDidMount();
}
var stores = Base.getStores();
// This tracks when any store has changed and we may need to update.
var changed = false;
var setChanged = () => {
changed = true;
};
// This adds subscriptions to stores. When a store changes all we do is
// set changed to true.
this.<API key> = stores.map(
store => store.onChange(setChanged)
);
// This callback is called after the dispatch of the relevant stores. If
// any have reported a change we update the state, then reset changed.
var callback = () => {
if (changed) {
this.setState(prevState => {
return Base.calculateState(prevState, this.props);
});
}
changed = false;
};
this._storeGroup = new StoreGroup(stores, callback);
}
<API key>(nextProps, nextContext) {
if (super.<API key>) {
super.<API key>(nextProps, nextContext);
}
// TODO: pure options?
// Finally update the state using the new props.
this.setState(prevState => Base.calculateState(prevState, nextProps));
}
<API key>() {
if (super.<API key>) {
super.<API key>();
}
this._storeGroup.release();
this.<API key>.forEach(removeEventListener => {
removeEventListener();
});
this.<API key> = [];
}
}
// Update the name of the container before returning.
var componentName = Base.displayName || Base.name;
ContainerComponent.displayName = 'Container(' + componentName + ')';
return ContainerComponent;
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace DevO2.Shared
{
public sealed class Compression
{
#region Metodos
public static bool ComprimirArchivo(string archivo, TipoCompresion tipo)
{
try
{
switch (tipo)
{
case TipoCompresion.Deflate: break;
case TipoCompresion.GZip: break;
}
}
catch (Exception ex)
{
}
return false;
}
public static bool ComprimirArchivos(string[] archivos, TipoCompresion tipo)
{
return false;
}
public static bool DescomprimirArchivo(string archivo, TipoCompresion tipo)
{
try
{
switch (tipo)
{
case TipoCompresion.Deflate: break;
case TipoCompresion.GZip: break;
}
}
catch (Exception ex)
{
}
return false;
}
public static bool <API key>(string[] archivos, TipoCompresion tipo)
{
return false;
}
#endregion
}
} |
package com.iyzipay.model;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
public class PaymentDetail {
private Long paymentId;
private Integer paymentStatus;
private String paymentRefundStatus;
private BigDecimal price;
private BigDecimal paidPrice;
private Integer installment;
private BigDecimal <API key>;
private BigDecimal <API key>;
private BigDecimal <API key>;
private BigDecimal iyziCommissionFee;
private String <API key>;
private Integer fraudStatus;
private String cardType;
private String cardAssociation;
private String cardFamily;
private String cardToken;
private String cardUserKey;
private String binNumber;
private String lastFourDigits;
private String basketId;
private String currency;
private String connectorName;
private String authCode;
private boolean threeDS;
private String phase;
private String acquirerBankName;
private Integer mdStatus;
private String hostReference;
private Date createdDate;
private Date updatedDate;
private String orderId;
private List<RefundDetail> cancels;
private List<PaymentTxDetail> itemTransactions;
public Long getPaymentId() {
return paymentId;
}
public void setPaymentId(Long paymentId) {
this.paymentId = paymentId;
}
public Integer getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(Integer paymentStatus) {
this.paymentStatus = paymentStatus;
}
public String <API key>() {
return paymentRefundStatus;
}
public void <API key>(String paymentRefundStatus) {
this.paymentRefundStatus = paymentRefundStatus;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getPaidPrice() {
return paidPrice;
}
public void setPaidPrice(BigDecimal paidPrice) {
this.paidPrice = paidPrice;
}
public Integer getInstallment() {
return installment;
}
public void setInstallment(Integer installment) {
this.installment = installment;
}
public BigDecimal <API key>() {
return <API key>;
}
public void <API key>(BigDecimal <API key>) {
this.<API key> = <API key>;
}
public BigDecimal <API key>() {
return <API key>;
}
public void <API key>(BigDecimal <API key>) {
this.<API key> = <API key>;
}
public BigDecimal <API key>() {
return <API key>;
}
public void <API key>(BigDecimal <API key>) {
this.<API key> = <API key>;
}
public BigDecimal <API key>() {
return iyziCommissionFee;
}
public void <API key>(BigDecimal iyziCommissionFee) {
this.iyziCommissionFee = iyziCommissionFee;
}
public String <API key>() {
return <API key>;
}
public void <API key>(String <API key>) {
this.<API key> = <API key>;
}
public Integer getFraudStatus() {
return fraudStatus;
}
public void setFraudStatus(Integer fraudStatus) {
this.fraudStatus = fraudStatus;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getCardAssociation() {
return cardAssociation;
}
public void setCardAssociation(String cardAssociation) {
this.cardAssociation = cardAssociation;
}
public String getCardFamily() {
return cardFamily;
}
public void setCardFamily(String cardFamily) {
this.cardFamily = cardFamily;
}
public String getCardToken() {
return cardToken;
}
public void setCardToken(String cardToken) {
this.cardToken = cardToken;
}
public String getCardUserKey() {
return cardUserKey;
}
public void setCardUserKey(String cardUserKey) {
this.cardUserKey = cardUserKey;
}
public String getBinNumber() {
return binNumber;
}
public void setBinNumber(String binNumber) {
this.binNumber = binNumber;
}
public String getLastFourDigits() {
return lastFourDigits;
}
public void setLastFourDigits(String lastFourDigits) {
this.lastFourDigits = lastFourDigits;
}
public String getBasketId() {
return basketId;
}
public void setBasketId(String basketId) {
this.basketId = basketId;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public String getConnectorName() {
return connectorName;
}
public void setConnectorName(String connectorName) {
this.connectorName = connectorName;
}
public String getAuthCode() {
return authCode;
}
public void setAuthCode(String authCode) {
this.authCode = authCode;
}
public boolean isThreeDS() {
return threeDS;
}
public void setThreeDS(boolean threeDS) {
this.threeDS = threeDS;
}
public String getPhase() {
return phase;
}
public void setPhase(String phase) {
this.phase = phase;
}
public String getAcquirerBankName() {
return acquirerBankName;
}
public void setAcquirerBankName(String acquirerBankName) {
this.acquirerBankName = acquirerBankName;
}
public Integer getMdStatus() {
return mdStatus;
}
public void setMdStatus(Integer mdStatus) {
this.mdStatus = mdStatus;
}
public String getHostReference() {
return hostReference;
}
public void setHostReference(String hostReference) {
this.hostReference = hostReference;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public List<RefundDetail> getCancels() {
return cancels;
}
public void setCancels(List<RefundDetail> cancels) {
this.cancels = cancels;
}
public List<PaymentTxDetail> getItemTransactions() {
return itemTransactions;
}
public void setItemTransactions(List<PaymentTxDetail> itemTransactions) {
this.itemTransactions = itemTransactions;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
} |
(function($){
$(document).ready(function() {
pathArray = location.href.split( '/' );
protocol = pathArray[0];
host = pathArray[2];
baseUrl = protocol + '//' + host;
var ajaxCall = function() {
var item = $('#item').val();
if(item){
$.ajax({
type: "post",
url: baseUrl + "/stock/ajax/" + item,
cache: false,
success: function(response){
$('#result').html("");
var markup = '';
var obj = JSON.parse(response);
if(obj.length > 0){
var items = [];
$.each(obj, function(i,val){
markup = '<tr>'+'<td>'+ val.name +'</td>'+'<td>'+ val.season +'</td>'+'<td>'+ val.year +'</td>'+'<td>'+ val.size +'</td>';
markup = markup + '<td><input class="quantity" type="number" name="quantities[' + val.size_id + ']"></td>'+'</tr>';
items.push(markup);
});
$('#result').append.apply($('#result'), items);
}else{
$('#result').html($('<tr/>').text('No rows found'));
}
},
error: function(){
console.log('Ajax response error');
}
});
}
}
var ajaxSearch = function() {
if($("#item-search").val().length >= 0){
var item = $('#item-search').val()
$.ajax({
type: 'post',
url: baseUrl + '/stock/ajax_search',
data: {
item: item
},
success: function(response){
$('#result').html("");
var markup = '';
var obj = JSON.parse(response);
if(obj.length > 0){
var items = [];
$.each(obj, function(i,val){
markup = '<tr>'+'<td>'+ val.item +'</td>'+'<td>'+ val.season +'</td>'+'<td>'+ val.year +'</td>';
markup += '<td>'+ val.color +'</td>' + '<td>'+ val.size +'</td>' + '<td>' + val.quantity + '</td>'+'</tr>';
items.push(markup);
});
$('#result').append.apply($('#result'), items);
}else{
$('#result').html($('<tr/>').text('No rows found'));
}
},
error: function(){
console.log('Ajax response error');
}
});
}
}
ajaxCall();
$('#item').on('change', ajaxCall);
$('#default_quantity').on('change', function() {
$('.quantity').val($(this).val());
});
$('#item-search').keyup(function() {
ajaxSearch();
});
});
})(jQuery); |
import { Injectable } from '@angular/core';
import { Question } from '../classes/question';
@Injectable()
export class QuestionsService {
constructor() { }
questions: Question[] = [
{ "id": 1,
"title": "Откуда деньги у Навального?",
"date": new Date(2017, 7, 10),//'10.08.2017',
"answers": 3,
"rating": 80,
"views": 700 },
{ "id": 2,
"title": "Что делать с Кавказом?",
"date": new Date(2017, 7, 5),//'5.08.2017',
"answers": 3,
"rating": 100,
"views": 1000 },
{ "id": 3,
"title": "Как реформировать суды?",
"date": new Date(2017, 7, 15),//'15.08.2017'
"answers": 3,
"rating": 200,
"views": 900 },
{ "id": 4,
"title": "Кто будет платить пенсии?",
"date": new Date(2017, 6, 10),
"answers": 1,
"rating": 5,
"views": 800 },
{ "id": 5,
"title": "Где взял деньги на избирательную кампанию?",
"date": new Date(2017, 6, 11),//'15.08.2017'
"answers": 0,
"rating": 150,
"views": 850 },
{ "id": 6,
"title": "Сколько тебе заплатил госдеп?",
"date": new Date(2017, 6, 12),//'15.08.2017'
"answers": 0,
"rating": 2,
"views": 920 },
{ "id": 7,
"title": "Чей Крым - наш или не наш?",
"date": new Date(2017, 6, 13),//'15.08.2017'
"answers": 0,
"rating": 5000,
"views": 200 },
{ "id": 8,
"title": "Донбасс будешь сливать или нет?",
"date": new Date(2017, 6, 20),//'15.08.2017'
"answers": 0,
"rating": 190,
"views": 100 },
{ "id": 9,
"title": "Как реформировать правоохранительные органы?",
"date": new Date(2017, 7, 2),//'15.08.2017'
"answers": 0,
"rating": 10,
"views": 1000 },
{ "id": 10,
"title": "Что за люстрация и зачем?",
"date": new Date(2017, 7, 3),//'15.08.2017'
"answers": 0,
"rating": 2,
"views": 1 }
];
// Get all questions list
getList() {
return this.questions;
}
// Get question by id
getQuestion(id){
return this.questions.find((q) => q.id == id);
}
addQuestion(questionNew: Question){
// find next id
let maxIdQuestion = this.questions.reduce((prev,cur) => cur.id>prev.id?cur:prev,{id:-Infinity});
console.log('maxIdQuestion: ', maxIdQuestion);
questionNew.id = +maxIdQuestion.id + 1;
let date = new Date();
questionNew.date = new Date();
//push answer
console.log('Questions length before: ', this.questions.length);
this.questions.push(questionNew);
console.log('Questions length after: ', this.questions.length);
console.log('New question: ', this.getQuestion(questionNew.id));
return questionNew.id;
}
getListByRating(){
return this.questions.sort((a, b)=>{return b.rating - a.rating});
}
getListByDate(){
return this.questions.sort((a, b)=>{
return b.date > a.date ? 1 : -1;
});
}
getListUnanswered(){
return this.questions.filter((q)=>{return q.answers == 0});
}
updateQuestion(id){
let index = this.questions.findIndex((q) => q.id == id);
this.questions[index].answers ++;
}
} |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Éditeur 3D: 2DEV - 3D-KIT</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Éditeur 3D
 <span id="projectnumber">1.0</span>
</div>
<div id="projectbrief">Un simple éditeur 3D, projet de fin d&
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('<API key>.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">2DEV - 3D-KIT </div> </div>
</div><!--header
<div class="contents">
<div class="textblock"><ul>
<li><b>debut janvier</b> : Debut creation de l'interface graphique</li>
<li><b>fin janvier</b> : Fin/finition apportee au GUI et controle sur la rotation/scale des objets</li>
<li><b>debut fevrier</b> : Creation et utilisation de groupe d'objets</li>
<li><b>fin fevrier</b> : Creation de plusieurs zones/Suppression d'objets dans une zone</li>
<li><b>debut mars</b> : Portail liant les zones entre elles</li>
<li><b>fin mars</b> : Sauvegarde/chargement de mondes</li>
<li><b>debut avril</b> : Amelioration eclairage et test sur la fonction couleur</li>
<li><b>fin avril</b> : Amelioration/fix de bug</li>
<li><b>debut mars</b> : Documentation et Presentation</li>
</ul>
<h1>2ARC - Network stack</h1>
<ul>
<li><b>debut fevrier</b> : Apprentissage Raw socket/creation de library</li>
<li><b>fin fevrier</b> : Test connect ICMP</li>
<li><b>debut mars</b> : "Traduction" IP/MAC (composante ARP)</li>
<li><b>fin mars</b> : Debut test TCP/IP</li>
<li><b>debut avril</b> : Connexion en TCP/IP</li>
<li><b>fin avril</b> : Test envoie/reception donnee</li>
<li><b>debut mai</b> : TCP/IP avec plusieurs connexion</li>
<li><b>fin mai</b> : Amelioration/fix de bug</li>
<li><b>debut juin</b> : Documentation et Presentation</li>
</ul>
<h1>Liste de membres du groupes:</h1>
<table class="doxtable">
<tr>
<th align="center">ID </th><th align="left">Nom Prénom </th><th align="left">Compte Github </th></tr>
<tr>
<td align="center">169796 </td><td align="left">BEAL Corentin </td><td align="left"><a href="https://github.com/Aztyu"></a> </td></tr>
<tr>
<td align="center">169865 </td><td align="left">ROCHE Arnaud </td><td align="left"><a href="https://github.com/arnaud-roche">-roche</a> </td></tr>
<tr>
<td align="center">170408 </td><td align="left">STHEME de JUBECOURT Etienne </td><td align="left"><a href="https://github.com/etiennestm"></a> </td></tr>
<tr>
<td align="center">172320 </td><td align="left">ORIOL Guillaume </td><td align="left"><a href="https://github.com/devguillaume"></a> </td></tr>
<tr>
<td align="center">170535 </td><td align="left">GARDET Julien </td><td align="left"><a href="https://github.com/Jitrixis"></a> </td></tr>
<tr>
<td align="center">200184 </td><td align="left">CHIAPPINI Matthieu </td><td align="left"><a href="https://github.com/chiapipi"></a> </td></tr>
</table>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated on Sat Jul 25 2015 12:26:07 for Éditeur 3D by
<a href="http:
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.9.1 </li>
</ul>
</div>
</body>
</html> |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Method</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.5.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.5.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title=""></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: </em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/Activity.html">Activity</a></li>
<li><a href="../classes/ActivityController.html">ActivityController</a></li>
<li><a href="../classes/Constraint.html">Constraint</a></li>
<li><a href="../classes/<API key>.html"><API key></a></li>
<li><a href="../classes/Counter.html">Counter</a></li>
<li><a href="../classes/CounterController.html">CounterController</a></li>
<li><a href="../classes/CSVParser.html">CSVParser</a></li>
<li><a href="../classes/FacadeController.html">FacadeController</a></li>
<li><a href="../classes/FileManager.html">FileManager</a></li>
<li><a href="../classes/Main.html">Main</a></li>
<li><a href="../classes/Method.html">Method</a></li>
<li><a href="../classes/MethodController.html">MethodController</a></li>
<li><a href="../classes/Plan.html">Plan</a></li>
<li><a href="../classes/Planner.html">Planner</a></li>
<li><a href="../classes/Recommender.html">Recommender</a></li>
<li><a href="../classes/Slider.html">Slider</a></li>
<li><a href="../classes/SliderController.html">SliderController</a></li>
<li><a href="../classes/Subactivity.html">Subactivity</a></li>
<li><a href="../classes/<API key>.html"><API key></a></li>
<li><a href="../classes/TotalCounter.html">TotalCounter</a></li>
<li><a href="../classes/<API key>.html"><API key></a></li>
<li><a href="../classes/Weight.html">Weight</a></li>
<li><a href="../classes/WeightCollection.html">WeightCollection</a></li>
<li><a href="../classes/XMLParser.html">XMLParser</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/App.html">App</a></li>
<li><a href="../modules/Collections.html">Collections</a></li>
<li><a href="../modules/Constants.html">Constants</a></li>
<li><a href="../modules/Controllers.html">Controllers</a></li>
<li><a href="../modules/Main.html">Main</a></li>
<li><a href="../modules/Models.html">Models</a></li>
<li><a href="../modules/Plan.html">Plan</a></li>
<li><a href="../modules/UP.html">UP</a></li>
<li><a href="../modules/Util.html">Util</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1>Method Class</h1>
<div class="box meta">
<div class="foundat">
Defined in: <a href="../files/models.js.html#l254"><code>models.js:254</code></a>
</div>
Module: <a href="../modules/Models.html">Models</a><br>
Parent Module: <a href="../modules/UP.html">UP</a>
</div>
<div class="box intro">
</div>
<div id="classdocs" class="tabview">
<ul class="api-class-tabs">
<li class="api-class-tab index"><a href="#index">Index</a></li>
<li class="api-class-tab methods"><a href="#methods">Methods</a></li>
<li class="api-class-tab properties"><a href="#properties">Properties</a></li>
</ul>
<div>
<div id="index" class="api-class-tabpanel index">
<h2 class="off-left">Item Index</h2>
<div class="index-section methods">
<h3>Methods</h3>
<ul class="index-list methods">
<li class="index-item method">
<a href="#method_addWeight">addWeight</a>
</li>
<li class="index-item method">
<a href="#<API key>">addWeightCollection</a>
</li>
<li class="index-item method">
<a href="#<API key>">changeOrderView</a>
</li>
<li class="index-item method">
<a href="#<API key>">changeSelection</a>
</li>
<li class="index-item method">
<a href="#<API key>">compareNameWith</a>
</li>
<li class="index-item method">
<a href="#<API key>">decrementValue</a>
</li>
<li class="index-item method">
<a href="#<API key>">denormalizeValue</a>
</li>
<li class="index-item method">
<a href="#<API key>">getDescription</a>
</li>
<li class="index-item method">
<a href="#method_getName">getName</a>
</li>
<li class="index-item method">
<a href="#method_getURL">getURL</a>
</li>
<li class="index-item method">
<a href="#method_getValue">getValue</a>
</li>
<li class="index-item method">
<a href="#method_getWeights">getWeights</a>
</li>
<li class="index-item method">
<a href="#method_hideMethod">hideMethod</a>
</li>
<li class="index-item method">
<a href="#<API key>">incrementValue</a>
</li>
<li class="index-item method">
<a href="#method_initialize">initialize</a>
</li>
<li class="index-item method">
<a href="#method_isSelected">isSelected</a>
</li>
<li class="index-item method">
<a href="#<API key>">normalizeValue</a>
</li>
<li class="index-item method">
<a href="#<API key>">removeWeights</a>
</li>
<li class="index-item method">
<a href="#method_selectMethod">selectMethod</a>
</li>
<li class="index-item method">
<a href="#<API key>"><API key></a>
</li>
<li class="index-item method">
<a href="#method_toCSV">toCSV</a>
</li>
<li class="index-item method">
<a href="#<API key>">unselectMethod</a>
</li>
<li class="index-item method">
<a href="#method_weightsToCSV">weightsToCSV</a>
</li>
</ul>
</div>
<div class="index-section properties">
<h3>Properties</h3>
<ul class="index-list properties">
<li class="index-item property">
<a href="#<API key>">description</a>
</li>
<li class="index-item property">
<a href="#property_name">name</a>
</li>
<li class="index-item property">
<a href="#<API key>">numIncrements</a>
</li>
<li class="index-item property">
<a href="#property_selected">selected</a>
</li>
<li class="index-item property">
<a href="#property_url">url</a>
</li>
<li class="index-item property">
<a href="#property_value">value</a>
</li>
<li class="index-item property">
<a href="#<API key>">weightCollection</a>
</li>
</ul>
</div>
</div>
<div id="methods" class="api-class-tabpanel">
<h2 class="off-left">Methods</h2>
<div id="method_addWeight" class="method item">
<h3 class="name"><code>addWeight</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>weight</code>
</li>
</ul><span class="paren">)</span>
</div>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l397"><code>models.js:397</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">weight</code>
<span class="type"><a href="..\classes\Weight.html" class="crosslink">Weight</a></span>
<div class="param-description">
</div>
</li>
</ul>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>addWeightCollection</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>col</code>
</li>
</ul><span class="paren">)</span>
</div>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l406"><code>models.js:406</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">col</code>
<span class="type"><a href="..\classes\WeightCollection.html" class="crosslink">WeightCollection</a></span>
<div class="param-description">
</div>
</li>
</ul>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>changeOrderView</code></h3>
<span class="paren">()</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l426"><code>models.js:426</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>changeSelection</code></h3>
<span class="paren">()</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l447"><code>models.js:447</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>compareNameWith</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>name</code>
</li>
</ul><span class="paren">)</span>
</div>
<span class="returns-inline">
<span class="type">Boolean</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l537"><code>models.js:537</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">name</code>
<span class="type">String</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">Boolean</span>:
equals
</div>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>decrementValue</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>weightValue</code>
</li>
</ul><span class="paren">)</span>
</div>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l347"><code>models.js:347</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">weightValue</code>
<span class="type">Number</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>denormalizeValue</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">Number</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l388"><code>models.js:388</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">Number</span>:
totalValue
</div>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>getDescription</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">String</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l501"><code>models.js:501</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">String</span>:
dscription
</div>
</div>
</div>
<div id="method_getName" class="method item">
<h3 class="name"><code>getName</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">String</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l492"><code>models.js:492</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">String</span>:
name
</div>
</div>
</div>
<div id="method_getURL" class="method item">
<h3 class="name"><code>getURL</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">String</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l510"><code>models.js:510</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">String</span>:
url
</div>
</div>
</div>
<div id="method_getValue" class="method item">
<h3 class="name"><code>getValue</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">Number</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l519"><code>models.js:519</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">Number</span>:
value
</div>
</div>
</div>
<div id="method_getWeights" class="method item">
<h3 class="name"><code>getWeights</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type"><a href="..\classes\WeightCollection.html" class="crosslink">WeightCollection</a></span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l528"><code>models.js:528</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type"><a href="..\classes\WeightCollection.html" class="crosslink">WeightCollection</a></span>:
weightCollection
</div>
</div>
</div>
<div id="method_hideMethod" class="method item">
<h3 class="name"><code>hideMethod</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>sliderValue</code>
</li>
</ul><span class="paren">)</span>
</div>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l434"><code>models.js:434</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">sliderValue</code>
<span class="type">Number</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>incrementValue</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>weightValue</code>
</li>
</ul><span class="paren">)</span>
</div>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l323"><code>models.js:323</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">weightValue</code>
<span class="type">Number</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
</div>
<div id="method_initialize" class="method item">
<h3 class="name"><code>initialize</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>name</code>
</li>
<li class="arg">
<code>description</code>
</li>
<li class="arg">
<code>url</code>
</li>
</ul><span class="paren">)</span>
</div>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l262"><code>models.js:262</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">name</code>
<span class="type">String</span>
<div class="param-description">
</div>
</li>
<li class="param">
<code class="param-name">description</code>
<span class="type">String</span>
<div class="param-description">
</div>
</li>
<li class="param">
<code class="param-name">url</code>
<span class="type">String</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
</div>
<div id="method_isSelected" class="method item">
<h3 class="name"><code>isSelected</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">Boolean</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l483"><code>models.js:483</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">Boolean</span>:
selected
</div>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>normalizeValue</code></h3>
<div class="args">
<span class="paren">(</span><ul class="args-list inline commas">
<li class="arg">
<code>totalValue</code>
</li>
</ul><span class="paren">)</span>
</div>
<span class="returns-inline">
<span class="type">Number</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l371"><code>models.js:371</code></a>
</p>
</div>
<div class="description">
</div>
<div class="params">
<h4>Parameters:</h4>
<ul class="params-list">
<li class="param">
<code class="param-name">totalValue</code>
<span class="type">Number</span>
<div class="param-description">
</div>
</li>
</ul>
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">Number</span>:
newTotalvalue
</div>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>removeWeights</code></h3>
<span class="paren">()</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l418"><code>models.js:418</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="method_selectMethod" class="method item">
<h3 class="name"><code>selectMethod</code></h3>
<span class="paren">()</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l456"><code>models.js:456</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code><API key></code></h3>
<span class="paren">()</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l466"><code>models.js:466</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="method_toCSV" class="method item">
<h3 class="name"><code>toCSV</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">String</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l562"><code>models.js:562</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">String</span>:
csv
</div>
</div>
</div>
<div id="<API key>" class="method item">
<h3 class="name"><code>unselectMethod</code></h3>
<span class="paren">()</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l475"><code>models.js:475</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="method_weightsToCSV" class="method item">
<h3 class="name"><code>weightsToCSV</code></h3>
<span class="paren">()</span>
<span class="returns-inline">
<span class="type">String</span>
</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l547"><code>models.js:547</code></a>
</p>
</div>
<div class="description">
</div>
<div class="returns">
<h4>Returns:</h4>
<div class="returns-description">
<span class="type">String</span>:
output
</div>
</div>
</div>
</div>
<div id="properties" class="api-class-tabpanel">
<h2 class="off-left">Properties</h2>
<div id="<API key>" class="property item">
<h3 class="name"><code>description</code></h3>
<span class="type">String</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l279"><code>models.js:279</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_name" class="property item">
<h3 class="name"><code>name</code></h3>
<span class="type">String</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l273"><code>models.js:273</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="<API key>" class="property item">
<h3 class="name"><code>numIncrements</code></h3>
<span class="type">Number</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l312"><code>models.js:312</code></a>
</p>
</div>
<div class="description">
</div>
<p><strong>Default:</strong> "0"</p>
</div>
<div id="property_selected" class="property item">
<h3 class="name"><code>selected</code></h3>
<span class="type">Boolean</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l298"><code>models.js:298</code></a>
</p>
</div>
<div class="description">
</div>
<p><strong>Default:</strong> "false"</p>
</div>
<div id="property_url" class="property item">
<h3 class="name"><code>url</code></h3>
<span class="type">String</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l285"><code>models.js:285</code></a>
</p>
</div>
<div class="description">
</div>
</div>
<div id="property_value" class="property item">
<h3 class="name"><code>value</code></h3>
<span class="type">Number</span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l305"><code>models.js:305</code></a>
</p>
</div>
<div class="description">
</div>
<p><strong>Default:</strong> "0"</p>
</div>
<div id="<API key>" class="property item">
<h3 class="name"><code>weightCollection</code></h3>
<span class="type"><a href="..\classes\WeightCollection.html" class="crosslink">WeightCollection</a></span>
<div class="meta">
<p>
Defined in
<a href="../files/models.js.html#l291"><code>models.js:291</code></a>
</p>
</div>
<div class="description">
</div>
<p><strong>Default:</strong> "new WeightCollection"</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html> |
<p>Admin Menu:</p>
<p>Form Admin<br>
- <a href="<?PHP echo SITE_URL; ?>admin/forms/form-manager.php?page=add">Create Form</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/forms/form-manager.php?page=modify">Modify Form</a><br>
<!-- - <a href="<?PHP echo SITE_URL; ?>admin/forms/form-manager.php?page=delete">Delete Form</a><br>-->
- <a href="<?PHP echo SITE_URL; ?>admin/forms/form-manager.php?page=search">Form Search</a><br>
<p>Form Fields Admin<br>
- <a href="<?PHP echo SITE_URL; ?>admin/forms/configure-fields.php?page=add">Create Field</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/forms/configure-fields.php?page=modify">Modify Field</a><br>
<!-- - <a href="<?PHP echo SITE_URL; ?>admin/forms/configure-fields.php?page=delete">Delete Field</a><br>-->
- <a href="<?PHP echo SITE_URL; ?>admin/forms/configure-fields.php?page=search">Field Search</a><br>
<p>Form Stats & Info<br>
- <a href="<?PHP echo SITE_URL; ?>admin/form-stats/recent-forms.php">Recent Form Filling</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/form-stats/filtered-forms.php">Filtered Form Data</a>
</p>
<p>Client Admin & Info<br>
- <a href="<?PHP echo SITE_URL; ?>admin/clients/client-manager.php?page=add">Create Client</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/clients/client-manager.php?page=modify">Modify Client</a><br>
<!-- - <a href="<?PHP echo SITE_URL; ?>admin/clients/client-manager.php?page=delete">Delete Client</a><br>-->
- <a href="<?PHP echo SITE_URL; ?>admin/clients/client-manager.php?page=search">Client Search</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/clients/client-activity.php">Client Activity Info</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/clients/client-list.php">Client List</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/clients/label-select.php">Select Client Labels</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/clients/client_labels.php" target="_blank">All Client Labels</a>
</p>
<!-- <p>User Admin<br>
- <a href="<?PHP echo SITE_URL; ?>admin/users/user-manager.php?page=add">Create User</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/users/user-manager.php?page=modify">Modify User</a><br>
- <a href="<?PHP echo SITE_URL; ?>admin/users/user-manager.php?page=delete">Delete User</a>
</p> |
module Vector2D where
type Vector2D = (Double, Double)
zero :: Vector2D
zero = (0, 0)
unit :: Vector2D
unit = (1, 1)
fromScalar :: Double -> Vector2D
fromScalar scalar = (scalar, scalar)
fromAngle :: Double -> Vector2D
fromAngle angle = (cos angle, sin angle)
magnitude :: Vector2D -> Double
magnitude vector = sqrt(magnitudeSquared vector)
magnitudeSquared :: Vector2D -> Double
magnitudeSquared (x, y) = (x*x + y*y)
addVector :: Vector2D -> Vector2D -> Vector2D
addVector (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
subtractVector :: Vector2D -> Vector2D -> Vector2D
subtractVector (x1, y1) (x2, y2) = (x1 - x2, y1 - y2)
multiplyVector :: Vector2D -> Vector2D -> Vector2D
multiplyVector (x1, y1) (x2, y2) = (x1 * x2, y1 * y2)
multiplyScalar :: Vector2D -> Double -> Vector2D
multiplyScalar vector scalar = multiplyVector vector $ fromScalar scalar
divideVector :: Vector2D -> Vector2D -> Vector2D
divideVector (x1, y1) (x2, y2) = (x1 / x2, y1 / y2)
divideScalar :: Vector2D -> Double -> Vector2D
divideScalar vector scalar = divideVector vector $ fromScalar scalar
distance :: Vector2D -> Vector2D -> Double
distance (x1, y1) (x2, y2) = sqrt $ dx * dx + dy * dx
where dx = x1 - x2
dy = y1 - y2
dot :: Vector2D -> Vector2D -> Double
dot (x1, y1) (x2, y2) = x1*x2 + y1+y2
reflect :: Vector2D -> Vector2D -> Vector2D
reflect vector1@(vectorX, vectorY) vector2@(normalX, normalY) = (vectorX - (2 * dotProduct * normalX), vectorY - (2 * dotProduct * normalY))
where dotProduct = dot vector1 vector2
normalize :: Vector2D -> Vector2D
normalize vector
| vectorMagnitude == 0 || vectorMagnitude == 1 = vector
| otherwise = vector `divideVector` (fromScalar vectorMagnitude)
where vectorMagnitude = magnitude vector
limit :: Vector2D -> Double -> Vector2D
limit vector maximum
| magnitudeSquared vector <= maximum * maximum = vector
| otherwise = (normalize vector) `multiplyScalar` maximum
getAngle :: Vector2D -> Double
getAngle (x, y) = (-1) * (atan2 (-y) x)
rotate :: Vector2D -> Double -> Vector2D
rotate (x, y) angle = (x * (cos angle) - y * (sin angle),
x * (sin angle) - y * (cos angle))
lerp :: Double -> Double -> Double -> Double
lerp start end amount = start + (end - start) * amount
lerpVector :: Vector2D -> Vector2D -> Double -> Vector2D
lerpVector (startX, startY) (endX, endY) amount = (lerp startX endX amount,
lerp startY endY amount)
remap :: Double -> Double -> Double -> Double -> Double -> Double
remap value oldMin oldMax newMin newMax = newMin + (newMax - newMin) * ((value - oldMin) / (oldMax - oldMin))
remapVectorToScalar :: Vector2D -> Double -> Double -> Double -> Double -> Vector2D
remapVectorToScalar (x, y) oldMin oldMax newMin newMax = (remap x oldMin oldMax newMin newMax,
remap y oldMin oldMax newMin newMax)
<API key> :: Vector2D -> Vector2D -> Vector2D -> Vector2D -> Vector2D -> Vector2D
<API key> (x, y) (oldMinX, oldMinY) (oldMaxX, oldMaxY) (newMinX, newMinY) (newMaxX, newMaxY) = (remap x oldMinX oldMaxX newMinX newMaxX,
remap y oldMinY oldMaxY newMinY newMaxY)
angleBetween :: Vector2D -> Vector2D -> Double
angleBetween vector1 vector2 = acos (<API key> tempValue)
where tempValue = (vector1 `dot` vector2) / (magnitude vector1 * magnitude vector2)
<API key> value
| value <= -1 = pi
| value >= 1 = 0
| otherwise = value
degreesToRadians :: Double -> Double
degreesToRadians degrees = degrees * (pi / 180)
radiansToDegrees :: Double -> Double
radiansToDegrees radians = radians * (180 / pi)
clamp :: Double -> Double -> Double -> Double
clamp input min max
| input < min = min
| input > max = max
| otherwise = input
clampToScalar :: Vector2D -> Double -> Double -> Vector2D
clampToScalar (x, y) min max = (clamp x min max, clamp y min max)
clampToVectors :: Vector2D -> Vector2D -> Vector2D -> Vector2D
clampToVectors (x, y) (minX, minY) (maxX, maxY) = (clamp x minX maxX,
clamp y minY maxY)
negate :: Vector2D -> Vector2D
negate vector = vector `multiplyScalar` (-1) |
body {
padding-top: 50px;
padding-bottom: 20px;
background-color: #4bb5ff !important;
}
/* Set padding to keep content from hitting the edges */
.body-content {
padding-left: 15px;
padding-right: 15px;
}
.modal-header {
background-color: #8B0000 !important;
}
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 1000px;
width: 100%;
}
.contentBox {
background-color: #81cbff;
background-color: rgba(255,255,255,0.3);
padding: 20px;
border-radius: 25px;
}
.NickName {
padding: 1px;
margin: 1px;
font-weight: bold;
font-size: 110%;
}
.Channel {
padding: 1px;
margin: 1px;
}
.noLink {
text-decoration: none;
color: black;
}
.ChannelGroup {
padding-left: 22px !IMPORTANT;
}
.Account {
border: black;
border-width: 1px;
border-radius: 3px;
} |
# Giles' Notebook
onofficial notes on relevant work
Genome Asssembly
0005 - Sablefish Genome Project - Lab Notebook [link](https://github.com/sr320/nb-2016/blob/master/notes/<API key>.pdf)
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/0005_1D131CE3.png" alt="0005_1D131CE3.png"/>
RAD
0003 - Steelhead RADseq Project [link](https://github.com/sr320/nb-2016/blob/master/notes/<API key>.pdf)
<img src="http://eagle.fish.washington.edu/cnidarian/skitch/0003_1D131D93.png" alt="0003_1D131D93.png"/> |
require 'test_helper'
class TestDivinity < Test::Unit::TestCase
should "probably rename this file and start testing for real" do
flunk "hey buddy, you should probably rename this file and start testing for real"
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.