text
stringlengths 27
775k
|
---|
package eu.kanade.tachiyomi.extension.en.newmanganelos
import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import kotlin.collections.ArrayList
import okhttp3.CacheControl
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import rx.Observable
class Newmanganelos : ParsedHttpSource() {
private val chapterRegEx: Regex = ".*(Chapter)\\s([\\d.]+).*".toRegex()
private val protocol: String = "http:"
override val baseUrl: String = "$protocol//manganelos.com"
override val lang: String = "en"
override val name: String = "NewManganelos"
override val supportsLatest: Boolean = true
private val rateLimitInterceptor = RateLimitInterceptor(2)
override val client: OkHttpClient = network.client.newBuilder()
.addNetworkInterceptor(rateLimitInterceptor).build()
private val userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" +
" (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
override fun headersBuilder(): Headers.Builder = Headers.Builder().apply {
add("User-Agent", userAgent)
}
override fun popularMangaNextPageSelector(): String = "ul.pagination > li > a[rel=next]"
override fun latestUpdatesNextPageSelector(): String = popularMangaNextPageSelector()
override fun searchMangaNextPageSelector(): String = popularMangaNextPageSelector()
override fun popularMangaSelector(): String = "div.cate-manga > div.col-md-6"
override fun latestUpdatesSelector(): String = popularMangaSelector()
override fun searchMangaSelector(): String = popularMangaSelector()
override fun chapterListSelector(): String = "div.chapter-list:nth-child(1) > ul > li.row > div.chapter > h4 > a"
override fun popularMangaRequest(page: Int): Request {
val url = if (page == 1) "$baseUrl/popular-manga"
else "$baseUrl/popular-manga/?page=$page"
return GET(url, headersBuilder().build())
}
override fun latestUpdatesRequest(page: Int): Request {
val url = if (page == 1) "$baseUrl/latest-manga"
else "$baseUrl/latest-manga?page=$page"
return GET(url, headersBuilder().build())
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val rawq = query.toLowerCase()
val q = HttpUrl.parse("$baseUrl/search")!!.newBuilder()
q.addQueryParameter("q", rawq)
q.addQueryParameter("page", page.toString())
return GET(q.toString(), headersBuilder().build(), CacheControl.FORCE_NETWORK)
}
override fun chapterFromElement(element: Element): SChapter = throw Exception("Not used")
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
return if (manga.status != SManga.LICENSED) {
client.newCall(chapterListRequest(manga))
.asObservableSuccess()
.map { response ->
chapterListParse(response, manga)
}
} else {
Observable.error(java.lang.Exception("Licensed - No chapters to show"))
}
}
private fun parseChapterName(name: String): String {
return chapterRegEx.find(name)!!.groupValues.subList(1, 3).joinToString(" ")
}
private fun chapterListParse(response: Response, manga: SManga): List<SChapter> {
val document = response.asJsoup()
return document.select(chapterListSelector())
.map { chapterFromElement(it, manga) }
.distinctBy { Pair(it.name, it.chapter_number) }
.sortedBy { it.chapter_number }
.reversed()
}
private fun chapterFromElement(element: Element, manga: SManga): SChapter {
val chapter = SChapter.create()
chapter.name = parseChapterName(element.text())
try {
chapter.chapter_number = parseChapterName(chapter.name).split(" ")[1].toFloat()
} catch (e: java.lang.Exception) {
chapter.chapter_number = 0.0F
}
chapter.setUrlWithoutDomain(element.attr("href").toString())
chapter.date_upload = 0
return chapter
}
private fun parseStatus(status: String): Int {
return when (status.trim().toLowerCase()) {
"ongoing" -> SManga.ONGOING
"completed" -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
}
private fun getSubString(text: String, start: String, end: String): String {
var startPos = text.indexOf(start)
if (startPos == -1) return ""
startPos += start.length
var endPos = text.indexOf(end, startPos)
if (endPos == -1) return ""
endPos -= 1
return text.subSequence(startPos, endPos).toString()
}
private fun fixThumbURL(thumbUrl: String): String {
if (thumbUrl.startsWith("//")) {
return "$protocol$thumbUrl"
}
return thumbUrl
}
override fun mangaDetailsParse(document: Document): SManga {
val manga = SManga.create()
val root = document.select("div.manga-detail")
val table = document.select("div.media-body")
val tableBody = table.select("p.description-update").toString()
val genres = ArrayList<String>()
val authors = ArrayList<String>()
table.select("p.description-update > a").text()
.split("; ").forEach { x ->
genres.add(x.trim())
}
getSubString(tableBody, "<span>Author(s): </span>", "<br>").split(";")
.forEach { x ->
authors.add(x.trim())
}
manga.title = root.select("h1.title-manga").text()
manga.status = parseStatus(getSubString(tableBody, "<span>Status: </span>", "<br>"))
manga.thumbnail_url = fixThumbURL(document.select("div.manga-detail > div.cover-detail > img")
.attr("src").toString())
manga.description = document.select("div.manga-content > p").text()
manga.author = authors.joinToString()
manga.genre = genres.joinToString()
return manga
}
override fun latestUpdatesFromElement(element: Element): SManga {
val manga = SManga.create()
val mangaItem = element.select("div.media")
val mangaLink = mangaItem.select("div.media-body > a")
manga.thumbnail_url = fixThumbURL(mangaItem.select("div.cover-manga > a > img")
.attr("src").toString())
manga.title = mangaLink.attr("title").toString()
manga.setUrlWithoutDomain(mangaLink.attr("href").toString())
return manga
}
override fun popularMangaFromElement(element: Element): SManga = latestUpdatesFromElement(element)
override fun searchMangaFromElement(element: Element): SManga = latestUpdatesFromElement(element)
override fun imageUrlParse(document: Document) = ""
override fun imageRequest(page: Page): Request {
val imgHeader = Headers.Builder().apply {
add("User-Agent", userAgent)
// add("Referer", page.url)
}.build()
return GET(page.imageUrl!!, imgHeader)
}
override fun pageListParse(response: Response): List<Page> {
val document: Document = response.asJsoup()
val refUrl = response.request().url().toString()
var i = 0
val chapters = document.select("p[id=arraydata]").text()
return chapters.split(",").map { el ->
Page(i++, refUrl, fixThumbURL(el))
}
}
override fun pageListParse(document: Document): List<Page> {
throw Exception("Not used")
}
}
|
package expr
import (
"github.com/imulab/go-scim/pkg/core/spec"
)
var urnsCache = &urns{}
// Register the resource type to correctly use expression package's compiler capability. This method
// caches all schema urn ids available in a resource type, so they can be recognized later when an
// expression that contains one is passed in as an argument to compiler.
func Register(resourceType *spec.ResourceType) {
register(resourceType.Schema().ID())
resourceType.ForEachExtension(func(extension *spec.Schema, _ bool) {
register(extension.ID())
})
}
func register(s string) {
urnsCache = urnsCache.insert(urnsCache, s, 0)
}
// A trie data structure to cache all registered resource type ID URNs. These URNs
// are essential for the compiler to decide where to treat a dot as a path separator
// and where to treat it as just part of the property namespace.
type urns struct {
// true if a word's trie path ends at this node
w bool
next map[byte]*urns
}
func (t *urns) isWord() bool {
return t != nil && t.w
}
func (t *urns) nextTrie(c byte) (*urns, bool) {
if t == nil || len(t.next) == 0 {
return nil, false
}
next, ok := t.next[toLowerCaseByte(c)]
return next, ok
}
func (t *urns) insert(x *urns, word string, d int) *urns {
if x == nil {
x = &urns{}
}
if d == len(word) {
x.w = true
return x
}
if x.next == nil {
x.next = make(map[byte]*urns)
}
b := toLowerCaseByte(word[d])
x.next[b] = t.insert(x.next[b], word, d+1)
return x
}
func toLowerCaseByte(c byte) byte {
if 'A' <= c && c <= 'Z' {
return 'a' + (c - 'A')
}
return c
}
|
#!/bin/bash
DATE=`date +%Y%m%d%H%M`
BACKUPDIR=/opt/pgsql-dump
PGDATA=/opt/pgsql-data
PGSQL_HOME=/opt/pgsql
echo "select pg_start_backup('full - $DATE');" | $PGSQL_HOME/bin/psql
cd $PGDATA
tar -zcvf $BACKUPDIR/full-dump-pit-$DATE.tar.gz .
echo "select pg_stop_backup();" | $PGSQL_HOME/bin/psql
|
package de.jensklingenberg.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import de.jensklingenberg.ui.deeplinkStarter.DeepLinkStarterContract
import de.jensklingenberg.ui.deeplinkStarter.DeepLinkStarterView
class ToolsMenuAction : AnAction() {
override fun actionPerformed(anActionEvent: AnActionEvent) {
DeepLinkStarterView(DeepLinkStarterContract.Mode.CUSTOM).showAndGet()
}
} |
// Command d4mctl offers command line manipulation of a docker-for-mac installation.
package main
import (
"encoding/json"
"fmt"
"os"
"strconv"
"github.com/spf13/cobra"
"github.com/tmc/d4mctl/d4m"
)
func loadConf() *d4m.Settings {
s, err := d4m.Load()
if err != nil {
fmt.Println("issue loading configuration:", err)
os.Exit(1)
}
return s
}
var cmdk8s = &cobra.Command{
Use: "k8s [status|enable|disable]",
Short: "Get or set state of k8s-enabled in the local docker-for-mac installation",
Args: cobra.ExactValidArgs(1),
Run: func(cmd *cobra.Command, args []string) {
s := loadConf()
switch args[0] {
case "status":
fmt.Println(s.KubernetesEnabled)
case "enable":
s.KubernetesEnabled = true
if err := s.Write(); err != nil {
fmt.Println("issue writing:", err)
os.Exit(1)
}
case "disable":
s.KubernetesEnabled = false
if err := s.Write(); err != nil {
fmt.Println("issue writing:", err)
os.Exit(1)
}
}
},
}
var cmdCpus = &cobra.Command{
Use: "cpus [n]",
Short: "Get or set number of cpus enabled in the local docker-for-mac installation",
Run: func(cmd *cobra.Command, args []string) {
s := loadConf()
if len(args) == 0 {
fmt.Println(s.Cpus)
} else {
n, err := strconv.Atoi(args[0])
if err != nil {
fmt.Println("issue interpreting n:", err)
os.Exit(1)
}
s.Cpus = n
if err := s.Write(); err != nil {
fmt.Println("issue writing:", err)
os.Exit(1)
}
}
},
}
var cmdMem = &cobra.Command{
Use: "mem [n]",
Short: "Get or set amount of memory alllocated for the local docker-for-mac installation (in megabytes)",
Run: func(cmd *cobra.Command, args []string) {
s := loadConf()
if len(args) == 0 {
fmt.Println(s.MemoryMiB)
} else {
n, err := strconv.Atoi(args[0])
if err != nil {
fmt.Println("issue interpreting n:", err)
os.Exit(1)
}
s.MemoryMiB = n
if err := s.Write(); err != nil {
fmt.Println("issue writing:", err)
os.Exit(1)
}
}
},
}
var cmdDump = &cobra.Command{
Use: "dump",
Short: "Dump current configuration",
Run: func(cmd *cobra.Command, args []string) {
json.NewEncoder(os.Stdout).Encode(loadConf())
},
}
var restartWait bool
var cmdRestart = &cobra.Command{
Use: "restart",
Short: "Restart docker-for-mac",
Run: func(cmd *cobra.Command, args []string) {
err := d4m.Restart(restartWait)
// exit early if we complete without issue
if err == nil {
return
}
fmt.Println("issue restarting:", err)
fmt.Println("retrying")
if err = d4m.Restart(restartWait); err != nil {
fmt.Println("issue restarting:", err)
os.Exit(1)
}
},
}
func main() {
rootCmd := &cobra.Command{Use: "d4mctl"}
rootCmd.AddCommand(cmdDump)
rootCmd.AddCommand(cmdk8s)
rootCmd.AddCommand(cmdCpus)
rootCmd.AddCommand(cmdMem)
rootCmd.AddCommand(cmdRestart)
cmdRestart.Flags().BoolVarP(&restartWait, "wait", "w", false, "If provided, wait until the docker engine is back up.")
rootCmd.Execute()
}
|
# Disciplina de Sistemas Embarcados
Material das aulas e trabalhos das equipes de sistemas embarcado do curso de Engenharia da Computação da Uema.
# Aulas
...
# Trabalhos da disciplina
1 - Automacao Residencial (https://github.com/elizeumatheus/AutomacaoResidencial)
2 - Seguranca Residencial (https://github.com/rodrigoframa/Indesys)
3 - Radar Ultrasonico (https://github.com/Thiarlleson/ProjetoSistemaEmbarcado)
4 - Controle Irrigacao de Solo (https://github.com/PatrickGuedesOliveira/SistemasEmbarcados)
|
#!/bin/bash
# To be run as sudo
echo "Clearing CIB temp files"
rm -r /tmp/tomcat*
echo "Clearing thumbor temp files"
rm -r /tmp/thumbor
echo "Clearing RIC temp files"
rm -r /tmp/RICdiskcache
echo "Clearing cache"
sh -c 'sync && echo 3 >/proc/sys/vm/drop_caches'
|
/**
* Module API
*
* import { Basic, Advanced, Managers, Utils } from 'czechidm-core';
*
* @author Radek Tomiška
*/
import * as Basic from './src/components/basic';
import * as Advanced from './src/components/advanced';
import * as Services from './src/services';
import * as Managers from './src/redux';
import * as ConfigActions from './src/redux/config/actions';
import * as ConfigReducers from './src/redux/config/reducer';
import * as FlashReducers from './src/redux/flash/reducer';
import * as DataReducers from './src/redux/data/reducer';
import * as SecurityReducers from './src/redux/security/reducer';
import * as Utils from './src/utils';
import * as Domain from './src/domain';
// import Routes from './routes';
import ComponentService from './src/services/ComponentService';
//
import AbstractEnum from './src/enums/AbstractEnum';
import BasePermissionEnum from './src/enums/BasePermissionEnum';
import OperationStateEnum from './src/enums/OperationStateEnum';
import PasswordPolicyTypeEnum from './src/enums/PasswordPolicyTypeEnum';
import ScriptCategoryEnum from './src/enums/ScriptCategoryEnum';
import ApiOperationTypeEnum from './src/enums/ApiOperationTypeEnum';
import IdentityAttributeEnum from './src/enums/IdentityAttributeEnum';
import ContractAttributeEnum from './src/enums/ContractAttributeEnum';
import ContractSliceAttributeEnum from './src/enums/ContractSliceAttributeEnum';
import ConceptRoleRequestOperationEnum from './src/enums/ConceptRoleRequestOperationEnum';
import IdentityStateEnum from './src/enums/IdentityStateEnum';
import TokenTypeEnum from './src/enums/TokenTypeEnum';
//
import ValidationMessage from './src/components/advanced/ValidationMessage/ValidationMessage';
//
import IdentityTableComponent from './src/content/identity/IdentityTable';
import RoleRequestTableComponent from './src/content/requestrole/RoleRequestTable';
import IdentityRoleTableComponent from './src/content/identity/IdentityRoleTable';
import OrganizationPosition from './src/content/identity/OrganizationPosition';
import AbstractIdentityProjection from './src/content/identity/projection/AbstractIdentityProjection';
const ModuleRoot = {
Basic,
Advanced,
Services,
Managers,
ConfigActions,
Reducers: {
config: ConfigReducers.config,
messages: FlashReducers.messages,
data: DataReducers.data,
security: SecurityReducers.security
},
ComponentService,
Utils,
Domain,
Enums: {
AbstractEnum,
BasePermissionEnum,
OperationStateEnum,
PasswordPolicyTypeEnum,
ScriptCategoryEnum,
ApiOperationTypeEnum,
IdentityAttributeEnum,
IdentityStateEnum,
ContractAttributeEnum,
ContractSliceAttributeEnum,
ConceptRoleRequestOperationEnum,
TokenTypeEnum
},
Content: {
ValidationMessage, // backward compatibility
OrganizationPosition,
AbstractIdentityProjection
},
Table: {
IdentityTable: IdentityTableComponent,
RoleRequestTable: RoleRequestTableComponent,
IdentityRoleTable: IdentityRoleTableComponent
}
};
ModuleRoot.version = '10.8.0';
module.exports = ModuleRoot;
|
/* eslint-disable camelcase */
/**
* WordPress dependencies
*/
const { __ } = wp.i18n;
const { render } = wp.element;
const { Icon } = wp.components;
/**
* Internal dependencies
*/
import './style.scss';
import { Discord } from '../providers/discord';
const App = () => {
return (
<>
<div className="codeinwp-header">
<div className="codeinwp-container">
<div className="codeinwp-logo">
<h1>
<Icon icon="admin-network" size={ 40 } />
{ __( 'Authentication' ) }
</h1>
</div>
</div>
</div>
<div className="codeinwp-main">
<Discord />
</div>
</>
);
};
window.onload = () => {
const element = document.getElementById( 'phobos-auth-admin' );
console.log( element ); //eslint-disable-line
render( <App />, element );
};
|
<?php
declare(strict_types=1);
/*
* @author mfris
* @copyright PIXELFEDERATION s.r.o.
* @license Internal use only
*/
namespace K911\Swoole\Server\Runtime\HMR;
use UnexpectedValueException;
/**
*
*/
final class HmrComposerLoader
{
/**
* @var LoadedFiles
*/
private $loadedFiles;
/**
* @var mixed
*/
private $decorated;
/**
* @var string
*/
private $decoratedMethod;
/**
* @var bool
*/
private $isFinder;
/**
* @param LoadedFiles $loadedFiles
* @param mixed $decorated
* @param string $decoratedMethod
*/
public function __construct(LoadedFiles $loadedFiles, $decorated, string $decoratedMethod)
{
$this->loadedFiles = $loadedFiles;
$this->decorated = $decorated;
$this->decoratedMethod = $decoratedMethod;
$this->isFinder = method_exists($decorated, 'findFile');
}
/**
* Autoload a class by it's name
*
* @param string $class Name of the class to load
*/
public function loadClass($class)
{
$this->decorated->{$this->decoratedMethod}($class);
}
/**
* Finds either the path to the file where the class is defined,
* or gets the appropriate php://filter stream for the given class.
*
* @param string $class
* @return string|false The path/resource if found, false otherwise.
*/
public function findFile($class)
{
if (!$this->isFinder) {
return null;
}
$file = $this->decorated->findFile($class);
if (is_string($file)) {
$correctFile = $this->getCorrectFile($file);
$this->loadedFiles->addFile($correctFile);
}
return $file;
}
/**
* @param string $file
*
* @return string
*/
private function getCorrectFile(string $file): string
{
if (strpos($file, 'php://') === 0) {
if (!preg_match('/\/resource=(.*\.php)/', $file, $matches)) {
throw new UnexpectedValueException(sprintf('Unable to parse file from string: %s', $file));
}
if (!isset($matches[1])) {
throw new UnexpectedValueException(
sprintf('Unable to match file data from string: %s, got %s', $file, print_r($matches, true))
);
}
return $matches[1];
}
return $file;
}
}
|
; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
; RUN: llc %s --mtriple aarch64 -verify-machineinstrs -o - | FileCheck %s
define dso_local void @jsimd_idct_ifast_neon_intrinsic(i8* nocapture readonly %dct_table, i16* nocapture readonly %coef_block, i8** nocapture readonly %output_buf, i32 %output_col) local_unnamed_addr #0 {
; CHECK-LABEL: jsimd_idct_ifast_neon_intrinsic:
; CHECK: // %bb.0: // %entry
; CHECK-NEXT: ldr q0, [x1, #32]
; CHECK-NEXT: mov w8, w3
; CHECK-NEXT: ldr q1, [x1, #96]
; CHECK-NEXT: ldr q2, [x0, #32]
; CHECK-NEXT: ldr q3, [x0, #96]
; CHECK-NEXT: ldr x9, [x2, #48]
; CHECK-NEXT: mul v0.8h, v2.8h, v0.8h
; CHECK-NEXT: mul v1.8h, v3.8h, v1.8h
; CHECK-NEXT: add v2.8h, v0.8h, v1.8h
; CHECK-NEXT: str q2, [x9, x8]
; CHECK-NEXT: ldr x9, [x2, #56]
; CHECK-NEXT: sub v0.8h, v0.8h, v1.8h
; CHECK-NEXT: str q0, [x9, x8]
; CHECK-NEXT: ret
entry:
%add.ptr5 = getelementptr inbounds i16, i16* %coef_block, i64 16
%0 = bitcast i16* %add.ptr5 to <8 x i16>*
%1 = load <8 x i16>, <8 x i16>* %0, align 16
%add.ptr17 = getelementptr inbounds i16, i16* %coef_block, i64 48
%2 = bitcast i16* %add.ptr17 to <8 x i16>*
%3 = load <8 x i16>, <8 x i16>* %2, align 16
%add.ptr29 = getelementptr inbounds i8, i8* %dct_table, i64 32
%4 = bitcast i8* %add.ptr29 to <8 x i16>*
%5 = load <8 x i16>, <8 x i16>* %4, align 16
%add.ptr41 = getelementptr inbounds i8, i8* %dct_table, i64 96
%6 = bitcast i8* %add.ptr41 to <8 x i16>*
%7 = load <8 x i16>, <8 x i16>* %6, align 16
%mul.i966 = mul <8 x i16> %5, %1
%mul.i964 = mul <8 x i16> %7, %3
%add.i961 = add <8 x i16> %mul.i966, %mul.i964
%sub.i960 = sub <8 x i16> %mul.i966, %mul.i964
%idx.ext = zext i32 %output_col to i64
%arrayidx404 = getelementptr inbounds i8*, i8** %output_buf, i64 6
%8 = load i8*, i8** %arrayidx404, align 8
%add.ptr406 = getelementptr inbounds i8, i8* %8, i64 %idx.ext
%9 = bitcast i8* %add.ptr406 to <8 x i16>*
store <8 x i16> %add.i961, <8 x i16>* %9, align 8
%arrayidx408 = getelementptr inbounds i8*, i8** %output_buf, i64 7
%10 = load i8*, i8** %arrayidx408, align 8
%add.ptr410 = getelementptr inbounds i8, i8* %10, i64 %idx.ext
%11 = bitcast i8* %add.ptr410 to <8 x i16>*
store <8 x i16> %sub.i960, <8 x i16>* %11, align 8
ret void
}
|
@extends ('layout')
@section('content')
<div class="content">
<div class="title-banner" style="background-image: url({{ Request::root() }}/img/photo_gallery.jpg);">
<div class="wrapper">
<h2>{{ Request::is('media_center/video_gallery') ? 'Видеогалерея' : 'Фотогалерея' }}</h2>
</div>
</div>
<div class="wrapper">
<div class="single-page">
<div class="right-col">
<div class="text-header">
<h2>Медиа-центр</h2>
</div>
<ul class="right-col-menu">
<!-- <li><a href="{{ URL::to('/press_releases') }}">Пресс-релизы</a></li> -->
<li><a href="{{ URL::to('/news') }}">Новости индустрии</a></li>
<li><a href="{{ URL::to('/media_center/photo_gallery') }}">Фотогалерея</a></li>
<li><a href="{{ URL::to('/media_center/video_gallery') }}">Видеогалерея</a></li>
</ul>
<div class="text-header">
<h2>Контакты</h2>
</div>
<div class="right-col-contacts">
<p>Телефон: <strong>+7 928 123 45 67</strong></p>
<p>Е-mail: <strong>[email protected]</strong></p>
<p>Факс: <strong>+7 928 123 45 67</strong></p>
<p>Адрес: <strong>г.Москва, ул. Магасовская 06</strong></p>
</div>
</div>
<div class="content-left-block">
<div class="left-col">
@if(Request::is('media_center/photo_gallery') || Request::is('media_center/video_gallery'))
@include('includes/list_photo_video')
@endif
@if(Request::is('media_center/photo_gallery/*'))
@include('includes/photo_item')
@endif
</div>
</div>
</div>
@if(Request::is('media_center/photo_gallery') || Request::is('media_center/video_gallery'))
@include ('includes/pagination')
@endif
</div>
</div>
@endsection
|
#include <iostream>
#include <string> // imports more string's functions
using namespace std;
// Without using template
// here, you can only use int
class Number1{
public:
int n1, n2;
int get_sum(){
return this->n1 + this->n2;
}
};
// Using template
// here, you can use any data types
// You don't need to have diferent class for int, float, double etc.
// 'num' is just a representor of the data type
// 'num' can be int, float or anything
template <class num>
class Number2{
public:
num n1, n2;
num get_sum(){
return this->n1 + this->n2;
}
};
// more than one custom data types
template <class T1, class T2, class T3>
class Number3{
public:
T1 n1;
T2 n2;
T3 n3;
void print_sum(){
cout << this->n1 + this->n2 + this->n3 << endl;
}
};
// default data types
template <class num=int> // default : num is int
class Number4{
public:
num n1, n2;
num get_sum(){
return this->n1 + this->n2;
}
};
// same process for function
template <class T1, class T2>
float avarage(T1 n1, T2 n2){
return (n1 + n2) / 2.0;
}
int main(){
Number1 a;
a.n1 = 45;
a.n2 = 34;
cout << a.get_sum() << endl;
// here, to use float you need to create an another class
// here, specify what data type you will use, that's it
Number2 <float> b;
b.n1 = 7.56;
b.n2 = 8.56;
cout << b.get_sum() << endl;
Number2 <int> c;
c.n1 = 75;
c.n2 = 56;
cout << c.get_sum() << endl;
Number3 <int, double, float> d; // using multiple template data types
d.n1 = 75;
d.n2 = 57.564778;
d.n3 = 86.14;
d.print_sum();
Number4 <> e; // this will use default data types : int
e.n1 = 78;
e.n2 = 23;
cout << e.get_sum() << endl;
Number4 <float> f; // not using default data types
f.n1 = 28.58;
f.n2 = 75.954;
cout << f.get_sum() << endl;
cout << avarage(2, 5) << endl;
cout << avarage(2.14, 8.69) << endl;
// one function for all kind of data types
return 0;
}
// but if we have a func for int and then same named func for templated data types,
// then if we call that func with int, first func will be called
// else second func that means func with template will be called
|
#encoding: utf-8
module SpreeImporter
module Parsers
class BaseParser
def parse value
raise 'You must define this function'
end
end
end
end
|
# Enable tab completion
source ~/bin/git-completion.bash
# colors!
green="\[\033[0;32m\]"
blue="\[\033[0;34m\]"
purple="\[\033[0;35m\]"
reset="\[\033[0m\]"
# Change command prompt
source ~/bin/git-prompt.sh
export GIT_PS1_SHOWDIRTYSTATE=1
# '\u' adds the name of the current user to the prompt
# '\$(__git_ps1)' adds git-related stuff
# '\W' adds the name of the current directory
export PS1="$purple\u$green\$(__git_ps1)$blue \W $ $reset"
|
# 4.1 VBA明细选择判定示例
* 效果图:

* 实现在Excel表格中点击不同明细区域时,区域首行更新为选中行的数据
```vb
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim rng
Set rng = Application.Intersect(Target(1).EntireRow,Range("_data1")) '检查是否为data1行区域
If rng Is Nothing Then
Set rng = Application.Intersect(Target(1).EntireRow,Range("_data2")) '检查是否为data2行区域
If rng Is Nothing Then Exit Sub
Range("_check2").Value = rng.Value '行拷贝
Else
Range("_check1").Value = rng.Value '行拷贝
End If
Set rng = Nothing
End Sub
```
### 本节贡献者
*@DHL*
|
import pytest
from plums.commons.path import Path
from plums.dataflow.utils.path import PathResolver
def test_resolver_init():
resolver = PathResolver('data/images/{dataset}/{aoi}/{source}/{tile}.jpg')
assert resolver._regex.pattern \
== r'data/images/(?P<dataset>[^/]+)/(?P<aoi>[^/]+)/(?P<source>[^/]+)/(?P<tile>[^/]+)\.jpg'
assert resolver._prefix == Path('data/images/')
resolver = PathResolver('/home/user/{dataset}/{aoi}/{source}/{tile}.jpg')
assert resolver._regex.pattern \
== r'/home/user/(?P<dataset>[^/]+)/(?P<aoi>[^/]+)/(?P<source>[^/]+)/(?P<tile>[^/]+)\.jpg'
assert resolver._prefix == Path('/home/user')
def test_degenerate(complex_tree):
root, path_list = complex_tree
resolver = PathResolver('data/images/dataset_0/labeled/tile_83.jpg')
with pytest.raises(OSError, match='Degenerate path pattern points to a non-existing file'):
_ = list(resolver.find(root))
resolver = PathResolver('data/images/dataset_0/labeled/tile_23.jpg')
resolved = list(resolver.find(root))
assert len(resolved) == 1
assert resolved[0] == root / 'data/images/dataset_0/labeled/tile_23.jpg'
def test_absolute_degenerate(complex_tree):
root, path_list = complex_tree
resolver = PathResolver(str(root / 'data/images/dataset_0/labeled/tile_83.jpg'))
with pytest.raises(OSError, match='Degenerate path pattern points to a non-existing file'):
_ = list(resolver.find())
resolver = PathResolver(str(root / 'data/images/dataset_0/labeled/tile_23.jpg'))
resolved = list(resolver.find())
assert len(resolved) == 1
assert resolved[0] == root / 'data/images/dataset_0/labeled/tile_23.jpg'
def test_absolute_group_walk(complex_tree):
root, path_list = complex_tree
resolver = PathResolver(str(root / 'data/images/{dataset}/{aoi}/{source}/{tile}.jpg'))
# Test raise on absolute + root find
with pytest.raises(ValueError, match='The dataset pattern to search for is '
'absolute but a search path was provided'):
_ = list(resolver.find(root))
ground_truth = [root / path for path in path_list if 'dataset_1' in path]
resolved = list(resolver.find())
# Test unordered equality
assert len(resolved) == len(ground_truth)
assert all(path in ground_truth for path in resolved)
# Test capture
for path in resolved:
assert hasattr(path, 'match')
assert path.match['dataset'] == 'dataset_1'
assert path.match['aoi'] in ('aoi_0', 'aoi_3')
assert path.match['source'] in ('labeled', 'simulated')
assert 'tile_' in path.match['tile']
def test_group_walk(complex_tree):
root, path_list = complex_tree
resolver = PathResolver('data/images/{dataset}/{aoi}/{source}/{tile}.jpg')
# Test raise on relative - root find
with pytest.raises(ValueError, match='The dataset pattern to search for is '
'relative but no search path was provided'):
_ = list(resolver.find())
ground_truth = [path for path in path_list if 'dataset_1' in path]
resolved = list(resolver.find(root))
# Test unordered equality
assert len(resolved) == len(ground_truth)
assert all(path in ground_truth for path in resolved)
# Test capture
for path in resolved:
assert hasattr(path, 'match')
assert path.match['dataset'] == 'dataset_1'
assert path.match['aoi'] in ('aoi_0', 'aoi_3')
assert path.match['source'] in ('labeled', 'simulated')
assert 'tile_' in path.match['tile']
def test_composed_group_walk(complex_tree):
root, path_list = complex_tree
resolver = PathResolver('data/images/{dataset}/aoi_0/{source}/{tile}.jpg')
ground_truth = [path for path in path_list if 'dataset_1' in path and 'aoi_0' in path]
resolved = list(resolver.find(root))
# Test unordered equality
assert len(resolved) == len(ground_truth)
assert all(path in ground_truth for path in resolved)
# Test capture
for path in resolved:
assert hasattr(path, 'match')
assert path.match['dataset'] == 'dataset_1'
assert path.match['source'] in ('labeled', 'simulated')
assert 'tile_' in path.match['tile']
def test_loose_regex_recursive_walk(complex_tree):
root, path_list = complex_tree
resolver = PathResolver('data/images/{path/:(?!.*added.*).*}/{tile}.jpg')
ground_truth = [path for path in path_list if 'added' not in path and path.ext == '.jpg']
resolved = list(resolver.find(root))
# Test unordered equality
assert len(resolved) == len(ground_truth)
assert all(path in ground_truth for path in resolved)
def test_strict_regex_recursive_walk(complex_tree):
root, path_list = complex_tree
resolver = PathResolver('data/images/{path/:[a-z]+_[0-9]+}/{tile}.jpg')
ground_truth = [path for path in path_list if 'dataset_3' in path and 'added' not in path]
resolved = list(resolver.find(root))
# Test unordered equality
assert len(resolved) == len(ground_truth)
assert all(path in ground_truth for path in resolved)
def test_composed_strict_regex_recursive_walk(complex_tree):
root, path_list = complex_tree
resolver = PathResolver('data/images/{path/:[a-z]+_[0-9]+}/added/{tile}.jpg')
ground_truth = [path for path in path_list if 'dataset_3' in path and 'added' in path]
resolved = list(resolver.find(root))
# Test unordered equality
assert len(resolved) == len(ground_truth)
assert all(path in ground_truth for path in resolved)
def test_loose_recursive_walk(complex_tree):
root, path_list = complex_tree
resolver = PathResolver('data/images/{path/}/{tile}.jpg')
ground_truth = [path for path in path_list if path.ext == '.jpg']
resolved = list(resolver.find(root))
# Test unordered equality
assert len(resolved) == len(ground_truth)
assert all(path in ground_truth for path in resolved)
|
require 'spec_helper'
require 'fileutils'
RSpec.describe DataSourcePipeline do
describe '#process' do
let(:zip_file_name) { 'loopholes.zip' }
let(:file_name) { 'test' }
let(:source_name) { 'loopholes' }
let(:file_content) { File.read("spec/fixtures/#{zip_file_name}") }
let(:passphrase) { '' }
let(:tmpdir) { Dir.mktmpdir }
before do
stub_request(:get, /#{Terminal::DOMAIN}.*/).
to_return(status: 200, body: file_content)
end
subject do
described_class.new(
source_name: source_name,
passphrase: passphrase,
destination_dir: tmpdir
)
end
after do
FileUtils.rm_r(tmpdir)
end
it 'loads data' do
records_set = subject.process
expect(records_set).to_not be_empty
end
end
end
|
#!/busybox/sh
java -jar /var/lib/nodedial-jars/nodedial-client.jar "$@"
|
/* ************************ Lab0.c *************************************
* File name: Lab0.c
* Author: Richard W. Wall
* Date: August 19, 2013
* This program is designed to provide a simple platform for exploring the
* software instrumentation and debugging tools available with the MPLAB X
* Integrated Development Environment (IDE). C code examples are provided
* that demonstrate passing data by value and by reference between two
* functions .
* ********************************************************************* */
/*
Note: Local project header files are written between " ".
System header files are bracketed between < >. */
#include "CerebotMX7cK.h" /* Cerebot MX7cK board definitions */
#include "lab0.h" /* Lab 0 definitions and function prototypes */
/* Global variable list - normally, only variables that are required
* to pass data to or from interrupt service routines (ISR) are required
* to be declared as global variables. Processor Special Function Register
* (SFR) are global by the system. */
/* Constant data types cannot be modified at execution time and appear
* as protected variables in the MPLAB watch window. */
const int ac = A; /* Constants assigned values that are defined */
const int bc = B;
/* -------------------- Start of program code ------------------------------ */
int main(void)
{
/* Variable that are declared as static can be viewed in the MPLAB watch
* window but values for these type of variables will be shown when the program
* is executing code in the function in which they are declared. Static local
* variables do not automatically appear in the variables window.
*/
static int a; /* Static local variables have permanent memory allocation*/
static int b;
int c; /* auto local variables have temporary memory allocation */
const int d = 3; /* Variables that are declared as a data type "const"
are assigned a value when they are declared. The
"const" variable cannot appear on the left side of the
equal (=) sign in any statement. For example, the
statement, d = 34*a;, will generate a compiler error */
Cerebot_mx7cK_setup(); /* Initialize Cerebot MX7ck on board resources */
while(1) /* Infinite application loop */
{
a = ac; /* Initialize variables a and b. */
b = bc;
no_swap(a, b); /* Call swapping functions */
c = swap(&a, &b);
a = c - d; /* Math statement */
}
return(1); /* A program developed for the embedded system should never
be able to execute this return instruction. - Why??? */
} /* End of main */
/* no_swap FUNCTION DESCRIPTION ********************************************
* SYNTAX: void no_swap(int x, int y)
* KEYWORDS: swap, exchange, pass by value
* DESCRIPTION: This function swaps the values in variables x and y. Since
* the variables are passed by value, the results are lost once
* the program execution returns from this function.
* PARAMETER1: first integer value
* PARAMETER2: second integer value
* RETURN VALUE: None.
*
* NOTES: Variables passed by value in the argument list are local
* considered to be variables. Variables declared inside the
* function are also local variables provided they are not
* declared as static.
* END DESCRIPTION **********************************************************/
void no_swap(int x, int y)
{
int z; /* Temporary local variable */
z = x; /* Execute the exchange of values*/
x = y;
y = z;
} /* End of no_swap funbction */
/* swap FUNCTION DESCRIPTION ************************************************
* SYNTAX: void swap(int ^x, int *y)
* KEYWORDS: swap, exchange, pass by reference
* DESCRIPTION: This function swaps the values of variables whose address are
* passed as x and y. Since the variables are passed by reference,
* the results are not lost once the function is done.
* PARAMETER1: first integer value
* PARAMETER2: second integer value
* RETURN VALUE: Sum of x and y.
*
* NOTES: Variables that are passed by reference appear in the MPLAB
* locals window. Local variables that are declared as static
* can be viewed in the watch window.
* END DESCRIPTION **********************************************************/
int swap(int *x, int *y)
{
int z; /* Temporary local variable */
z = *x; /* Execute the exchange of values */
*x = *y;
*y = z;
z = *x +*y;
return z;
} /* End of swap function */
/* End of Lab0.c */
|
"""
```julia
using DifferentialEquations, Plots
function lorenz!(du,u,p,t)
du[1] = 10.0*(u[2]-u[1])
du[2] = u[1]*(28.0-u[3]) - u[2]
du[3] = u[1]*u[2] - (8/3)*u[3]
end
u0 = [1.0;0.0;0.0]
tspan = (0.0,100.0)
prob = ODEProblem(lorenz!,u0,tspan)
sol = solve(prob)
plot(sol)
```
"""
module DifferentialEquations
using Reexport
@reexport using DiffEqBase
@reexport using DiffEqNoiseProcess
@reexport using RecursiveArrayTools
@reexport using SteadyStateDiffEq
@reexport using StochasticDiffEq
@reexport using OrdinaryDiffEq
@reexport using BoundaryValueDiffEq
using Sundials
@reexport using DelayDiffEq
@reexport using DiffEqCallbacks
@reexport using DiffEqJump
@reexport using DiffEqFinancial
@reexport using MultiScaleArrays
@reexport using DiffEqPhysics
@reexport using DimensionalPlotRecipes
@reexport using ParameterizedFunctions
using LinearAlgebra
import DiffEqBase: solve
include("default_solve.jl")
include("default_arg_parsing.jl")
include("ode_default_alg.jl")
include("sde_default_alg.jl")
include("dae_default_alg.jl")
include("dde_default_alg.jl")
include("discrete_default_alg.jl")
include("rode_default_alg.jl")
include("steady_state_default_alg.jl")
include("bvp_default_alg.jl")
end # module
|
using System;
using System.Xml;
namespace WebApplication
{
/// <summary>
/// Summary description for XmlAcmeResponseError.
/// </summary>
public class XmlAcmeResponseError : XmlAcmeResponse
{
#region Constructors
/// <summary>
/// Create an instance of XmlAcmeResponseError.
/// </summary>
/// <param name="e"></param>
public XmlAcmeResponseError(AcmeException e)
: base(e.StatusCode)
{
Exception = e;
ErrorMessage = e.Message;
}
/// <summary>
/// Create an instance of XmlAcmeResponseError.
/// </summary>
/// <param name="e"></param>
/// <param name="statusCode">The status code.</param>
public XmlAcmeResponseError(Exception? e, AcmeStatusCode statusCode)
: base(statusCode)
{
Exception = e;
ErrorMessage = e?.Message ?? statusCode.GetDescription();
}
/// <summary>
/// Create an instance of XmlAcmeResponseError.
/// </summary>
/// <param name="e"></param>
/// <param name="errorMessage">The error message.</param>
/// <param name="statusCode">The status code.</param>
public XmlAcmeResponseError(Exception? e, string errorMessage, AcmeStatusCode statusCode)
: base(statusCode)
{
Exception = e;
ErrorMessage = errorMessage;
}
#endregion
#region Non-serialized Properties
/// <summary></summary>
public string ErrorMessage { get; set; }
/// <summary></summary>
public Exception? Exception { get; set; }
#endregion
#region IRenderXml Implementation
/// <summary>
/// Render the current instance to the specified <see cref="T:XmlWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="T:XmlWriter"/>.</param>
public override void RenderXml(XmlWriter writer)
{
base.RenderStartResponse(writer);
base.RenderEndResponse(writer);
}
#endregion
}
}
|
/*
*************************************************************************************
* Copyright 2011 Normation SAS
*************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*************************************************************************************
*/
package com.normation.authorization
import java.security.Principal
/**
* This class define the main method to interact with
* authorization questions.
* Methods allow to answer to questions like:
* "Does PRINCIPAL have RIGHTS on TARGETS"
*
*/
trait AuthorizationService {
/**
* Check if the given principal has all the rights in rights on the given target
* @param principal
* the principal for whom the authorization has to be perform
* @param rights
* the set of AuthorizationType to check
* @param target
* the target on which we want to check rights for principal
* @return false if any AuthorizationType in rights is missing for principal on target.
*/
def isAllowed(principal:Principal, right: AuthorizationType, target:String) : Boolean
/**
* Check on what target from the list principal has rights.
*
* @param principal
* the principal for whom the authorization has to be perform
* @param rights
* the set of AuthorizationType to check
* @param target
* the list of targets on which we want to check rights for principal
* @return the list of targets from targets parameter on which principal has rights, or
* empty collection if principal has rights on zero target.
*/
def isAllowed(principal:Principal, rights: AuthorizationType, targets:String*) : Traversable[String]
/**
* Check if the given principal has all the rights in rights on the given target
* @param principal
* the principal for whom the authorization has to be perform
* @param rights
* the set of AuthorizationType to check
* @param target
* the target on which we want to check rights for principal
* @return false if any AuthorizationType in rights is missing for principal on target.
*/
def isAllowed(principal:Principal, rights: Rights, target:String) : Boolean
/**
* Check on what target from the list principal has rights.
*
* @param principal
* the principal for whom the authorization has to be perform
* @param rights
* the set of AuthorizationType to check
* @param target
* the list of targets on which we want to check rights for principal
* @return the list of targets from targets parameter on which principal has rights, or
* empty collection if principal has rights on zero target.
*/
def isAllowed(principal:Principal, rights: Rights, targets:String*) : Traversable[String]
} |
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_jellow/model/moments_vo.dart';
import 'package:flutter_jellow/pages/moments/photo_view_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_screenutil/size_extension.dart';
Widget multiImage(BuildContext context, List<Picture> list) {
int length = list?.length ?? 0;
if (length == 0) {
return Container();
}
final imageUrls = list.map((it) => it.picUrl).toList();
if (length == 1) {
final image = list.first;
if (image.width > image.height) {
return imageViewer(
context: context,
index: 0,
child: Image.network(
image.middlePicUrl,
width: 200.w,
fit: BoxFit.cover,
),
photoUrls: imageUrls);
} else {
return imageViewer(
context: context,
index: 0,
child: Image.network(
image.middlePicUrl,
height: 200.h,
),
photoUrls: imageUrls);
}
} else {
int remain = length;
final widgets = <Widget>[];
while (remain > 0) {
int take = 0;
if ((remain ~/ 3) > 0) {
take = 3;
} else {
take = remain % 3;
}
remain = remain - take;
final row = imageRow(
context, list.sublist(remain, remain + take), remain, imageUrls);
widgets.add(row);
}
final newWidgets = <Widget>[];
for (int i = widgets.length - 1; i >= 0; i--) {
newWidgets.add(widgets[i]);
if (i != 0) {
newWidgets.add(SizedBox(
height: 1.h,
));
}
}
return Column(mainAxisSize: MainAxisSize.min, children: newWidgets);
}
}
Widget imageRow(BuildContext context, List<Picture> list, int startIndex,
List<String> imageUrls) {
assert(list.length <= 3, 'length must <= 3: ${list.length}');
double width = list.length == 1 ? 362 : 360 / list.length;
final widgets = <Widget>[];
for (int i = 0; i < list.length; i++) {
widgets.add(imageViewer(
context: context,
index: startIndex + i,
child: ConstrainedBox(
child: Image.network(
list.length == 1 ? list[i].middlePicUrl : list[i].thumbnailUrl,
width: width.w,
height: width.h,
fit: BoxFit.cover,
),
constraints: BoxConstraints(maxHeight: 150.h),
),
photoUrls: imageUrls));
// 不是最后一个, 添加一个间隔
if (i != list.length - 1) {
widgets.add(SizedBox(
width: 1.w,
));
}
}
return Row(children: widgets);
}
Widget imageViewer(
{@required BuildContext context,
@required int index,
@required Widget child,
@required photoUrls}) {
return GestureDetector(
onTap: () {
Navigator.of(context)
.push(new MaterialPageRoute(builder: (BuildContext context) {
return new PhotoViewPage(
photoUrls: photoUrls,
initIndex: index,
);
}));
},
child: child,
);
}
/// 缓存图片
Widget imageCached(
String url, {
double width = 48,
double height = 48,
EdgeInsetsGeometry margin,
}) {
return CachedNetworkImage(
imageUrl: url,
imageBuilder: (context, imageProvider) => Container(
height: height.h,
width: width.w,
margin: margin,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
// colorFilter: ColorFilter.mode(Colors.red, BlendMode.colorBurn),
),
),
),
placeholder: (context, url) {
return Container(
alignment: Alignment.center,
child: CircularProgressIndicator(),
);
},
errorWidget: (context, url, error) => Icon(Icons.error),
);
}
|
package com.hamrah.akka.persistence.rocksdb
package journal
import akka.persistence.journal._
import com.typesafe.config.ConfigFactory
import akka.actor._
import akka.testkit._
import org.scalatest._
import org.rocksdb._
import java.io.File
import org.apache.commons.io.FileUtils
class RocksDbJournalSpec
extends JournalSpec {
lazy val config = ConfigFactory.parseString(
s"""
|rocksdb-journal.dir = "target/journal-spec"
|akka.persistence.journal.plugin = "rocksdb-journal"
""".stripMargin
)
val storageLocations = List(
new File(system.settings.config.getString("rocksdb-journal.dir"))
)
override def beforeAll() {
super.beforeAll()
storageLocations foreach FileUtils.deleteDirectory
}
override def afterAll() {
storageLocations foreach FileUtils.deleteDirectory
super.afterAll()
}
}
|
require 'pathname'
module Blog
# Blog CLI
class CLI
HELP_MESSAGE = <<~TEXT.freeze
Usage:
blog build <source>
blog serve <source>
blog -h | --help
Options:
-h --help Show this message
TEXT
private_constant :HELP_MESSAGE
# @param [ARGV, Array<String>] arguments the arguments to +blog+ command.
# @param [IO] output output stream for messages
# @param [IO] error_output output stream for error messages
def initialize(arguments: ARGV, output: $stdout, error_output: $stderr)
@arguments = arguments
@output = output
@error_output = error_output
end
# Run +blog+ command with arguments
def run
stop_with HELP_MESSAGE if help_needed?
stop_with 'usage: blog (build | serve) <source>' if source.nil?
stop_with "command not found: #{@arguments.first}" if command.nil?
command.run
end
private
# @param [String] message message printed when exit
def stop_with(message)
@error_output.puts message
exit 1
end
# @return [Boolean] whether CLI is needed for help
def help_needed?
@arguments.include?('-h') || @arguments.include?('--help')
end
# @return [Pathname] path to the directory Post data are persisted
def source
@source ||= @arguments.length >= 2 ? Pathname.pwd.join(@arguments[1]) : nil
end
# @return [Command::Build, nil] command found by arguments
def command
@command ||= case @arguments.first
when 'build'
Build.new(source: source)
when 'serve'
Serve.new(source: source)
end
end
end
end
|
************************************************************************
* This file implements heapsort strategies for arrays.
************************************************************************
************************************************************************
* Heapsort for integer arrays
*
* This routine accepts a 2D array, i.e. an array of arrays with data
* of the same type. Each sub-array is treated as a node. The routine
* sorts these nodes in ascending order according to a criterium using
* standard heapsort. An index identifies the guiding element in
* each array-node heapsort uses for determining the order.
*
* In:
* N - Number of sub-arrays / array-nodes
* SIZE - Size of each node = number of elements in each sub-array
* ELMS - array [1..SIZE,1..N] of integer
* The elements that are to be sorted
* IDX - integer, 1..SIZE. Index of the key integer inside of a
* subarray that serves for determining the order
*
* Out:
* ELMS - Resorted element arrays.
*
************************************************************************
* Remark: Although "bottom-up" heap-sort would be a little bit cheaper,
* the standard heap-sort is easier to implement, so we use that one...
SUBROUTINE HSRTIN (N,SIZE,ELMS,IDX)
IMPLICIT NONE
INTEGER N,SIZE,IDX
INTEGER ELMS(SIZE,N)
C local variables
INTEGER I,J
INTEGER VTMP
C Heap setup phase.
C Loop through all sub-trees and ensure the inverse heap property:
C largest element on the root. Of course we don't have to take care
C about the leaves...
DO I=N/2,1,-1
CALL HSRHIN (N,SIZE,I,ELMS,IDX)
END DO
C Now we have to move the largest elements to the bottom. Loop through
C all elements:
DO I=N,2,-1
C Exchange the current root I with the topmost element, which is
C the currently largest:
DO J=1,SIZE
VTMP = ELMS(J,I)
ELMS(J,I) = ELMS(J,1)
ELMS(J,1) = VTMP
END DO
C The main root lacks the inversed heap property; reheap to
C reensure it, Root=topmost root, only I-1 elements in the
C tree (as the elements I..N are already sorted):
CALL HSRHIN (I-1,SIZE,1,ELMS,IDX)
END DO
END
************************************************************************
* Bottom-up heapsort, reheap subroutine
*
* This subroutine implements the reheap phase for the heapsort
* algorithm. It assures that a subtree of the whole tree fulfills
* the inverse heap property (largest element on the root).
*
* In:
* N - Number of sub-arrays / array-nodes
* SIZE - Size of each node = number of elements in each sub-array
* ROOT - Index of the root inside of the element tree
* ELMS - array [1..SIZE,1..N] of integer
* The elements that are to be sorted
* IDX - integer, 1..SIZE. Index of the key integer inside of a
* subarray that serves for determining the order
*
* Out:
* ELMS - Resorted element arrays.
************************************************************************
SUBROUTINE HSRHIN (N,SIZE,ROOT,ELMS,IDX)
IMPLICIT NONE
INTEGER N,SIZE,ROOT,IDX
INTEGER ELMS(SIZE,N)
C local variables
INTEGER CNDE,RCH,LCH,XC,I
INTEGER VAL,VTMP
C We use the "inversed heap property" (largest element on the root
C instead of smallest element), since we want to sort in ascending
C order.
C
C We assume that the two subtrees below our root fulfill the inversed
C heap property, only the root might violate this.
C
C We start with the node on the root:
CNDE = ROOT
C Its value is taken from the sub-array
VAL = ELMS(IDX,CNDE)
C Crippled Do-While-Loop
10 CONTINUE
C CNDE*2 gives the left child, CNDE*2+1 the right child.
C XC denotes a found child that is larger and has to be exchanged
C with our current node.
XC = 0
LCH=2*CNDE
RCH=2*CNDE+1
C One or two children?
IF (RCH.LE.N) THEN
C Is the right child larger
IF (ELMS(IDX,RCH).GT.VAL) THEN
XC = RCH
C Left child even larger?
IF (ELMS(IDX,LCH).GT.ELMS(IDX,XC)) XC = LCH
ELSE
C Left child larger?
IF (ELMS(IDX,LCH).GT.VAL) XC = LCH
END IF
ELSE IF (LCH.LE.N) THEN
IF (ELMS(IDX,LCH).GT.VAL) THEN
C Only one child - and it is larger
XC = LCH
END IF
END IF
C If a larger child was found (XC<>0), exchange that with our current
C node and continue the search in the lower sub-tree.
C The search ends if no larger element was found or the
C bottom of the tree is reached.
IF (XC.NE.0) THEN
DO I=1,SIZE
VTMP = ELMS(I,XC)
ELMS(I,XC) = ELMS(I,CNDE)
ELMS(I,CNDE) = VTMP
END DO
CNDE = XC
END IF
IF (XC.NE.0) GOTO 10
END
|
lui $1,35117
ori $1,$1,33896
lui $2,64975
ori $2,$2,47349
lui $3,39921
ori $3,$3,13256
lui $4,30093
ori $4,$4,7286
lui $5,60867
ori $5,$5,53937
lui $6,63760
ori $6,$6,27844
mthi $1
mtlo $2
sec0:
nop
nop
nop
slt $5,$6,$2
sec1:
nop
nop
sltu $6,$1,$1
slt $5,$6,$2
sec2:
nop
nop
lui $6,20852
slt $0,$6,$2
sec3:
nop
nop
mflo $6
slt $3,$6,$2
sec4:
nop
nop
lbu $6,8($0)
slt $5,$6,$2
sec5:
nop
and $2,$4,$3
nop
slt $4,$6,$2
sec6:
nop
slt $2,$6,$4
or $6,$1,$3
slt $4,$6,$2
sec7:
nop
and $2,$3,$2
lui $6,7773
slt $5,$6,$2
sec8:
nop
slt $2,$2,$4
mflo $6
slt $3,$6,$2
sec9:
nop
slt $2,$3,$5
lb $6,8($0)
slt $4,$6,$2
sec10:
nop
andi $2,$6,27068
nop
slt $2,$6,$2
sec11:
nop
lui $2,57446
subu $6,$3,$1
slt $3,$6,$2
sec12:
nop
ori $2,$2,37366
slti $6,$0,26101
slt $2,$6,$2
sec13:
nop
xori $2,$0,12465
mflo $6
slt $3,$6,$2
sec14:
nop
ori $2,$5,50717
lb $6,12($0)
slt $1,$6,$2
sec15:
nop
mfhi $2
nop
slt $3,$6,$2
sec16:
nop
mflo $2
or $6,$4,$4
slt $2,$6,$2
sec17:
nop
mflo $2
xori $6,$1,14602
slt $6,$6,$2
sec18:
nop
mfhi $2
mfhi $6
slt $3,$6,$2
sec19:
nop
mflo $2
lb $6,2($0)
slt $2,$6,$2
sec20:
nop
lh $2,4($0)
nop
slt $3,$6,$2
sec21:
nop
lb $2,13($0)
subu $6,$5,$3
slt $3,$6,$2
sec22:
nop
lw $2,4($0)
ori $6,$3,22411
slt $3,$6,$2
sec23:
nop
lbu $2,13($0)
mfhi $6
slt $3,$6,$2
sec24:
nop
lw $2,16($0)
lw $6,8($0)
slt $0,$6,$2
sec25:
slt $6,$4,$2
nop
nop
slt $2,$6,$2
sec26:
addu $6,$3,$4
nop
addu $6,$1,$3
slt $1,$6,$2
sec27:
xor $6,$3,$0
nop
lui $6,30998
slt $3,$6,$2
sec28:
sltu $6,$3,$4
nop
mflo $6
slt $1,$6,$2
sec29:
or $6,$4,$6
nop
lbu $6,2($0)
slt $5,$6,$2
sec30:
sltu $6,$5,$0
and $2,$4,$0
nop
slt $5,$6,$2
sec31:
subu $6,$5,$0
or $2,$4,$3
xor $6,$5,$0
slt $4,$6,$2
sec32:
slt $6,$4,$3
xor $2,$4,$0
sltiu $6,$4,-9603
slt $0,$6,$2
sec33:
nor $6,$3,$2
and $2,$6,$2
mfhi $6
slt $2,$6,$2
sec34:
sltu $6,$4,$5
nor $2,$4,$3
lbu $6,2($0)
slt $4,$6,$2
sec35:
nor $6,$4,$4
ori $2,$4,8727
nop
slt $1,$6,$2
sec36:
subu $6,$6,$1
xori $2,$4,40702
and $6,$1,$3
slt $1,$6,$2
sec37:
sltu $6,$3,$3
ori $2,$2,26209
andi $6,$2,17186
slt $3,$6,$2
sec38:
slt $6,$2,$3
xori $2,$4,58925
mflo $6
slt $0,$6,$2
sec39:
addu $6,$2,$0
addiu $2,$4,23838
lbu $6,8($0)
slt $3,$6,$2
sec40:
addu $6,$3,$4
mfhi $2
nop
slt $3,$6,$2
sec41:
addu $6,$2,$4
mfhi $2
subu $6,$3,$3
slt $3,$6,$2
sec42:
addu $6,$5,$3
mfhi $2
slti $6,$2,-3701
slt $4,$6,$2
sec43:
xor $6,$3,$4
mfhi $2
mfhi $6
slt $0,$6,$2
sec44:
subu $6,$2,$3
mfhi $2
lhu $6,6($0)
slt $1,$6,$2
sec45:
or $6,$3,$2
lhu $2,16($0)
nop
slt $1,$6,$2
sec46:
nor $6,$2,$1
lbu $2,6($0)
subu $6,$4,$3
slt $1,$6,$2
sec47:
subu $6,$4,$3
lh $2,6($0)
lui $6,47773
slt $3,$6,$2
sec48:
addu $6,$2,$2
lh $2,14($0)
mflo $6
slt $3,$6,$2
sec49:
xor $6,$3,$2
lw $2,0($0)
lw $6,8($0)
slt $3,$6,$2
sec50:
addiu $6,$5,12570
nop
nop
slt $1,$6,$2
sec51:
slti $6,$4,-4081
nop
sltu $6,$2,$3
slt $2,$6,$2
sec52:
slti $6,$2,22819
nop
lui $6,44322
slt $2,$6,$2
sec53:
andi $6,$2,14996
nop
mflo $6
slt $6,$6,$2
sec54:
lui $6,2154
nop
lh $6,12($0)
slt $5,$6,$2
sec55:
slti $6,$3,21860
and $2,$3,$3
nop
slt $4,$6,$2
sec56:
andi $6,$3,30482
sltu $2,$2,$2
slt $6,$6,$3
slt $6,$6,$2
sec57:
xori $6,$5,64755
subu $2,$2,$1
andi $6,$2,29521
slt $3,$6,$2
sec58:
addiu $6,$4,-24275
subu $2,$2,$3
mfhi $6
slt $3,$6,$2
sec59:
sltiu $6,$1,-7539
or $2,$0,$4
lh $6,16($0)
slt $1,$6,$2
sec60:
xori $6,$5,712
xori $2,$6,7052
nop
slt $4,$6,$2
sec61:
sltiu $6,$3,-15629
addiu $2,$0,22729
slt $6,$3,$3
slt $3,$6,$2
sec62:
andi $6,$1,14118
sltiu $2,$4,-12812
xori $6,$4,57194
slt $1,$6,$2
sec63:
lui $6,19897
sltiu $2,$5,29537
mflo $6
slt $5,$6,$2
sec64:
xori $6,$6,14707
lui $2,61203
lhu $6,2($0)
slt $6,$6,$2
sec65:
lui $6,8585
mflo $2
nop
slt $4,$6,$2
sec66:
sltiu $6,$3,-4475
mfhi $2
sltu $6,$2,$4
slt $1,$6,$2
sec67:
xori $6,$3,57711
mfhi $2
sltiu $6,$5,-26234
slt $4,$6,$2
sec68:
xori $6,$3,23172
mfhi $2
mfhi $6
slt $3,$6,$2
sec69:
lui $6,10258
mfhi $2
lhu $6,10($0)
slt $5,$6,$2
sec70:
xori $6,$4,65030
lb $2,6($0)
nop
slt $5,$6,$2
sec71:
ori $6,$3,39629
lbu $2,10($0)
or $6,$5,$1
slt $1,$6,$2
sec72:
slti $6,$2,-21039
lhu $2,0($0)
lui $6,32686
slt $5,$6,$2
sec73:
andi $6,$4,6866
lbu $2,7($0)
mfhi $6
slt $3,$6,$2
sec74:
lui $6,42994
lh $2,10($0)
lh $6,2($0)
slt $2,$6,$2
sec75:
mfhi $6
nop
nop
slt $1,$6,$2
sec76:
mflo $6
nop
addu $6,$2,$1
slt $3,$6,$2
sec77:
mflo $6
nop
slti $6,$4,5657
slt $2,$6,$2
sec78:
mflo $6
nop
mfhi $6
slt $4,$6,$2
sec79:
mflo $6
nop
lw $6,12($0)
slt $1,$6,$2
sec80:
mfhi $6
slt $2,$5,$2
nop
slt $1,$6,$2
sec81:
mflo $6
sltu $2,$3,$4
sltu $6,$2,$6
slt $3,$6,$2
sec82:
mflo $6
nor $2,$2,$2
addiu $6,$1,-14120
slt $4,$6,$2
sec83:
mflo $6
subu $2,$1,$3
mfhi $6
slt $3,$6,$2
sec84:
mfhi $6
or $2,$3,$4
lh $6,12($0)
slt $4,$6,$2
sec85:
mfhi $6
lui $2,65128
nop
slt $2,$6,$2
sec86:
mfhi $6
ori $2,$3,53468
subu $6,$3,$1
slt $4,$6,$2
sec87:
mflo $6
ori $2,$0,53490
sltiu $6,$4,-28346
slt $4,$6,$2
sec88:
mfhi $6
addiu $2,$2,-26745
mfhi $6
slt $5,$6,$2
sec89:
mflo $6
xori $2,$5,18552
lbu $6,9($0)
slt $2,$6,$2
sec90:
mflo $6
mfhi $2
nop
slt $2,$6,$2
sec91:
mfhi $6
mfhi $2
and $6,$0,$3
slt $0,$6,$2
sec92:
mfhi $6
mflo $2
addiu $6,$3,-17157
slt $6,$6,$2
sec93:
mfhi $6
mflo $2
mflo $6
slt $2,$6,$2
sec94:
mfhi $6
mfhi $2
lb $6,15($0)
slt $3,$6,$2
sec95:
mfhi $6
lbu $2,11($0)
nop
slt $3,$6,$2
sec96:
mfhi $6
lbu $2,1($0)
sltu $6,$4,$5
slt $1,$6,$2
sec97:
mfhi $6
lhu $2,6($0)
xori $6,$0,29815
slt $3,$6,$2
sec98:
mflo $6
lw $2,12($0)
mfhi $6
slt $2,$6,$2
sec99:
mfhi $6
lb $2,11($0)
lbu $6,13($0)
slt $2,$6,$2
sec100:
lh $6,14($0)
nop
nop
slt $4,$6,$2
sec101:
lbu $6,6($0)
nop
addu $6,$1,$1
slt $1,$6,$2
sec102:
lw $6,4($0)
nop
addiu $6,$6,-18550
slt $1,$6,$2
sec103:
lhu $6,2($0)
nop
mflo $6
slt $5,$6,$2
sec104:
lbu $6,2($0)
nop
lhu $6,2($0)
slt $2,$6,$2
sec105:
lhu $6,2($0)
and $2,$3,$1
nop
slt $4,$6,$2
sec106:
lhu $6,16($0)
nor $2,$4,$6
or $6,$6,$4
slt $5,$6,$2
sec107:
lh $6,8($0)
subu $2,$5,$3
slti $6,$2,-17788
slt $3,$6,$2
sec108:
lb $6,5($0)
or $2,$3,$4
mfhi $6
slt $5,$6,$2
sec109:
lw $6,16($0)
slt $2,$5,$4
lbu $6,1($0)
slt $6,$6,$2
sec110:
lh $6,8($0)
slti $2,$1,18480
nop
slt $5,$6,$2
sec111:
lbu $6,0($0)
lui $2,63285
or $6,$2,$2
slt $0,$6,$2
sec112:
lbu $6,0($0)
slti $2,$1,-1694
ori $6,$2,56191
slt $6,$6,$2
sec113:
lh $6,12($0)
lui $2,14490
mflo $6
slt $3,$6,$2
sec114:
lh $6,6($0)
ori $2,$3,54982
lw $6,16($0)
slt $3,$6,$2
sec115:
lb $6,16($0)
mflo $2
nop
slt $6,$6,$2
sec116:
lh $6,4($0)
mfhi $2
and $6,$3,$3
slt $1,$6,$2
sec117:
lb $6,3($0)
mflo $2
andi $6,$3,65159
slt $1,$6,$2
sec118:
lb $6,1($0)
mflo $2
mflo $6
slt $2,$6,$2
sec119:
lw $6,12($0)
mfhi $2
lw $6,0($0)
slt $1,$6,$2
sec120:
lbu $6,6($0)
lb $2,15($0)
nop
slt $5,$6,$2
sec121:
lhu $6,8($0)
lbu $2,5($0)
or $6,$4,$2
slt $0,$6,$2
sec122:
lh $6,0($0)
lhu $2,14($0)
addiu $6,$4,27629
slt $6,$6,$2
sec123:
lh $6,6($0)
lb $2,16($0)
mflo $6
slt $5,$6,$2
sec124:
lw $6,8($0)
lbu $2,4($0)
lw $6,12($0)
slt $4,$6,$2
|
---
layout: page
title: "JavaScript runkit_method_add function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/runkit_method_add:813
- /functions/view/runkit_method_add
- /functions/view/813
- /functions/runkit_method_add:813
- /functions/813
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's runkit_method_add
{% codeblock runkit/runkit_method_add.js lang:js https://raw.github.com/kvz/phpjs/master/functions/runkit/runkit_method_add.js raw on github %}
function runkit_method_add (classname, methodname, args, code, flags) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// * example 1: function a (){}
// * example 1: runkit_method_add ('a', 'b', 'a,b', 'return a+b');
// * returns 1: true
var func, argmnts = [];
switch (flags) {
case 'RUNKIT_ACC_PROTECTED':
throw 'Protected not supported';
case 'RUNKIT_ACC_PRIVATE':
throw 'Private not supported';
case 'RUNKIT_ACC_PUBLIC':
default:
break;
}
argmnts = args.split(/,\s*/);
if (typeof classname === 'string') {
classname = this.window[classname];
}
// Could use the following to add as a static method to the class
// func = Function.apply(null, argmnts.concat(code));
// classname[methodname] = func;
func = Function.apply(null, argmnts.concat(code));
classname.prototype[methodname] = func;
return true;
}
{% endcodeblock %}
- [view on github](https://github.com/kvz/phpjs/blob/master/functions/runkit/runkit_method_add.js)
- [edit on github](https://github.com/kvz/phpjs/edit/master/functions/runkit/runkit_method_add.js)
### Example 1
This code
{% codeblock lang:js example %}
function a (){}
runkit_method_add ('a', 'b', 'a,b', 'return a+b');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
true
{% endcodeblock %}
### Other PHP functions in the runkit extension
{% render_partial _includes/custom/runkit.html %}
|
C***********************************************************************
C Module: avl.f
C
C Copyright (C) 2002 Mark Drela, Harold Youngren
C
C This program is free software; you can redistribute it and/or modify
C it under the terms of the GNU General Public License as published by
C the Free Software Foundation; either version 2 of the License, or
C (at your option) any later version.
C
C This program is distributed in the hope that it will be useful,
C but WITHOUT ANY WARRANTY; without even the implied warranty of
C MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
C GNU General Public License for more details.
C
C You should have received a copy of the GNU General Public License
C along with this program; if not, write to the Free Software
C Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
C***********************************************************************
PROGRAM AVL
C=======================================================================
C 3-D Vortex Lattice code.
C See file avl_doc.txt for user guide.
C See file version_notes.txt for most recent changes.
C=======================================================================
INCLUDE 'AVL.INC'
INCLUDE 'AVLPLT.INC'
LOGICAL ERROR
C
CHARACTER*4 COMAND
CHARACTER*128 COMARG
CHARACTER*80 FNNEW
C
REAL RINPUT(20)
INTEGER IINPUT(20)
C
C
VERSION = 3.35
C
1000 FORMAT(A)
C
WRITE (*,1005) VERSION
1005 FORMAT (
& /' ==================================================='
& /' Athena Vortex Lattice Program Version ',F5.2
& /' Copyright (C) 2002 Mark Drela, Harold Youngren'
& //' This software comes with ABSOLUTELY NO WARRANTY,'
& /' subject to the GNU General Public License.'
& //' Caveat computor'
& /' ===================================================')
C
C
PI = 4.0*ATAN(1.0)
DTR = PI/180.0
C
C---- logical units
LUINP = 4 ! configuration file
LURUN = 7 ! run case file
LUMAS = 8 ! mass file
LUPRM = 9 ! parameter file
LUOUT = 19 ! output dump file
LUSTD = 20 ! stability derivative dump file
LUSYS = 22 ! dynamic system matrix dump file
C
C---- set basic defaults
CALL DEFINI
CALL MASINI
C
C---- initialize Xplot, and AVL plot stuff
CALL PLINIT
C
C
C---- Read a new input geometry from input file
CALL GETARG0(1,FILDEF)
C
IF(FILDEF.NE.' ') THEN
CALL INPUT(LUINP,FILDEF,ERROR)
C
C----- no valid geometry... skip reading run and mass files
IF(ERROR) GO TO 100
C
C----- set up all parameters
CALL PARSET
C
C----- process geometry to define strip and vortex data
LPLTNEW = .TRUE.
CALL ENCALC
C
C----- initialize state
CALL VARINI
C
ELSE
C----- no geometry... skip reading run and mass files
GO TO 100
C
ENDIF
C
C-------------------------------------------------------------------
C---- try to read mass file
CALL GETARG0(3,FMSDEF)
IF(FMSDEF.EQ.' ') THEN
KDOT = INDEX(FILDEF,'.')
IF(KDOT.EQ.0) THEN
CALL STRIP(FILDEF,LENF)
FMSDEF = FILDEF(1:LENF) // '.mass'
ELSE
FMSDEF = FILDEF(1:KDOT) // 'mass'
ENDIF
ENDIF
C
CALL STRIP(FMSDEF,NMS)
WRITE(*,*)
WRITE(*,*)
& '---------------------------------------------------------------'
WRITE(*,*) 'Trying to read file: ', FMSDEF(1:NMS), ' ...'
CALL MASGET(LUMAS,FMSDEF,ERROR)
C
IF(ERROR) THEN
WRITE(*,*) 'Internal mass defaults used'
CALL MASINI
C
ELSE
WRITE(*,*)
WRITE(*,*) 'Mass distribution read ...'
CALL MASSHO(6)
C
CALL APPGET
WRITE(*,*)
& '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
CALL APPSHO(6,RHO0)
C
ENDIF
C
C-------------------------------------------------------------------
C---- try to read run case file
CALL GETARG0(2,FRNDEF)
IF(FRNDEF.EQ.' ') THEN
KDOT = INDEX(FILDEF,'.')
IF(KDOT.EQ.0) THEN
CALL STRIP(FILDEF,LENF)
FRNDEF = FILDEF(1:LENF) // '.run'
ELSE
FRNDEF = FILDEF(1:KDOT) // 'run'
ENDIF
ENDIF
C
CALL STRIP(FRNDEF,NFR)
WRITE(*,*)
WRITE(*,*)
& '---------------------------------------------------------------'
WRITE(*,*) 'Trying to read file: ', FRNDEF(1:NFR), ' ...'
CALL RUNGET(LURUN,FRNDEF,ERROR)
C
IF(ERROR) THEN
WRITE(*,*) 'Internal run case defaults used'
CALL RUNINI
C
ELSE
WRITE(*,1025) (IR, RTITLE(IR), IR=1, NRUN)
1025 FORMAT(//' Run cases read ...',
& 100(/1X,I4,': ',A))
C
ENDIF
C
C-------------------------------------------------------------------
100 CONTINUE
C
C---- set up plotting parameters for geometry (if any)
CALL PLPARS
C
WRITE(*,2000)
2000 FORMAT(
& /' =========================================================='
& /' Quit Exit program'
& //' .OPER Compute operating-point run cases'
& /' .MODE Eigenvalue analysis of run cases'
& /' .TIME Time-domain calculations'
& //' LOAD f Read configuration input file'
& /' MASS f Read mass distribution file'
& /' CASE f Read run case file'
& //' CINI Clear and initialize run cases'
& /' MSET i Apply mass file data to stored run case(s)'
& //' .PLOP Plotting options'
& /' NAME s Specify new configuration name')
C
C======================================================================
C---- start of menu loop
500 CONTINUE
CALL ASKC(' AVL^',COMAND,COMARG)
C
C---- extract command line numeric arguments
DO I=1, 20
IINPUT(I) = 0
RINPUT(I) = 0.0
ENDDO
NINPUT = 20
CALL GETINT(COMARG,IINPUT,NINPUT,ERROR)
NINPUT = 20
CALL GETFLT(COMARG,RINPUT,NINPUT,ERROR)
C
C===============================================
IF(COMAND.EQ.' ') THEN
GO TO 500
C
C===============================================
ELSEIF(COMAND.EQ.'? ') THEN
WRITE(*,2000)
C
C===============================================
ELSEIF(COMAND.EQ.'QUIT' .OR.
& COMAND.EQ.'Q ' ) THEN
CALL PLCLOSE
STOP
C
C===============================================
ELSEIF(COMAND.EQ.'OPER') THEN
CALL OPER
C
C===============================================
ELSEIF(COMAND.EQ.'MODE') THEN
CALL MODE
C
C===============================================
ELSEIF(COMAND.EQ.'TIME') THEN
ccc CALL TIME
C
C===============================================
ELSE IF(COMAND.EQ.'LOAD') THEN
C----- Read a new input geometry from input file
IF(COMARG.NE.' ') THEN
FILDEF = COMARG
C
ELSE
CALL STRIP(FILDEF,LENF)
LENF1 = MAX(LENF,1)
C
WRITE(*,2010) FILDEF(1:LENF1)
2010 FORMAT(' Enter input filename: ', A)
READ (*,1000) FNNEW
C
IF(FNNEW.EQ.' ') THEN
IF(LENF.EQ.0) GO TO 500
ELSE
FILDEF = FNNEW
ENDIF
C
ENDIF
C
CALL INPUT(LUINP,FILDEF,ERROR)
IF(ERROR) THEN
WRITE(*,*)
& '** File not processed. Current geometry may be corrupted.'
GO TO 500
ENDIF
C
CALL PARSET
C
IF(NRUN.EQ.0) THEN
CALL RUNINI
ELSE
WRITE(*,*)
WRITE(*,*) 'Existing run cases will be used.'
WRITE(*,*) 'Issue CASE or CINI command if necessary.'
ENDIF
C
C----- process geometry to define strip and vortex data
LPLTNEW = .TRUE.
CALL ENCALC
C
C----- initialize state
CALL VARINI
C
LAIC = .FALSE.
LSRD = .FALSE.
LVEL = .FALSE.
LSOL = .FALSE.
LSEN = .FALSE.
C
C----- set up plotting parameters for new geometry
CALL PLPARS
C
C===============================================
ELSE IF(COMAND.EQ.'MASS') THEN
C----- Read a new mass distribution file
IF(COMARG.NE.' ') THEN
FMSDEF = COMARG
C
ELSE
CALL STRIP(FMSDEF,LENF)
LENF1 = MAX(LENF,1)
C
WRITE(*,3010) FMSDEF(1:LENF1)
3010 FORMAT(' Enter mass filename: ', A)
READ (*,1000) FNNEW
C
IF(FNNEW.EQ.' ') THEN
IF(LENF.EQ.0) GO TO 500
ELSE
FMSDEF = FNNEW
ENDIF
ENDIF
C
CALL STRIP(FMSDEF,NMS)
CALL MASGET(LUMAS,FMSDEF,ERROR)
IF(ERROR) THEN
ELSE
WRITE(*,*)
WRITE(*,*) 'Mass distribution read ...'
CALL MASSHO(6)
C
CALL APPGET
WRITE(*,*)
& '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -'
CALL APPSHO(6,RHO0)
C
WRITE(*,*)
WRITE(*,*)
& 'Use MSET to apply these mass,inertias to run cases'
ccc CALL MASPUT(1,NRMAX)
ENDIF
C
C===============================================
ELSE IF(COMAND.EQ.'CASE') THEN
C----- Read a new run case file
IF(COMARG.NE.' ') THEN
FRNDEF = COMARG
C
ELSE
CALL STRIP(FRNDEF,LENF)
LENF1 = MAX(LENF,1)
C
WRITE(*,3020) FRNDEF(1:LENF1)
3020 FORMAT(' Enter run case filename: ', A)
READ (*,1000) FNNEW
C
IF(FNNEW.EQ.' ') THEN
IF(LENF.EQ.0) GO TO 500
ELSE
FRNDEF = FNNEW
ENDIF
ENDIF
C
CALL STRIP(FRNDEF,NFR)
CALL RUNGET(LURUN,FRNDEF,ERROR)
IF(ERROR) THEN
ELSE
WRITE(*,1025) (IR, RTITLE(IR), IR=1, NRUN)
ENDIF
C
C----- initialize state
CALL VARINI
C
LSOL = .FALSE.
LSEN = .FALSE.
C
C===============================================
ELSE IF(COMAND.EQ.'CINI') THEN
IF(LGEO) THEN
CALL RUNINI
ELSE
WRITE(*,*) 'No configuration available.'
NRUN = 0
ENDIF
C
C===============================================
ELSE IF(COMAND.EQ.'MSET') THEN
C----- set input mass,inertias
IF(NINPUT.GE.1) THEN
IR1 = IINPUT(1)
ELSE
60 WRITE(*,3060)
3060 FORMAT(/
& ' Enter index of target run case (0=all, -1=abort): 0')
IR1 = 0
CALL READI(1,IR1,ERROR)
IF(ERROR) GO TO 60
ENDIF
C
IF(IR1.EQ.0) THEN
IR1 = 1
IR2 = NRUN
ELSE
IR2 = IR1
ENDIF
C
IF(IR1.LT.1 .OR. IR1.GT.NRUN) GO TO 500
C
CALL MASPUT(IR1,IR2)
C
LSOL = .FALSE.
LSEN = .FALSE.
C
C===============================================
ELSEIF(COMAND.EQ.'PLOP') THEN
CALL OPLSET(IDEV,IDEVH,IPSLU,LSVMOV,
& SIZE,PLOTAR,
& XMARG,YMARG,XPAGE,YPAGE,
& CH,SCRNFRAC,LCURS,LCREV)
C
C===============================================
ELSEIF(COMAND.EQ.'NAME') THEN
IF(COMARG.EQ.' ') THEN
CALL ASKS('Enter new name^',TITLE)
ELSE
TITLE = COMARG
ENDIF
C
C===============================================
ELSE
WRITE(*,1050) COMAND
1050 FORMAT(1X,A4,' command not recognized. Type a "?" for list')
C
ENDIF
C
GO TO 500
END ! AVL
SUBROUTINE PLINIT
C---- Initialize plotting variables
C
INCLUDE 'AVL.INC'
INCLUDE 'AVLPLT.INC'
C
REAL ORG(3)
C
C---- Plotting flag
IDEV = 1 ! X11 window only
c IDEV = 2 ! B&W PostScript output file only (no color)
c IDEV = 3 ! both X11 and B&W PostScript file
c IDEV = 4 ! Color PostScript output file only
c IDEV = 5 ! both X11 and Color PostScript file
C
C---- Re-plotting flag (for hardcopy)
c IDEVH = 2 ! B&W PostScript
IDEVH = 4 ! Color PostScript
C
C---- Movie-plotting flag
cc IDEVH = 3 ! B&W PostScript
IDEVM = 5 ! both X11 and Color PostScript file
C
LSVMOV = .FALSE. ! no movie PS output yet
C
C---- PostScript output logical unit and file specification
ccc IPSLU = -1 ! output to files plotNNN.ps on LU 80, with NNN = 001, 002, ...
IPSLU = 0 ! output to file plot.ps on LU 80 (default case)
ccc IPSLU = nnn ! output to file plotNNN.ps on LU NNN
C
C---- screen fraction taken up by plot window upon opening
SCRNFRAC = 0.70 ! Landscape
C SCRNFRAC = -0.85 ! Portrait specified if < 0
C
C---- Default plot size in inches
C- (Default plot window is 11.0 x 8.5)
SIZE = 9.0
C
C---- plot aspect ratio
PLOTAR = 0.75
C
C---- character width/SIZE
CH = 0.017
C
CALL PLINITIALIZE
C
NCOLORS = 0
C---- set up color spectrum
ccc NCOLORS = 32
ccc CALL COLORSPECTRUMHUES(NCOLORS,'RYGCBM')
C
C---- plot-window dimensions in inches for plot blowup calculations
C- currently, 11.0 x 8.5 default window is hard-wired in libPlt
XPAGE = 11.0
YPAGE = 8.5
C
XWIND = 11.0
YWIND = 8.5
C
C---- page margins in inches
XMARG = 0.0
YMARG = 0.0
C
C---- bottom,left plot margin from edge
PMARG = 0.15
C
IF(IDEV.EQ.0) THEN
LPLOT = .FALSE.
ENDIF
C
C---- set colors for run cases
DO IR = 1, NRMAX
IRCOLOR(IR) = MOD(IR-1,8) + 3
ENDDO
C
C---- set vectors for little axes
SLEN = 0.5
HLEN = 0.5
C
RHEAD = HLEN * 0.25
NHEAD = NHAXIS
C
ORG(1) = 0.
ORG(2) = 0.
ORG(3) = 0.
DO IAX = 1, 3
UAXDIR(1,IAX) = 0.
UAXDIR(2,IAX) = 0.
UAXDIR(3,IAX) = 0.
UAXDIR(IAX,IAX) = 1.0
CALL ARWSET(ORG,UAXDIR(1,IAX),SLEN,HLEN,RHEAD,NHEAD,
& UAXARW(1,1,1,IAX),NLINAX)
ENDDO
C
C---- initial phase, eigenvector scale, slo-mo scale (for mode plots)
EPHASE = 0.0
EIGENF = 1.0
SLOMOF = 1.0
TMOFAC = 1.0
RETURN
END ! PLINIT
SUBROUTINE PLPARS
INCLUDE 'AVL.INC'
INCLUDE 'AVLPLT.INC'
C
IMARKSURF = 0
DO N = 1, NSURF
LPLTSURF(N) = .TRUE.
END DO
DO N = 1, NBODY
LPLTBODY(N) = .TRUE.
END DO
C
C---- Scaling factors for velocity and pressure
CPFAC = MIN(0.4*CREF,0.1*BREF) / CREF
ENFAC = MIN(0.3*CREF,0.06*BREF) / CREF
HNFAC = MIN(CREF,0.5*BREF) / CREF
C
C---- initialize observer position angles and perspective 1/distance
AZIMOB = -45.0
ELEVOB = 20.0
TILTOB = 0.
ROBINV = 0.
C
C---- slo-mo factor
SLOMOF = 1.0
C
C---- eigenmode animation integration time step
DTIMED = 0.025
C
C---- movie-dump frame time step
DTMOVIE = 0.05
C
C---- max length of movie
TMOVIE = 10.0
C
C...Flags
LABEL_BODY = .FALSE.
LABEL_SURF = .FALSE.
LABEL_STRP = .FALSE.
LABEL_VRTX = .FALSE.
LWAKEPLT = .FALSE.
LHINGEPLT = .FALSE.
LLOADPLT = .FALSE.
LCNTLPTS = .FALSE.
LNRMLPLT = .FALSE.
LAXESPLT = .TRUE.
LRREFPLT = .TRUE.
LCLPERPLT = .TRUE.
LDWASHPLT = .TRUE.
LLABSURF = .FALSE.
LCAMBER = .FALSE.
LCHORDLINE = .TRUE.
LBOUNDLEG = .TRUE.
C
C---- Initially assume nothing hidden
LHID = .TRUE.
C
C---- Initially assume no reverse color output
LCREV = .FALSE.
C
C---- flags to plot parameter values above eigenmode map
DO IP = 1, IPTOT
LPPAR(IP) = .FALSE.
ENDDO
LPPAR(IPALFA) = .TRUE.
LPPAR(IPBETA) = .TRUE.
c LPPAR(IPROTX) = .TRUE.
c LPPAR(IPROTY) = .TRUE.
c LPPAR(IPROTZ) = .TRUE.
LPPAR(IPCL ) = .TRUE.
LPPAR(IPCD0 ) = .TRUE.
LPPAR(IPPHI ) = .TRUE.
c LPPAR(IPTHE ) = .TRUE.
c LPPAR(IPPSI ) = .TRUE.
c LPPAR(IPMACH) = .TRUE.
LPPAR(IPVEE ) = .TRUE.
LPPAR(IPRHO ) = .TRUE.
c LPPAR(IPGEE ) = .TRUE.
LPPAR(IPRAD ) = .TRUE.
c LPPAR(IPFAC ) = .TRUE.
LPPAR(IPXCG ) = .TRUE.
c LPPAR(IPYCG ) = .TRUE.
LPPAR(IPZCG ) = .TRUE.
LPPAR(IPMASS) = .TRUE.
c LPPAR(IPIXX ) = .TRUE.
c LPPAR(IPIYY ) = .TRUE.
c LPPAR(IPIZZ ) = .TRUE.
c LPPAR(IPIXY ) = .TRUE.
c LPPAR(IPIYZ ) = .TRUE.
c LPPAR(IPIZX ) = .TRUE.
c LPPAR(IPCLA ) = .TRUE.
c LPPAR(IPCLU ) = .TRUE.
c LPPAR(IPCMA ) = .TRUE.
c LPPAR(IPCMU ) = .TRUE.
RETURN
END ! PLPARS
SUBROUTINE DEFINI
INCLUDE 'AVL.INC'
C
C---- flag for forces in standard NASA stability axes (as in Etkin)
LNASA_SA = .TRUE.
C
C---- flag for rotations defined in stability axes or body axes
LSA_RATES = .TRUE.
C
LPTOT = .TRUE.
LPSURF = .FALSE.
LPSTRP = .FALSE.
LPELE = .FALSE.
LPHINGE = .FALSE.
LPDERIV = .FALSE.
C
LGEO = .FALSE.
LENC = .FALSE.
C
LAIC = .FALSE.
LSRD = .FALSE.
LVEL = .FALSE.
LSOL = .FALSE.
LSEN = .FALSE.
C
LVISC = .TRUE.
LBFORCE = .TRUE.
LTRFORCE = .TRUE.
C
LMWAIT = .FALSE.
C
MATSYM = 0
NITMAX = 20
C
SAXFR = 0.25 ! x/c location of spanwise axis for Vperp definition
C
VRCORE = 0.25 ! vortex core radius / vortex span
SRCORE = 0.75 ! source core radius / body radius
C
C---- dafault basic units
UNITL = 1.
UNITM = 1.
UNITT = 1.
UNCHL = 'Lunit'
UNCHM = 'Munit'
UNCHT = 'Tunit'
NUL = 5
NUM = 5
NUT = 5
C
C---- set corresponding derived units
CALL UNITSET
C
C---- default air density and grav. accel.
RHO0 = 1.0
GEE0 = 1.0
C
C---- no eigenvalue reference data yet
FEVDEF = ' '
DO IR = 1, NRMAX
NEIGENDAT(IR) = 0
ENDDO
C
C---- no run cases defined yet
NRUN = 0
IRUN = 1
C
C---- number of valid time levels stored
NTLEV = 0
C
C---- default time step, and number of time steps to take
DELTAT = 0.0
NTSTEPS = 0
C
RETURN
END ! DEFINI
SUBROUTINE PARSET
INCLUDE 'AVL.INC'
C
C---- variable names
VARNAM(IVALFA) = 'alpha '
VARNAM(IVBETA) = 'beta '
VARNAM(IVROTX) = 'pb/2V '
VARNAM(IVROTY) = 'qc/2V '
VARNAM(IVROTZ) = 'rb/2V '
C
C---- variable selection keys
VARKEY(IVALFA) = 'A lpha'
VARKEY(IVBETA) = 'B eta'
VARKEY(IVROTX) = 'R oll rate'
VARKEY(IVROTY) = 'P itch rate'
VARKEY(IVROTZ) = 'Y aw rate'
C
C---- constraint names
CCC 123456789012
CONNAM(ICALFA) = 'alpha '
CONNAM(ICBETA) = 'beta '
CONNAM(ICROTX) = 'pb/2V '
CONNAM(ICROTY) = 'qc/2V '
CONNAM(ICROTZ) = 'rb/2V '
CONNAM(ICCL ) = 'CL '
CONNAM(ICCY ) = 'CY '
CONNAM(ICMOMX) = 'Cl roll mom'
CONNAM(ICMOMY) = 'Cm pitchmom'
CONNAM(ICMOMZ) = 'Cn yaw mom'
C
C---- constraint selection keys
CONKEY(ICALFA) = 'A '
CONKEY(ICBETA) = 'B '
CONKEY(ICROTX) = 'R '
CONKEY(ICROTY) = 'P '
CONKEY(ICROTZ) = 'Y '
CONKEY(ICCL ) = 'C '
CONKEY(ICCY ) = 'S '
CONKEY(ICMOMX) = 'RM'
CONKEY(ICMOMY) = 'PM'
CONKEY(ICMOMZ) = 'YM'
C
C------------------------------------------------------------------------
IZERO = ICHAR('0')
C
C---- add control variables, direct constraints
DO N = 1, NCONTROL
ITEN = N/10
IONE = N - 10*ITEN
C
C------ assign slots in variable ond constraint lists
IV = IVTOT + N
IC = ICTOT + N
VARNAM(IV) = DNAME(N)
CONNAM(IC) = DNAME(N)
IF(ITEN.EQ.0) THEN
VARKEY(IV) = 'D' // CHAR(IZERO+IONE) // ' '
& // ' ' // DNAME(N)(1:8)
CONKEY(IC) = 'D' // CHAR(IZERO+IONE)
ELSE
VARKEY(IV) = 'D' // CHAR(IZERO+ITEN) // CHAR(IZERO+IONE)
& // ' ' // DNAME(N)(1:8)
CONKEY(IC) = 'D' // CHAR(IZERO+ITEN) // CHAR(IZERO+IONE)
ENDIF
C
LCONDEF(N) = .TRUE.
ENDDO
C
C---- default design-variable flags, names
DO N = 1, NDESIGN
LDESDEF(N) = .TRUE.
ENDDO
C
C---- total number of variables, constraints
NVTOT = IVTOT + NCONTROL
NCTOT = ICTOT + NCONTROL
C
C---- run-case parameter names
PARNAM(IPALFA) = 'alpha '
PARNAM(IPBETA) = 'beta '
PARNAM(IPROTX) = 'pb/2V '
PARNAM(IPROTY) = 'qc/2V '
PARNAM(IPROTZ) = 'rb/2V '
PARNAM(IPCL ) = 'CL '
PARNAM(IPCD0) = 'CDo '
PARNAM(IPPHI) = 'bank '
PARNAM(IPTHE) = 'elevation'
PARNAM(IPPSI) = 'heading '
PARNAM(IPMACH) = 'Mach '
PARNAM(IPVEE) = 'velocity '
PARNAM(IPRHO) = 'density '
PARNAM(IPGEE) = 'grav.acc.'
PARNAM(IPRAD) = 'turn_rad.'
PARNAM(IPFAC) = 'load_fac.'
PARNAM(IPXCG) = 'X_cg '
PARNAM(IPYCG) = 'Y_cg '
PARNAM(IPZCG) = 'Z_cg '
PARNAM(IPMASS) = 'mass '
PARNAM(IPIXX) = 'Ixx '
PARNAM(IPIYY) = 'Iyy '
PARNAM(IPIZZ) = 'Izz '
PARNAM(IPIXY) = 'Ixy '
PARNAM(IPIYZ) = 'Iyz '
PARNAM(IPIZX) = 'Izx '
PARNAM(IPCLA) = 'visc CL_a'
PARNAM(IPCLU) = 'visc CL_u'
PARNAM(IPCMA) = 'visc CM_a'
PARNAM(IPCMU) = 'visc CM_u'
C
C---- total number of parameters
NPTOT = IPTOT
C
C---- set default parameter unit names
CALL PARNSET
C
RETURN
END ! PARSET
SUBROUTINE PARNSET
INCLUDE 'AVL.INC'
C
C---- set parameter unit name
DO IP = 1, IPTOT
PARUNCH(IP) = ' '
ENDDO
C
PARUNCH(IPALFA) = 'deg'
PARUNCH(IPBETA) = 'deg'
PARUNCH(IPPHI) = 'deg'
PARUNCH(IPTHE) = 'deg'
PARUNCH(IPPSI) = 'deg'
PARUNCH(IPVEE) = UNCHV
PARUNCH(IPRHO) = UNCHD
PARUNCH(IPGEE) = UNCHA
PARUNCH(IPRAD) = UNCHL
C---- bug 21 Feb 13 MD
c PARUNCH(IPXCG) = UNCHL
c PARUNCH(IPYCG) = UNCHL
c PARUNCH(IPZCG) = UNCHL
PARUNCH(IPXCG) = 'Lunit'
PARUNCH(IPYCG) = 'Lunit'
PARUNCH(IPZCG) = 'Lunit'
PARUNCH(IPMASS) = UNCHM
PARUNCH(IPIXX) = UNCHI
PARUNCH(IPIYY) = UNCHI
PARUNCH(IPIZZ) = UNCHI
PARUNCH(IPIXY) = UNCHI
PARUNCH(IPIYZ) = UNCHI
PARUNCH(IPIZX) = UNCHI
C
RETURN
END ! PARNSET
SUBROUTINE VARINI
INCLUDE 'AVL.INC'
C
C---- initialize state
ALFA = 0.
BETA = 0.
WROT(1) = 0.
WROT(2) = 0.
WROT(3) = 0.
C
DO N = 1, NCONTROL
DELCON(N) = 0.0
ENDDO
C
DO N = 1, NDESIGN
DELDES(N) = 0.0
ENDDO
LSOL = .FALSE.
C
RETURN
END ! VARINI
SUBROUTINE RUNINI
INCLUDE 'AVL.INC'
C
WRITE(*,*)
WRITE(*,*) 'Initializing run cases...'
C
C---- go over all run cases
DO IR = 1, NRMAX
C------ index of default constraint for each variable
ICON(IVALFA,IR) = ICALFA
ICON(IVBETA,IR) = ICBETA
ICON(IVROTX,IR) = ICROTX
ICON(IVROTY,IR) = ICROTY
ICON(IVROTZ,IR) = ICROTZ
C
C------ default constraint values
DO IC = 1, ICTOT
CONVAL(IC,IR) = 0.
ENDDO
C
C------ default run case titles
RTITLE(IR) = ' -unnamed- '
C
C------ default dimensional run case parameters
DO IP = 1, NPTOT
PARVAL(IP,IR) = 0.
ENDDO
PARVAL(IPGEE,IR) = GEE0
PARVAL(IPRHO,IR) = RHO0
C
C------ default CG location is the input reference location
PARVAL(IPXCG,IR) = XYZREF0(1)
PARVAL(IPYCG,IR) = XYZREF0(2)
PARVAL(IPZCG,IR) = XYZREF0(3)
C
PARVAL(IPMASS,IR) = RMASS0
PARVAL(IPIXX,IR) = RINER0(1,1)
PARVAL(IPIYY,IR) = RINER0(2,2)
PARVAL(IPIZZ,IR) = RINER0(3,3)
PARVAL(IPIXY,IR) = RINER0(1,2)
PARVAL(IPIYZ,IR) = RINER0(2,3)
PARVAL(IPIZX,IR) = RINER0(3,1)
C
PARVAL(IPCD0,IR) = CDREF0
C
PARVAL(IPCLA,IR) = DCL_A0
PARVAL(IPCLU,IR) = DCL_U0
PARVAL(IPCMA,IR) = DCM_A0
PARVAL(IPCMU,IR) = DCM_U0
C
ITRIM(IR) = 0
NEIGEN(IR) = 0
ENDDO
C
C---- add control variables, direct constraints
DO N = 1, NDMAX
IV = IVTOT + N
IC = ICTOT + N
DO IR = 1, NRMAX
ICON(IV,IR) = IC
CONVAL(IC,IR) = 0.
ENDDO
ENDDO
C
C---- default number of run cases
IRUN = 1
NRUN = 1
C
C---- all run cases are targets for eigenmode calculation
IRUNE = 0
C
C---- first run case is default for time march initial state
IRUNT = 1
C
RETURN
END ! RUNINI
SUBROUTINE RUNGET(LU,FNAME,ERROR)
C-------------------------------------------------
C Reads run case file into run case arrays
C-------------------------------------------------
INCLUDE 'AVL.INC'
CHARACTER*(*) FNAME
LOGICAL ERROR
C
CHARACTER*80 LINE, REST
CHARACTER*12 VARN, CONN
CHARACTER*8 PARN
C
OPEN(LU,FILE=FNAME,STATUS='OLD',ERR=90)
ILINE = 0
C
IR = 0
C
C==============================================================
C---- start line-reading loop
10 CONTINUE
C
READ(LU,1000,END=50) LINE
1000 FORMAT(A)
ILINE = ILINE + 1
C
KCOL = INDEX(LINE,':' )
KARR = INDEX(LINE,'->')
KEQU = INDEX(LINE,'=' )
IF(KCOL.NE.0) THEN
C----- start of new run case
READ(LINE(KCOL-3:KCOL-1),*,ERR=80) IR
C
IF(IR.LT.1 .OR. IR.GT.NRMAX) THEN
WRITE(*,*) 'RUNGET: Run case array limit NRMAX exceeded:', IR
IR = 0
GO TO 10
ENDIF
C
NRUN = MAX(NRUN,IR)
C
RTITLE(IR) = LINE(KCOL+1:80)
CALL STRIP(RTITLE(IR),NRT)
C
ELSEIF(IR.EQ.0) THEN
C----- keep ignoring lines if valid run case index is not set
GO TO 10
C
ELSEIF(KARR.NE.0 .AND. KEQU.NE.0) THEN
C----- variable/constraint declaration line
VARN = LINE(1:KARR-1)
CONN = LINE(KARR+2:KEQU-1)
CALL STRIP(VARN,NVARN)
CALL STRIP(CONN,NCONN)
C
DO IV = 1, NVTOT
IF(INDEX(VARNAM(IV),VARN(1:NVARN)).NE.0) GO TO 20
ENDDO
WRITE(*,*) 'Ignoring unrecognized variable: ', VARN(1:NVARN)
GO TO 10
C
20 CONTINUE
DO IC = 1, NCTOT
IF(INDEX(CONNAM(IC),CONN(1:NCONN)).NE.0) GO TO 25
ENDDO
WRITE(*,*) 'Ignoring unrecognized constraint: ', CONN(1:NCONN)
GO TO 10
C
25 CONTINUE
READ(LINE(KEQU+1:80),*,ERR=80) CONV
C
ICON(IV,IR) = IC
CONVAL(IC,IR) = CONV
C
ELSEIF(KARR.EQ.0 .AND. KEQU.NE.0) THEN
C----- run case parameter data line
PARN = LINE(1:KEQU-1)
CALL STRIP(PARN,NPARN)
DO IP = 1, NPTOT
IF(INDEX(PARNAM(IP),PARN(1:NPARN)).NE.0) GO TO 30
ENDDO
WRITE(*,*) 'Ignoring unrecognized parameter: ', PARN(1:NPARN)
GO TO 10
C
30 CONTINUE
REST = LINE(KEQU+1:80)
READ(REST,*,ERR=80) PARV
PARVAL(IP,IR) = PARV
if(.false.) then
CALL STRIP(REST,NREST)
KBLK = INDEX(REST,' ')
IF(KBLK .NE. 0) THEN
REST = REST(KBLK+1:80)
CALL STRIP(REST,NREST)
IF(NREST.GT.0) THEN
PARUNCH(IP) = REST
ENDIF
ENDIF
endif
ENDIF
C
C---- keep reading lines
GO TO 10
C
C==============================================================
C
50 CONTINUE
CLOSE(LU)
ERROR = .FALSE.
RETURN
C
80 CONTINUE
CALL STRIP(FNAME,NFN)
CALL STRIP(LINE ,NLI)
WRITE(*,8000) FNAME(1:NFN), ILINE, LINE(1:NLI)
8000 FORMAT(/' Run case file ',A,' read error on line', I4,':',A)
CLOSE(LU)
ERROR = .TRUE.
NRUN = 0
RETURN
C
90 CONTINUE
CALL STRIP(FNAME,NFN)
WRITE(*,9000) FNAME(1:NFN)
9000 FORMAT(/' Run case file ',A,' open error')
ERROR = .TRUE.
RETURN
END ! RUNGET
SUBROUTINE RUNSAV(LU)
INCLUDE 'AVL.INC'
C
DO IR = 1, NRUN
WRITE(LU,1010) IR, RTITLE(IR)
DO IV = 1, NVTOT
IC = ICON(IV,IR)
WRITE(LU,1050) VARNAM(IV), CONNAM(IC), CONVAL(IC,IR)
ENDDO
C
WRITE(LU,*)
C
DO IP = 1, NPTOT
WRITE(LU,1080) PARNAM(IP), PARVAL(IP,IR), PARUNCH(IP)
ENDDO
ENDDO
C
1010 FORMAT(/' ---------------------------------------------'
& /' Run case', I3,': ', A /)
1050 FORMAT(1X,A,' -> ', A, '=', G14.6, 1X, A)
1080 FORMAT(1X,A,'=', G14.6, 1X, A)
C
RETURN
END ! RUNSAV
LOGICAL FUNCTION LOWRIT(FNAME)
CHARACTER*(*) FNAME
C
CHARACTER*1 ANS
1000 FORMAT(A)
C
K = INDEX(FNAME,' ')
C
WRITE(*,*) 'File ', FNAME(1:K), ' exists. Overwrite? Y'
READ (*,1000) ANS
LOWRIT = INDEX('Nn',ANS) .EQ. 0
C
RETURN
END
SUBROUTINE AOCFIL(FNAME,IFILE)
CHARACTER*(*) FNAME
C
CHARACTER*1 ANS
1000 FORMAT(A)
C
K = INDEX(FNAME,' ')
C
WRITE(*,*) 'File ', FNAME(1:K),
& ' exists. Append, Overwrite, or Cancel? A'
READ (*,1000) ANS
IFILE = INDEX('AOC',ANS) + INDEX('aoc',ANS)
C
IF(IFILE.EQ.0) IFILE = 1
C
RETURN
END
|
homebrew_cask "iterm2"
cookbook_file "/Users/malston/Library/Preferences/com.googlecode.iterm2.plist" do
source "com.googlecode.iterm2.plist"
user node['current_user']
mode "0600"
end
|
;; Copyright (c) Tomek Lipski. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file LICENSE.txt at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns ganelon.tutorial.pages.routes
(:require [ganelon.web.dyna-routes :as dyna-routes]
[ganelon.tutorial.pages.common :as common]
[noir.cookies :as cookies]
[ganelon.tutorial.widgets.invitation-details :as invitation-details]
[ganelon.tutorial.widgets.meetup-add :as meetup-add]
[ganelon.tutorial.widgets.meetup-edit :as meetup-edit]
[ganelon.tutorial.widgets.meetups-list :as meetups-list]
[ganelon.tutorial.middleware :as middleware]))
(defn meetup-layout [& contents]
(common/layout
[:div.row-fluid [:div.span3 (meetup-add/new-meetup-widget)
(meetups-list/meetups-list-widget nil)]
[:div.span1 ]
[:div.span8 [:div#contents contents]]]))
(dyna-routes/defpage "/" []
(meetup-layout
[:div.hero-unit [:h1 "Welcome"]
[:p "Welcome to the interactive tutorial for " [:a {:href "http://ganelon.tomeklipski.com"} "Ganelon micro-framework."]]
[:p "This sample application used to manage meetups provides links to display source of every widget and action used.
In addition to that, each widget has a dashed border to mark its boundary."]]))
(dyna-routes/defpage "/meetup/edit/:id" [id]
(middleware/with-admin-id-from-meetup! id
(meetup-layout
(meetup-edit/meetup-details-widget id))))
(dyna-routes/defpage "/i/:id" [id]
(meetup-layout
(invitation-details/invitation-details-widget id))) |
# Northstar Speedometer
R2Northstar mod that restores speedometer in multiplayer
It was available before through VPK editing but now it's simpler to install
Uses MPH as default. To use kM/h add `+speedometer_use_metric_units 1` to startup args (ns_startup_args.txt)
|
package launchers
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/cybriq/p9/pkg/interrupt"
"github.com/cybriq/p9/pkg/qu"
"github.com/cybriq/p9/cmd/ctl"
"github.com/cybriq/p9/cmd/node"
"github.com/cybriq/p9/cmd/wallet"
"github.com/cybriq/p9/pkg/constant"
"github.com/cybriq/p9/pod/state"
"github.com/cybriq/p9/pkg/apputil"
)
// NodeHandle runs the ParallelCoin blockchain node
func NodeHandle(ifc interface{}) (e error) {
var cx *state.State
var ok bool
if cx, ok = ifc.(*state.State); !ok {
return fmt.Errorf("cannot run without a state")
}
I.Ln("running node handler")
cx.NodeReady = qu.T()
cx.Node.Store(false)
// // serviceOptions defines the configuration options for the daemon as a service on Windows.
// type serviceOptions struct {
// ServiceCommand string `short:"s" long:"service" description:"Service command {install, remove, start, stop}"`
// }
// // runServiceCommand is only set to a real function on Windows. It is used to parse and execute service commands
// // specified via the -s flag.
// runServiceCommand := func(string) (e error) { return nil }
// // Service options which are only added on Windows.
// serviceOpts := serviceOptions{}
// // Perform service command and exit if specified. Invalid service commands show an appropriate error. Only runs
// // on Windows since the runServiceCommand function will be nil when not on Windows.
// if serviceOpts.ServiceCommand != "" && runServiceCommand != nil {
// if e = runServiceCommand(serviceOpts.ServiceCommand); E.Chk(e) {
// return e
// }
// return nil
// }
go func() {
if e := node.NodeMain(cx); E.Chk(e) {
E.Ln("error starting node ", e)
}
}()
I.Ln("starting node")
if cx.Config.DisableRPC.False() {
cx.RPCServer = <-cx.NodeChan
cx.NodeReady.Q()
cx.Node.Store(true)
I.Ln("node started")
}
// }
cx.WaitWait()
I.Ln("node is now fully shut down")
cx.WaitGroup.Wait()
<-cx.KillAll
return nil
}
// WalletHandle runs the wallet server
func WalletHandle(ifc interface{}) (e error) {
var cx *state.State
var ok bool
if cx, ok = ifc.(*state.State); !ok {
return fmt.Errorf("cannot run without a state")
}
cx.Config.WalletFile.Set(filepath.Join(cx.Config.DataDir.V(),
cx.ActiveNet.Name, constant.DbName,
),
)
// dbFilename := *cx.Config.DataDir + slash + cx.ActiveNet.
// Params.Name + slash + wallet.WalletDbName
if !apputil.FileExists(cx.Config.WalletFile.V()) && !cx.IsGUI {
// D.Ln(cx.ActiveNet.Name, *cx.Config.WalletFile)
if e = wallet.CreateWallet(cx.ActiveNet, cx.Config); E.Chk(e) {
E.Ln("failed to create wallet", e) /**/
return e
}
fmt.Println("restart to complete initial setup")
// os.Exit(0)
interrupt.RequestRestart()
}
// for security with apps launching the wallet, the public password can be set with a file that is deleted after
walletPassPath := filepath.Join(cx.Config.DataDir.V(), cx.ActiveNet.Name,
"wp.txt",
)
D.Ln("reading password from", walletPassPath)
if apputil.FileExists(walletPassPath) {
var b []byte
if b, e = ioutil.ReadFile(walletPassPath); !E.Chk(e) {
cx.Config.WalletPass.SetBytes(b)
D.Ln("read password '"+string(b)+"'", cx.Config.WalletPass.V())
if e = ioutil.WriteFile(walletPassPath, make([]byte, len(b)),
0700,
); E.Chk(e) {
}
if e = os.Remove(walletPassPath); E.Chk(e) {
}
D.Ln("wallet cookie deleted", cx.Config.WalletPass.V())
}
}
cx.WalletKill = qu.T()
if e = wallet.Main(cx); E.Chk(e) {
E.Ln("failed to start up wallet", e)
}
// if !*cx.Config.DisableRPC {
// cx.WalletServer = <-cx.WalletChan
// }
// cx.WaitGroup.Wait()
cx.WaitWait()
return
}
func CtlHandleList(ifc interface{}) (e error) {
fmt.Println(ctl.ListCommands())
return nil
}
func CtlHandle(ifc interface{}) (e error) {
var cx *state.State
var ok bool
if cx, ok = ifc.(*state.State); !ok {
return fmt.Errorf("cannot run without a state")
}
cx.Config.LogLevel.Set("off")
ctl.CtlMain(cx.Config)
return nil
}
|
alias youtubedl='docker run --rm -u $(id -u):$(id -g) -v $PWD:/data vimagick/youtube-dl'
|
module Exec (
Command, VarTable, CommandTable, ScriptState(..),
runHashProgram, runTopLevel, getPath, emptyScriptState
) where
import qualified Data.Map as M
import Control.Applicative ((<$>))
import Control.Monad (when, (>>=))
import System.FilePath.Posix (isRelative, (</>))
import System.IO
import qualified Proba as P
import Expressions
-- A model of a command which is waiting for arguments and a state to run
type Command = [String] -> ScriptState -> IO ScriptState
-- A table of variables, in fact a map of (Name, Value) pairs.
type VarTable = M.Map String String
-- A command table - abstracted command execution, (contains command name,
-- command) pairs. Simplest, but hardly the best way to implement this.
type CommandTable = M.Map String Command
-- A script state containing the last output, current working directory and
-- the current table of variables.
data ScriptState = ScriptState { output :: String
, wd :: FilePath
, vartable :: VarTable
} deriving Show
emptyScriptState :: ScriptState
emptyScriptState = ScriptState "" "" M.empty
-- Runs a set of commands for a given command table. If this is the first
-- command in the chain, it is given a FilePath and constructs a new, initially
-- blank, ScriptState. Otherwise, it is given the state as left by the previous
-- command's execution.
runHashProgram :: CommandTable -> ScriptState -> [TLExpr] -> IO ScriptState
runHashProgram _ ss [] = return ss
runHashProgram ct ss (t:ts) = mScript >>= rHP
where rHP scs = runHashProgram ct scs ts -- run the rest of the expressions
mScript = runTopLevel ct ss t -- run one expression
-- Calculates the result of a top-level command execution
runTopLevel :: CommandTable -> ScriptState -> TLExpr -> IO ScriptState
runTopLevel ct ss t = case t of
TLCmd (Cmd n as i o a) -> case (M.lookup name ct) of
Nothing -> fail $ "Undefined command " ++ name
Just cmd -> resolveCmd cmd
where name = eval n
resolveCmd :: Command -> IO ScriptState
resolveCmd cmd = args >>= cmd' >>= resolveScript
where cmd' = flip cmd ss
args = case i of
Nothing -> return $ map eval as
Just f -> getInputFrom $ eval f
resolveScript :: ScriptState -> IO ScriptState
resolveScript ss = do
let out = output ss
case o of
Nothing -> if null out then return () else putStrLn out
Just f -> toOutputFile a (eval f) out
return ss { output = "" }
TLCmt _ -> return ss
TLCnd (If c cts) -> if (evalPred vt c)
then rHP cts
else return ss
TLCnd (IfElse c cts ces) -> if (evalPred vt c)
then rHP cts
else rHP ces
TLCas (Assign var val) -> rTL $ TLCmd
(Cmd (Expr "assign") [var, val] Nothing Nothing False)
w@(TLClp (While c b)) -> if (evalPred vt c)
then rHP b >>= fRTL w
else return ss
d@(TLClp (DoWhile c b)) -> do
s <- rHP b
if (evalPred (vartable s) c)
then rTL' s d
else return s
(TLClp f@(For initial _ _ _)) -> rTL (TLCas initial) >>= runFor f
where vt = vartable ss
eval = evalExpr vt
rHP' s = runHashProgram ct s . map TLCmd
rHP = rHP' ss
rTL' = runTopLevel ct
rTL = rTL' ss
fRTL = flip rTL'
runFor f@(For _ c s b) script = do
if (evalPred (vartable script) c)
then rHP' script b >>= fRTL (TLCas s) >>= runFor f
else return script
getInputFrom :: FilePath -> IO [String]
getInputFrom path = lines <$> readFile path
toOutputFile :: Bool -> (FilePath -> String -> IO ())
toOutputFile append = if append then appendFile else writeFile
-- LOWER LEVEL FUNCTIONS ==========================================================
-- evaluates the given expression
-- for a string returns it, for a variable returns it's value
oldEvalExpr :: VarTable -> Expr -> String
oldEvalExpr vt (Expr s) = (unwords . map find . words) s
where find ('$':xs) = case (M.lookup xs vt) of
Nothing -> '$':xs
Just v -> v
find xs = xs
evalExpr :: VarTable -> Expr -> String
evalExpr vt e = case (evalExpr' vt e) of
Just s -> s
Nothing -> oldEvalExpr vt e
evalExpr' :: VarTable -> Expr -> Maybe String
evalExpr' vt (Expr s) = P.parseE s >>= P.eval vt
evalComp :: VarTable -> Comp -> Bool
evalComp vt c = case c of
CEQ e1 e2 -> f (==) e1 e2
CNE e1 e2 -> f (/=) e1 e2
CGE e1 e2 -> f (>=) e1 e2
CGT e1 e2 -> f (>) e1 e2
CLE e1 e2 -> f (<=) e1 e2
CLT e1 e2 -> f (<) e1 e2
CLI e -> not . null $ ev e
where f c e1 e2 = c (ev e1) (ev e2)
ev e = evalExpr vt e
evalPred :: VarTable -> Pred -> Bool
evalPred vt p = case p of
Pred c -> evalComp vt c
Not p -> not $ evalPred vt p
And p1 p2 -> evalPred vt p1 && evalPred vt p2
Or p1 p2 -> evalPred vt p1 || evalPred vt p2
-- for given wd in scriptstate makes absolute path from given path
getPath :: ScriptState -> FilePath -> FilePath
getPath sc path
| isRelative path = wd sc </> path
| otherwise = path |
'use strict';
let env = String(process.env.NODE_ENV);
if (env !== 'production' && env !== 'testing') env = 'development';
const nodeEnv = module.exports = () => env;
nodeEnv.switch = (envArg) => {
envArg = String(envArg);
if (envArg === 'development' || envArg === 'testing' || envArg === 'production') {
env = envArg;
}
};
nodeEnv.isDevelop = () => env === 'development';
nodeEnv.isProduct = () => env === 'production';
nodeEnv.isTesting = () => env === 'testing';
|
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use crate::magic::transl8::impl_magic;
use crate::magic::transl8::FromV8;
use crate::magic::transl8::ToV8;
use std::mem::transmute;
/// serde_v8::Value allows passing through `v8::Value`s untouched
/// when de/serializing & allows mixing rust & v8 values in structs, tuples...
//
// SAFETY: caveat emptor, the rust-compiler can no longer link lifetimes to their
// original scope, you must take special care in ensuring your handles don't outlive their scope
pub struct Value<'s> {
pub v8_value: v8::Local<'s, v8::Value>,
}
impl_magic!(Value<'_>);
impl<'s> From<v8::Local<'s, v8::Value>> for Value<'s> {
fn from(v8_value: v8::Local<'s, v8::Value>) -> Self {
Self { v8_value }
}
}
impl<'s> From<Value<'s>> for v8::Local<'s, v8::Value> {
fn from(v: Value<'s>) -> Self {
v.v8_value
}
}
impl ToV8 for Value<'_> {
fn to_v8<'a>(
&self,
_scope: &mut v8::HandleScope<'a>,
) -> Result<v8::Local<'a, v8::Value>, crate::Error> {
// SAFETY: not fully safe, since lifetimes are detached from original scope
Ok(unsafe { transmute(self.v8_value) })
}
}
impl FromV8 for Value<'_> {
fn from_v8(
_scope: &mut v8::HandleScope,
value: v8::Local<v8::Value>,
) -> Result<Self, crate::Error> {
// SAFETY: not fully safe, since lifetimes are detached from original scope
Ok(unsafe { transmute::<Value, Value>(value.into()) })
}
}
|
import { ComposableStyles, ElementStyles } from "../styles/element-styles";
import type { ElementViewTemplate } from "../templating/template";
import { AttributeConfiguration, AttributeDefinition } from "./attributes";
/**
* Represents metadata configuration for a custom element.
* @public
*/
export interface PartialFASTElementDefinition {
/**
* The name of the custom element.
*/
readonly name: string;
/**
* The template to render for the custom element.
*/
readonly template?: ElementViewTemplate;
/**
* The styles to associate with the custom element.
*/
readonly styles?: ComposableStyles | ComposableStyles[];
/**
* The custom attributes of the custom element.
*/
readonly attributes?: (AttributeConfiguration | string)[];
/**
* Options controlling the creation of the custom element's shadow DOM.
*/
readonly shadowOptions?: Partial<ShadowRootInit> | null;
/**
* Options controlling how the custom element is defined with the platform.
*/
readonly elementOptions?: ElementDefinitionOptions;
}
/**
* Defines metadata for a FASTElement.
* @public
*/
export declare class FASTElementDefinition<TType extends Function = Function> {
private observedAttributes;
/**
* The type this element definition describes.
*/
readonly type: TType;
/**
* Indicates if this element has been defined in at least one registry.
*/
get isDefined(): boolean;
/**
* The name of the custom element.
*/
readonly name: string;
/**
* The custom attributes of the custom element.
*/
readonly attributes: ReadonlyArray<AttributeDefinition>;
/**
* A map enabling lookup of attribute by associated property name.
*/
readonly propertyLookup: Record<string, AttributeDefinition>;
/**
* A map enabling lookup of property by associated attribute name.
*/
readonly attributeLookup: Record<string, AttributeDefinition>;
/**
* The template to render for the custom element.
*/
readonly template?: ElementViewTemplate;
/**
* The styles to associate with the custom element.
*/
readonly styles?: ElementStyles;
/**
* Options controlling the creation of the custom element's shadow DOM.
*/
readonly shadowOptions?: ShadowRootInit;
/**
* Options controlling how the custom element is defined with the platform.
*/
readonly elementOptions?: ElementDefinitionOptions;
/**
* Creates an instance of FASTElementDefinition.
* @param type - The type this definition is being created for.
* @param nameOrConfig - The name of the element to define or a config object
* that describes the element to define.
*/
constructor(type: TType, nameOrConfig?: PartialFASTElementDefinition | string);
/**
* Defines a custom element based on this definition.
* @param registry - The element registry to define the element in.
*/
define(registry?: CustomElementRegistry): this;
/**
* Gets the element definition associated with the specified type.
* @param type - The custom element type to retrieve the definition for.
*/
static readonly forType: <TType_1 extends Function>(key: TType_1) => FASTElementDefinition<Function> | undefined;
}
|
/****************************************************************************
* Copyright 2021 EPAM Systems
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
import { Atom, Bond, SGroup, Struct } from 'domain/entities'
import { Elements } from 'domain/constants'
import { ifDef } from 'utilities'
export function toRlabel(values) {
let res = 0
values.forEach((val) => {
const rgi = val - 1
res |= 1 << rgi
})
return res
}
export function moleculeToStruct(ketItem: any): Struct {
const struct = new Struct()
ketItem.atoms.forEach((atom) => {
if (atom.type === 'rg-label') struct.atoms.add(rglabelToStruct(atom))
if (atom.type === 'atom-list') struct.atoms.add(atomListToStruct(atom))
if (!atom.type) struct.atoms.add(atomToStruct(atom))
})
if (ketItem.bonds) {
ketItem.bonds.forEach((bond) => struct.bonds.add(bondToStruct(bond)))
}
if (ketItem.sgroups) {
ketItem.sgroups.forEach((sgroup) =>
struct.sgroups.add(sgroupToStruct(sgroup))
)
}
struct.initHalfBonds()
struct.initNeighbors()
struct.markFragments()
struct.bindSGroupsToFunctionalGroups()
return struct
}
export function atomToStruct(source) {
const params: any = {}
ifDef(params, 'label', source.label)
ifDef(params, 'alias', source.alias)
ifDef(params, 'pp', {
x: source.location[0],
y: -source.location[1],
z: source.location[2] || 0.0
})
ifDef(params, 'charge', source.charge)
ifDef(params, 'explicitValence', source.explicitValence)
ifDef(params, 'isotope', source.isotope)
ifDef(params, 'radical', source.radical)
ifDef(params, 'attpnt', source.attachmentPoints)
// stereo
ifDef(params, 'stereoLabel', source.stereoLabel)
ifDef(params, 'stereoParity', source.stereoParity)
ifDef(params, 'weight', source.weight)
// query
ifDef(params, 'ringBondCount', source.ringBondCount)
ifDef(params, 'substitutionCount', source.substitutionCount)
ifDef(params, 'unsaturatedAtom', source.unsaturatedAtom)
ifDef(params, 'hCount', source.hCount)
// reaction
ifDef(params, 'aam', source.mapping)
ifDef(params, 'invRet', source.invRet)
ifDef(params, 'exactChangeFlag', !!source.exactChangeFlag)
return new Atom(params)
}
export function rglabelToStruct(source) {
const params: any = {}
params.label = 'R#'
ifDef(params, 'pp', {
x: source.location[0],
y: source.location[1],
z: source.location[2] || 0.0
})
ifDef(params, 'attpnt', source.attachmentPoints)
const rglabel = toRlabel(source.$refs.map((el) => parseInt(el.slice(3))))
ifDef(params, 'rglabel', rglabel)
return new Atom(params)
}
export function atomListToStruct(source) {
const params: any = {}
params.label = 'L#'
ifDef(params, 'pp', {
x: source.location[0],
y: source.location[1],
z: source.location[2] || 0.0
})
ifDef(params, 'attpnt', source.attachmentPoints)
const ids = source.elements
.map((el) => Elements.get(el)?.number)
.filter((id) => id)
ifDef(params, 'atomList', {
ids,
notList: source.notList
})
return new Atom(params)
}
export function bondToStruct(source) {
const params: any = {}
ifDef(params, 'type', source.type)
ifDef(params, 'topology', source.topology)
ifDef(params, 'reactingCenterStatus', source.center)
ifDef(params, 'stereo', source.stereo)
// if (params.stereo)
// params.stereo = params.stereo > 1 ? params.stereo * 2 : params.stereo;
// params.xxx = 0;
ifDef(params, 'begin', source.atoms[0])
ifDef(params, 'end', source.atoms[1])
return new Bond(params)
}
export function sgroupToStruct(source) {
const sgroup = new SGroup(source.type)
ifDef(sgroup, 'atoms', source.atoms)
switch (source.type) {
case 'GEN':
break
case 'MUL': {
ifDef(sgroup.data, 'mul', source.mul)
break
}
case 'SRU': {
ifDef(sgroup.data, 'subscript', source.subscript)
ifDef(sgroup.data, 'connectivity', source.connectivity.toLowerCase())
break
}
case 'SUP': {
ifDef(sgroup.data, 'name', source.name)
ifDef(sgroup.data, 'expanded', source.expanded)
ifDef(sgroup, 'id', source.id)
break
}
case 'DAT': {
ifDef(sgroup.data, 'absolute', source.placement)
ifDef(sgroup.data, 'attached', source.display)
ifDef(sgroup.data, 'context', source.context)
ifDef(sgroup.data, 'fieldName', source.fieldName)
ifDef(sgroup.data, 'fieldValue', source.fieldData)
break
}
default:
break
}
return sgroup
}
|
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Model;
use Faker\Generator as Faker;
$factory->define(\App\Models\Category::class, function (Faker $faker) {
$faker_ar = \Faker\Factory::create('ar_JO');
return [
'name_en' => $faker->name,//Str::random(10),
'name_ar' => $faker_ar->name,//Str::random(10),
'image' => null,
'type' => 2,
'delivery_fees' => 10,
'sort' => 0,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
];
});
|
'use strict';
import chalk from 'chalk';
import fs from 'fs';
exports.configFileExists = () => {
if (!fs.existsSync('./mevn.json')) {
console.log(
chalk.cyanBright(`\n\n Make sure that you're within a valid MEVN project
\n${chalk.redBright('Error:')} No mevn.json file found
`),
);
process.exit(1);
}
};
exports.templateIsGraphQL = () => {
let msg = `GraphQL boilerplate doesn't include ${chalk.yellowBright(
`model, route and controller`,
)} directories!`;
console.log(
chalk.redBright(
`\n Warning:- ${chalk.cyanBright(`${msg}
`)}`,
),
);
process.exit(1);
};
exports.dependencyNotInstalled = dependency => {
console.log(
chalk.redBright(`Warning:- ${chalk.cyanBright(
`${dependency} is required to be installed`,
)}
`),
);
process.exit(1);
};
|
/*
* Copyright 2012-2020 smartics, Kronseder & Reiner GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package de.smartics.maven.alias.report;
import de.smartics.maven.alias.domain.AliasCollector;
import de.smartics.maven.alias.domain.AliasGroup;
import de.smartics.maven.alias.domain.ExtensionGroup;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Collects alias information.
*/
public final class ReportAliasCollector
implements AliasCollector, Iterable<AliasGroup> {
// ********************************* Fields *********************************
// --- constants ------------------------------------------------------------
// --- members --------------------------------------------------------------
/**
* The list of aliases to add to the script.
*/
private final List<AliasGroup> aliasGroups = new ArrayList<AliasGroup>();
/**
* The collection of extension and their extended aliases.
*/
private final List<ExtensionGroup> extensionGroups =
new ArrayList<ExtensionGroup>();
// ****************************** Initializer *******************************
// ****************************** Constructors ******************************
/**
* Default constructor.
*/
public ReportAliasCollector() {}
// ****************************** Inner Classes *****************************
// ********************************* Methods ********************************
// --- init -----------------------------------------------------------------
// --- get&set --------------------------------------------------------------
@Override
public void setExtensionGroups(final List<ExtensionGroup> extensionGroups) {
this.extensionGroups.addAll(extensionGroups);
}
/**
* Returns the list of extension groups.
*
* @return the list of extension groups.
*/
public List<ExtensionGroup> getExtensionGroups() {
return extensionGroups;
}
// --- business -------------------------------------------------------------
@Override
public void addAliases(final AliasGroup group) {
if (!group.isEmpty()) {
this.aliasGroups.add(group);
}
}
/**
* Returns an iterator over the collected alias groups.
*
* @return an iterator over the collected alias groups.
*/
public Iterator<AliasGroup> iterator() {
return aliasGroups.iterator();
}
// --- object basics --------------------------------------------------------
}
|
<?php $_CONTROL->lblPromptLabel->Render() ?>
<br />
<?php $_CONTROL->lblBottom->Render() ?> |
export class CategorizedSkill {
category: string;
skills: string;
constructor(category?: string, skills?: string) {
this.category = category;
this.skills = skills;
}
}
|
package net.corda.examples.energyaccount.contracts
import net.corda.testing.node.transaction
import org.junit.Test
import java.time.LocalDate
class AccountContractModifyTests : AccountContractTestBase() {
@Test
fun `No input state provided`() {
ledgerServices.transaction() {
command(defaultSigners, AccountContract.Commands.Modify())
output(AccountContract.ID, defaultState)
`fails with` ("A single account must be consumed")
}
}
@Test
fun `Wrong number of output states provided`() {
ledgerServices.transaction() {
command(defaultSigners, AccountContract.Commands.Modify())
`fails with` ("A transaction must contain at least one input or output state")
input(AccountContract.ID, defaultState)
output(AccountContract.ID, defaultState)
output(AccountContract.ID,
defaultState.copy(
customerDetails = defaultState.customerDetails.copy(
firstName = "Alice",
lastName = "Anderson")))
`fails with` ("A single account must be created")
}
}
@Test
fun `The supplier has not signed the transaction`() {
ledgerServices.transaction() {
command(listOf(regulator.publicKey), AccountContract.Commands.Modify())
input(AccountContract.ID, defaultState)
output(AccountContract.ID, defaultState.copy(
customerDetails = defaultState.customerDetails.copy(
address = "2, Moorgate")))
`fails with` ("All participants have signed the transaction")
}
}
@Test
fun `The supplier has changed`() {
ledgerServices.transaction() {
command(listOf(regulator.publicKey), AccountContract.Commands.Modify())
input(AccountContract.ID, defaultState)
output(AccountContract.ID, defaultState.copy(
supplier = ukPower.party))
`fails with` ("The old and new supplier must be the same")
}
}
@Test
fun `Mandatory fields have not been populated`() {
// TODO: See if we can make this a proper JUnit parameterised test
for ((firstName, lastName) in listOf(
Pair("", ""),
Pair("Joe", ""),
Pair("", "Blogs"))) {
ledgerServices.transaction() {
command(defaultSigners, AccountContract.Commands.Modify())
input(AccountContract.ID, defaultState)
output(AccountContract.ID,
defaultState.copy(
customerDetails = defaultState.customerDetails.copy(
firstName = firstName,
lastName = lastName)))
`fails with` ("Name is populated")
}
}
ledgerServices.transaction() {
command(defaultSigners, AccountContract.Commands.Modify())
input(AccountContract.ID, defaultState)
output(AccountContract.ID,
defaultState.copy(
customerDetails = defaultState.customerDetails.copy(
address = "")))
`fails with` ("Address is populated")
}
}
@Test
fun `Invalid date of birth provided`() {
// TODO: See if we can make this a proper JUnit parameterised test
for (dateOfBirth in listOf(LocalDate.now(), LocalDate.now().minusYears(150))) {
ledgerServices.transaction() {
command(defaultSigners, AccountContract.Commands.Modify())
input(AccountContract.ID, defaultState)
output(AccountContract.ID,
defaultState.copy(
customerDetails = defaultState.customerDetails.copy(
dateOfBirth = dateOfBirth)))
`fails with` ("Date Of Birth is valid")
}
}
}
@Test
fun `Valid modify transaction`() {
ledgerServices.transaction() {
command(defaultSigners, AccountContract.Commands.Modify())
input(AccountContract.ID, defaultState)
output(AccountContract.ID,
defaultState.copy(
customerDetails = defaultState.customerDetails.copy(
address = "2, Moorgate")))
verifies()
}
}
} |
2020年12月03日21时数据
Status: 200
1.奚梦瑶发长文谈产后抑郁
微博热度:3763516
2.澳总理微信发文被删
微博热度:2497848
3.李佳琦增补为上海青联委员
微博热度:1275507
4.离婚证必须双方同时领取
微博热度:1265950
5.孙俪一件衣服穿十年
微博热度:1223789
6.明年1月1日起办理离婚将设冷静期
微博热度:1096561
7.当我妈妈必须先当硕士
微博热度:900769
8.四川失联女子疑在菲律宾遭男友杀害
微博热度:892617
9.美发布限制中共党员及家属赴美旅行新规
微博热度:876433
10.华春莹回应澳总理微信发文被删
微博热度:871286
11.张雨绮被减肥失败冒犯到
微博热度:856275
12.张子枫古装造型
微博热度:845090
13.丁真高原藏族妆
微博热度:839622
14.Uzi解说GNR
微博热度:808391
15.黄一川被执行死刑
微博热度:787833
16.木子洋室内抽烟
微博热度:758126
17.Sunnee机场要邓紫棋签名
微博热度:749319
18.凶宅试住主播
微博热度:725593
19.广州恒大将改名广州队
微博热度:720815
20.掌中之物
微博热度:716216
21.李沁一米长发
微博热度:683375
22.丁真的舅舅像疯了的郑伊健
微博热度:567948
23.骑爸爸最好的马 骑珍珠
微博热度:440681
24.00后男生眼线消费增速是女生4倍
微博热度:430592
25.丁真的舅舅简直是糊弄学大师
微博热度:413271
26.生日快乐是别人的
微博热度:372941
27.东北民房着火村民铲雪灭火
微博热度:371312
28.教育部答复义务教育改为十二年制建议
微博热度:358739
29.浓眉顶薪续约湖人
微博热度:358256
30.连电视剧都不敢这么拍
微博热度:357997
31.王霏霏在逃香水图鉴
微博热度:309356
32.离婚冷静期实施条款
微博热度:289888
33.澳总理希望与中国建设性接触
微博热度:281608
34.丁真直播
微博热度:278928
35.唐嫣摄影师回应粉丝不满
微博热度:268996
36.丁真有多爱他的小马珍珠
微博热度:243988
37.冬季护肤误区
微博热度:234313
38.离婚冷静期有必要吗
微博热度:231454
39.2020年将为有记录以来最暖年份之一
微博热度:230814
40.南北方搓澡文化的差异
微博热度:230248
41.体育老师示范动作有多可爱
微博热度:215552
42.云南初中学生体育音乐美术考试方案
微博热度:200981
43.错换人生当事人起诉开封卫健委
微博热度:187930
44.刘雯在走廊走出秀场的感觉
微博热度:174467
45.拜登拟任命亚洲事务主管
微博热度:156525
46.马斯克称人类应该提防人口崩溃
微博热度:150708
47.CBA
微博热度:113607
48.最高法强调坚决杜绝年底不立案
微博热度:107788
49.这就是北方人的快乐吗
微博热度:107188
50.申花
微博热度:105424
|
let loadGame = function() {
/*
cardDeckContract.events.DeckReady({
}, function(error, event) {
console.log('EVENTT', event);
})
.on('data', function(event) {
return cards.init({ table: '#card-table', type: STANDARD })
.then(res => {
startGame();
});
});
let from = web3.eth.defaultAccount;
return blackjackContract.methods.shuffleDeck().send({from})
*/
}
let startGame = function() {
//Tell the library which element to use for the table
cards.init({ table: '#card-table', type: STANDARD });
//Create a new deck of cards
deck = new cards.Deck();
//By default it's in the middle of the container, put it slightly to the side
deck.x -= 25;
deck.y -= 125;
console.log('ALL CARDS LETS SEE', cards);
//cards.all contains all cards, put them all in the deck
deck.addCards(cards.all);
//No animation here, just get the deck onto the table.
deck.render({ immediate: true });
//Now lets create a couple of hands, one face down, one face up.
upperhand = new cards.Hand({ faceUp: true, x: 0, y: 340 });//player2
lowerhand = new cards.Hand({ faceUp: true, x: 80, y: 340 });//player1
dealerhand = new cards.Hand({ faceUp: true });
dealerhand.x += 50;
//Let's deal when the Deal button is pressed:
$('#deal').click(function () {
//Deck has a built in method to deal to hands.
$('#deal').hide();
// deck.deal(1, [upperhand, lowerhand], 50, function() {
deck.deal(1, [upperhand, lowerhand, dealerhand], 700, function () {
//This is a callback function, called when the dealing
//is done.
// dealerhand.addCard(deck.topCard());
deck.deal(1, [upperhand, lowerhand, dealerhand], 700, function() {
dealerhand.render();
calculateScores();
});
});
calculateScores();
});
let playerScore1 = document.getElementById('score1');
let playerScore2 = document.getElementById('score2');
let dealerScore = document.getElementById('dealerscore');
//hit player1
$('#hit1').click(function (card) {
lowerhand.addCard(deck.topCard());
lowerhand.render();
console.log(card);
dealerhand.addCard(deck.topCard());
dealerhand.render();
calculateScores();
});
let calculateScores = function() {
// Add up cards
let player1Score = 0;
let player2Score = 0;
let dealerScore = 0;
for(let _card in lowerhand) {
if( !isNaN(parseInt(_card)) )
player1Score += lowerhand[_card].rank;
}
for(let _card in dealerhand) {
if( !isNaN(parseInt(_card)) )
dealerScore += dealerhand[_card].rank;
}
for(let _card in upperhand) {
if( !isNaN(parseInt(_card)) )
player2Score += upperhand[_card].rank;
}
playerScore1.innerHTML = player1Score;
playerScore2.innerHTML = player2Score;
//if any dealer score > 21, or player 1 score = 21, player 1 wins
if(player1Score === 21 || dealerScore > 21) {
win(true, {you: player1Score, dealer: dealerScore });
console.log('WIN OR LOSE', true);
}
//else if any dealer score = 21, or player 1 score > 21 dealer wins
else if(player1Score > 21 || dealerScore === 21) {
win(false, {you: player1Score, dealer: dealerScore });
console.log('WIN OR LOSE', false);
}
}
//hit player2
$('#hit2').click(function (card) {
console.info("Can't do this");
/**
upperhand.addCard(deck.topCard());
upperhand.render();
calculateScores();
// playerScore2.innerHTML = upperhand[0].rank + upperhand[1].rank + upperhand[2].rank;
console.log(card);
console.log(upperhand[0].rank + upperhand[1].rank);
*/
});
upperhand.click(function (card) {
console.log(card);
});
lowerhand.click(function (card) {
console.log(card);
});
dealerhand.click(function (card) {
card.showCard();
card.render();
console.log(card);
});
}
|
# Import required libraries
import numpy as np
import pandas as pd
from numpy import std
from numpy import mean
from math import sqrt
import matplotlib.pyplot as plt
from sklearn import linear_model
from scipy.stats import spearmanr
from sklearn.metrics import r2_score
from sklearn.metrics import max_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import median_absolute_error
from sklearn.metrics import mean_squared_log_error
#Github: https://github.com/sujitmandal
#This programe is create by Sujit Mandal
"""
Github: https://github.com/sujitmandal
This programe is create by Sujit Mandal
LinkedIn : https://www.linkedin.com/in/sujit-mandal-91215013a/
Facebook : https://www.facebook.com/sujit.mandal.33671748
Twitter : https://twitter.com/mandalsujit37
"""
#Read Data
data = pd.read_csv('Salary_Data.csv')
#Data Visualition
print(data.head(5))
print('\n')
print(data.tail(5))
print('\n')
print(data.shape)
#Data Processing
x = data['YearsExperience'].values.reshape(-1,1)
y = data['Salary'].values.reshape(-1,1)
xnew = x[20:30]
ynew = y[20:30]
x = x[:20]
y = y[:20]
#Data Visualition After Processing
print('\n')
print('xnew:',xnew.shape)
print('ynew:',ynew.shape)
print('x:',x.shape)
print('y:',y.shape)
#Scatter Plot
plt.title('YearsExperience vs. Salary')
plt.xlabel('YearsExperience')
plt.ylabel('Salary')
plt.scatter(x,y)
plt.show()
x_mean = mean(x)
x_stdv = std(x)
y_mean = mean(y)
y_stdv = std(y)
print('\n')
print('X Mean = %0.3f' % x_mean)
print('X Standard Deviation = %0.3f' %x_stdv)
print('\n')
print('Y Mean = %0.3f' % y_mean)
print('Y Standard Deviation = %0.3f' %y_stdv)
#Spearman's Correlation
correlation, _ = spearmanr(x, y)
print('\n')
print('Spearmans correlation: %.5f' % correlation)
#Regression Model
lr = linear_model.Lasso(alpha=1.0).fit(x, y)
print('\n')
print(lr)
intercept = (lr.intercept_)
print('\n')
print('Intercept: %.5f' % intercept)
#Prediction
predict = lr.predict(xnew)
print('\n')
print('Prediction:')
print(predict)
x_true = xnew
y_true = ynew
y_pred = predict
score = lr.score(y_true, y_pred)
print('\n')
print('Score: %.5f' % score)
#Coefficients
coef = (lr.coef_)
print('Coefficients: ', coef)
#R^2 (coefficient of determination)
r2_Score = r2_score(y_true, y_pred)
print('r2 Score : %.5f' % r2_Score)
#Root Mean Squared Error
rmse = sqrt(mean_squared_error(y_true, y_pred))
print('\n')
print('Model Result :')
print('Root Mean Squared Error = %0.3f' % rmse)
#Mean Squared Error
mse = mean_squared_error(y_true, y_pred)
print('Mean Squared Error = %0.3f' % mse)
#Mean Absolute Error
mae = mean_absolute_error(y_true, y_pred)
print('Mean Absolute Error = %0.3f' % mae)
#Median Absolute Error
med_ea = median_absolute_error(y_true, y_pred)
print('Median Absolute Error = %0.3f' % med_ea)
#Mean Squared Log Error
msle = mean_squared_log_error(y_true, y_pred)
print('Mean Squared Log Error = %0.3f' % msle)
#Max Error
me = max_error(y_true, y_pred)
print('Max Error = %0.3f' % me)
#Polt Actual vs. Predicted
plt.title('Actual vs. Predicted')
plt.xlabel('YearsExperience')
plt.ylabel('Salary')
plt.scatter(x_true, y_true)
plt.scatter(x_true, y_pred)
plt.show()
#Outputs Plot
plt.title('Actual vs. Predicted')
plt.xlabel('YearsExperience')
plt.ylabel('Salary')
plt.scatter(x_true, y_true)
plt.scatter(x_true, y_pred, color='r')
plt.plot(x_true, y_pred, color='y', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
#OUTPUT :
'''
YearsExperience Salary
0 1.1 39343.0
1 1.3 46205.0
2 1.5 37731.0
3 2.0 43525.0
4 2.2 39891.0
YearsExperience Salary
25 9.0 105582.0
26 9.5 116969.0
27 9.6 112635.0
28 10.3 122391.0
29 10.5 121872.0
(30, 2)
xnew: (10, 1)
ynew: (10, 1)
x: (20, 1)
y: (20, 1)
X Mean = 3.590
X Standard Deviation = 1.432
Y Mean = 59304.250
Y Standard Deviation = 14381.643
Spearmans correlation: 0.87058
Lasso(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=1000,
normalize=False, positive=False, precompute=False, random_state=None,
selection='cyclic', tol=0.0001, warm_start=False)
Intercept: 26579.15132
Prediction:
[ 88565.41065418 91300.09856578 98592.5996634 101327.287575
105885.10076101 108619.78867262 113177.60185863 114089.16449583
120470.10295624 122293.22823065]
Score: -8395486220.93957
Coefficients: [9115.62637202]
r2 Score : 0.71529
Model Result :
Root Mean Squared Error = 5138.616
Mean Squared Error = 26405370.644
Mean Absolute Error = 3951.098
Median Absolute Error = 3105.189
Mean Squared Log Error = 0.002
Max Error = 12484.712
'''
|
/*!
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project.
*/
import * as React from 'react'
import styled from 'styled-components'
import theme from '../util/theme'
const PrivacyStatement: React.SFC = () => (
<PrivacyText>
This site does not collect any personal information or use cookies.
<PrivacyLink
target="_blank"
href="https://privacy.microsoft.com/en-us/privacystatement/"
>
Read Microsoft's statement on Privacy and Cookies.
</PrivacyLink>
</PrivacyText>
)
const PrivacyText = styled.div`
color: ${theme.palette.whitish};
font-family: sans-serif;
font-size: 12px;
`
const PrivacyLink = styled.a`
color: ${theme.palette.highlight};
font-family: sans-serif;
font-size: 12px;
`
export default PrivacyStatement
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// Here we are testing that SSA and liveness agree on whether a dead
// partial store constitues a use (it does, in our model).
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class PartialDefLiveness
{
public static int Main()
{
// Just making sure we'll not hit any asserts in SSA.
Problem();
return 100;
}
[SkipLocalsInit]
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Problem()
{
Unsafe.SkipInit(out EnormousStruct a);
// We expect liveness to fail to remove this dead store.
a.Field = 1;
}
[StructLayout(LayoutKind.Explicit, Size = ushort.MaxValue + 1 + sizeof(int))]
struct EnormousStruct
{
[FieldOffset(ushort.MaxValue + 1)]
public int Field;
}
}
|
@extends('template.main')
@section('title','Crear Semestre')
@section('content')
{!! Form::open(['route'=>'admin.semestres.store', 'method'=>'POST']) !!}
<table>
<tbody>
<tr>
<td>{!! Form::label('semestre','Semestre') !!}
{!! Form::text('semestre', null, ['class'=>'form-control', 'placeholder'=>'Semestre','required']) !!}
</td>
<td>
{!! Form::label('swactivo','Activo') !!}
{{ Form::hidden('swactivo', 0) }}
{{ Form::checkbox('swactivo', '1',0, ['class'=>'checkbox'] )}}
</td>
</tr>
<tr>
<td>
{!! Form::label('inicio','inicio') !!}
{!! Form::text('inicio', null, ['class'=>'form-control','']) !!}
</td>
<td>
{!! Form::label('fin','fin') !!}
{!! Form::text('fin', null, ['class'=>'form-control','']) !!}
</td>
<td>
{!! Form::label('cierredisp','cierredisp') !!}
{!! Form::text('cierredisp', null, ['class'=>'form-control','']) !!}
</td>
<td>
{!! Form::label('cierredata','cierredata') !!}
{!! Form::text('cierredata', null, ['class'=>'form-control','']) !!}
</td>
</tr>
</tbody>
</table>
<div class="form-group">
{!! Form::submit('Registrar', ['class'=>'btn btn-lg btn-primary']) !!}
</div>
{!! Form::close() !!}
@endsection |
"""Unit tests for chartjs api."""
import json
from django.test import TestCase
try:
from django.urls import reverse
except ImportError:
# remove import shim when support for django 1.9 is dropped
from django.core.urlresolvers import reverse
from demoproject._compat import decode
from demoproject.models import Meter
from chartjs.util import value_or_null, NULL
class LineChartJSTestCase(TestCase):
def test_line_chartjs(self):
resp = self.client.get(reverse('line_chart'))
self.assertContains(resp, 'Chart.min.js')
def test_list_chartjs_json(self):
resp = self.client.get(reverse('line_chart_json'))
try:
data = json.loads(decode(resp.content))
except ValueError:
self.fail("%r is not valid json" % self.resp.content)
self.assertIn('datasets', data)
self.assertNotIn('series', data)
class ColorTestCase(TestCase):
def test_colorview(self):
resp = self.client.get(reverse('colors'))
self.assertContains(resp, '100px')
class HighChartJSTestCase(TestCase):
def test_column_chartjs_json(self):
resp = self.client.get(reverse('column_highchart_json'))
try:
data = json.loads(decode(resp.content))
except ValueError:
self.fail("%r is not valid json" % self.resp.content)
self.assertIn('title', data)
self.assertIn('text', data['title'])
self.assertEqual(data['title']['text'], 'Column Highchart test')
self.assertIn('credits', data)
credits = data['credits']
self.assertEqual(credits['enabled'], False)
def test_list_chartjs_json(self):
resp = self.client.get(reverse('line_highchart_json'))
try:
data = json.loads(decode(resp.content))
except ValueError:
self.fail("%r is not valid json" % self.resp.content)
self.assertIn('series', data)
self.assertNotIn('datasets', data)
self.assertIn('credits', data)
credits = data['credits']
self.assertEqual(credits['enabled'], True)
self.assertEqual(credits['href'], 'http://example.com')
self.assertEqual(credits['text'], 'Novapost Team')
def test_pie_chartjs_json(self):
resp = self.client.get(reverse('pie_highchart_json'))
try:
json.loads(decode(resp.content))
except ValueError:
self.fail("%r is not valid json" % self.resp.content)
def test_donut_chartjs_json(self):
resp = self.client.get(reverse('donut_highchart_json'))
try:
json.loads(decode(resp.content))
except ValueError:
self.fail("%r is not valid json" % self.resp.content)
class DiscontinuousDataTestCase(TestCase):
def setUp(self):
self.start_date = "2019-05-26"
self.end_date = "2019-06-04"
# water meter readings
Meter.objects.create(date="2019-05-26", name="water", reading=10)
Meter.objects.create(date="2019-05-27", name="water", reading=12)
Meter.objects.create(date="2019-05-28", name="water", reading=13)
Meter.objects.create(date="2019-05-29", name="water", reading=15)
Meter.objects.create(date="2019-06-01", name="water", reading=16)
Meter.objects.create(date="2019-06-02", name="water", reading=18)
Meter.objects.create(date="2019-06-03", name="water", reading=20)
Meter.objects.create(date="2019-06-04", name="water", reading=21)
# gas meter readings
Meter.objects.create(date="2019-05-28", name="gas", reading=15)
Meter.objects.create(date="2019-05-29", name="gas", reading=13)
Meter.objects.create(date="2019-05-30", name="gas", reading=12)
Meter.objects.create(date="2019-05-31", name="gas", reading=14)
Meter.objects.create(date="2019-06-01", name="gas", reading=16)
Meter.objects.create(date="2019-06-02", name="gas", reading=17)
def test_generator_fills_end_values_with_null(self):
queryset = Meter.objects.filter(name="gas")
actual_data = []
for item in value_or_null(self.start_date, self.end_date, queryset, "date", "reading"):
actual_data.append(item)
expected_data = [NULL, NULL, 15, 13, 12, 14, 16, 17, NULL, NULL]
self.assertEqual(actual_data, expected_data)
def test_generator_fills_middle_values_with_null(self):
queryset = Meter.objects.filter(name="water")
actual_data = []
for item in value_or_null(self.start_date, self.end_date, queryset, "date", "reading"):
actual_data.append(item)
expected_data = [10, 12, 13, 15, NULL, NULL, 16, 18, 20, 21]
self.assertEqual(actual_data, expected_data)
|
#ifndef ATOMICTEST_H
#define ATOMICTEST_H
#include <inttypes.h>
#include <stdexcept>
#include <vector>
#include <iostream>
class AtomicTest {
public:
AtomicTest() = delete;
AtomicTest(uint64_t idx, uint64_t testId, uint64_t variantIdx,
uint64_t subtestIdx, uint64_t statisticIdx)
: _idx(idx), _testId(testId), _variantIdx(variantIdx),
_subtestIdx(subtestIdx), _statisticIdx(statisticIdx)
{}
uint64_t getIdx() const {
return _idx;
}
uint64_t getTestId() const{
return _testId;
}
double getResult(const uint64_t & runIdx) const {
return _results.at(runIdx - 1);
}
std::vector<double> getResults() const {
return _results;
}
uint64_t getRunsCount() const {
return _results.size();
}
void setResults(const std::vector<double> & results) {
_results = results;
}
void print(std::ostream & out) const {
out << "Atomic IDX: " << _idx << "; "
<< "Test ID: " << _testId << "; "
<< "Variant IDX: " << _variantIdx << "; "
<< "Subtest IDX: " << _subtestIdx << "; "
<< "Statistic IDX: " << _statisticIdx << std::endl;
}
private:
uint64_t _idx;
uint64_t _testId;
uint64_t _variantIdx;
uint64_t _subtestIdx;
uint64_t _statisticIdx;
std::vector<double> _results;
};
/**
* @brief The AtomicTestList class Helper class that holds vector of AtomicTests and enforces correct access
* to the elements based on their indices
*/
class AtomicTestList {
public:
AtomicTestList() = delete;
AtomicTestList(const std::vector<AtomicTest> & list)
: _list(list)
{
if(_list.empty())
throw std::runtime_error("list can't be empty");
}
double getAtomicTestResult(const uint64_t & atomicTestIdx, const uint64_t & runIdx) const {
return getAtomicTestByIdx(atomicTestIdx).getResult(runIdx);
}
void printAtomicTest(std::ostream & out, const uint64_t & atomicTestIdx) const {
getAtomicTestByIdx(atomicTestIdx).print(out);
}
size_t getRunsCount() const {
return _list.front().getRunsCount();
}
/* Operator for accessing the underlying vector directly.
* Only constant reference is returned. */
friend const std::vector<AtomicTest> & operator*(const AtomicTestList & o) {
return o._list;
}
private:
std::vector<AtomicTest> _list;
const AtomicTest & getAtomicTestByIdx(const uint64_t & idx) const {
const auto & t = _list.at(idx - 1);
/* Preventive sanity check */
if(t.getIdx() != idx) {
throw std::runtime_error("AtomicTestList was incorrectly initialized: element "
"on position idx - 1 have _idx != idx");
}
return t;
}
};
#endif // ATOMICTEST_H
|
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Chapter3.DataObjects;
using Chapter3.Extensions;
using Chapter3.Models;
using Microsoft.Azure.Mobile.Server;
using Microsoft.Azure.Mobile.Server.Authentication;
namespace Chapter3.Controllers
{
[Authorize]
public class ExampleController : TableController<Example>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
MobileServiceContext context = new MobileServiceContext();
DomainManager = new EntityDomainManager<Example>(context, Request, enableSoftDelete: true);
}
/// <summary>
/// Get the list of groups from the claims
/// </summary>
/// <returns>The list of groups</returns>
public async Task<List<string>> GetGroups()
{
var creds = await User.GetAppServiceIdentityAsync<AzureActiveDirectoryCredentials>(Request);
return creds.UserClaims
.Where(claim => claim.Type.Equals("groups"))
.Select(claim => claim.Value)
.ToList();
}
/// <summary>
/// Validator to determine if the provided group is in the list of groups
/// </summary>
/// <param name="group">The group name</param>
public async Task ValidateGroup(string group)
{
var groups = await GetGroups();
if (!groups.Contains(group))
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
}
// GET tables/Example
public async Task<IQueryable<Example>> GetAllExample()
{
var groups = await GetGroups();
return Query().PerGroupFilter(groups);
}
// GET tables/Example/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<SingleResult<Example>> GetExample(string id)
{
var groups = await GetGroups();
return new SingleResult<Example>(Lookup(id).Queryable.PerGroupFilter(groups));
}
// PATCH tables/Example/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<Example> PatchExample(string id, Delta<Example> patch)
{
await ValidateGroup(patch.GetEntity().GroupId);
return await UpdateAsync(id, patch);
}
// POST tables/Example
public async Task<IHttpActionResult> PostExample(Example item)
{
await ValidateGroup(item.GroupId);
Example current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/Example/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteExample(string id)
{
return DeleteAsync(id);
}
}
}
|
import classNames from 'classnames'
import PropTypes, { InferProps } from 'prop-types'
import { AtRateProps } from 'types/rate'
import { Text, View } from '@tarojs/components'
import { CommonEvent } from '@tarojs/components/types/common'
import Taro from '@tarojs/taro'
import AtComponent from '../../common/component'
import { initTestEnv } from '../../common/utils'
initTestEnv()
export default class AtRate extends AtComponent<AtRateProps> {
public static defaultProps: AtRateProps
public static propTypes: InferProps<AtRateProps>
private handleClick(event: CommonEvent) {
this.props.onChange && this.props.onChange(event)
}
public render(): JSX.Element {
const { customStyle, className, value, max, size, margin } = this.props
const iconStyle = {
marginRight: Taro.pxTransform(margin!)
}
const starIconStyle = {
fontSize: size ? `${size}px` : ''
}
// 生成星星颜色 className 数组,方便在jsx中直接map
const classNameArr: string[] = []
const floorValue = Math.floor(value!)
const ceilValue = Math.ceil(value!)
for (let i = 0; i < max!; i++) {
if (floorValue > i) {
classNameArr.push('at-rate__icon at-rate__icon--on')
} else if (ceilValue - 1 === i) {
classNameArr.push('at-rate__icon at-rate__icon--half')
} else {
classNameArr.push('at-rate__icon at-rate__icon--off')
}
}
return (
<View className={classNames('at-rate', className)} style={customStyle}>
{classNameArr.map((cls, i) => (
<View
className={cls}
key={`at-rate-star-${i}`}
style={iconStyle}
onClick={this.handleClick.bind(this, i + 1)}
>
<Text
className='at-icon at-icon-star-2'
style={starIconStyle}
></Text>
<View className='at-rate__left'>
<Text
className='at-icon at-icon-star-2'
style={starIconStyle}
></Text>
</View>
</View>
))}
</View>
)
}
}
AtRate.defaultProps = {
customStyle: '',
className: '',
size: 0,
value: 0,
max: 5,
margin: 5,
onChange: () => {}
}
AtRate.propTypes = {
customStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
className: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
value: PropTypes.number,
max: PropTypes.number,
margin: PropTypes.number,
onChange: PropTypes.func
}
|
import React from "react"
import {
Box,
BoxProps,
GridColumns,
Column,
Flex,
HTML,
Text,
} from "@artsy/palette"
import { createFragmentContainer, graphql } from "react-relay"
import { FairHeader_fair } from "v2/__generated__/FairHeader_fair.graphql"
import { ForwardLink } from "v2/Components/Links/ForwardLink"
import { FairTimingFragmentContainer as FairTiming } from "./FairTiming"
import { FairHeaderImageFragmentContainer as FairHeaderImage } from "./FairHeaderImage"
import { FairHeaderIconFragmentContainer } from "./FairHeaderIcon"
interface FairHeaderProps extends BoxProps {
fair: FairHeader_fair
}
const FairHeader: React.FC<FairHeaderProps> = ({ fair, ...rest }) => {
const {
about,
tagline,
location,
ticketsLink,
hours,
links,
contact,
summary,
tickets,
} = fair
const canShowMoreInfoLink =
!!about ||
!!tagline ||
!!location?.summary ||
!!ticketsLink ||
!!hours ||
!!links ||
!!contact ||
!!summary ||
!!tickets
const previewText = summary || about
const columnCount = previewText ? 2 : 1
return (
<Box {...rest}>
<FairHeaderImage fair={fair} />
<GridColumns mt={[2, 4]}>
<Column span={6}>
<Flex mb={2}>
<FairHeaderIconFragmentContainer fair={fair} mr={2} />
<Text as="h1" variant="largeTitle">
{fair.name}
</Text>
</Flex>
<FairTiming fair={fair} />
</Column>
<Column span={6}>
<HTML variant="subtitle" lineHeight="body" html={previewText} />
{canShowMoreInfoLink && (
<ForwardLink
to={`/fair/${fair.slug}/info`}
mt={previewText ? 1 : undefined}
justifyContent={columnCount === 1 ? "center" : undefined}
>
More info
</ForwardLink>
)}
</Column>
</GridColumns>
</Box>
)
}
export const FairHeaderFragmentContainer = createFragmentContainer(FairHeader, {
fair: graphql`
fragment FairHeader_fair on Fair {
...FairTiming_fair
...FairHeaderImage_fair
...FairHeaderIcon_fair
about(format: HTML)
summary(format: HTML)
name
slug
# Used to figure out if we should render the More info link
tagline
location {
summary
}
ticketsLink
hours(format: HTML)
links(format: HTML)
tickets(format: HTML)
contact(format: HTML)
}
`,
})
|
<?php
namespace Tests\Unit;
use App\Docsets\ChartjsPluginDatalabels;
use Godbout\DashDocsetBuilder\Services\DocsetBuilder;
use Tests\TestCase;
class ChartjsPluginDatalabelsTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
$this->docset = new ChartjsPluginDatalabels();
$this->builder = new DocsetBuilder($this->docset);
}
/** @test */
public function it_can_generate_a_table_of_contents()
{
$toc = $this->docset->entries(
$this->docset->downloadedIndex()
);
$this->assertNotEmpty($toc);
}
}
|
import numpy as np
from glob import glob
import subprocess
import os
import shutil
import json
import audiofile
from concurrent.futures import ProcessPoolExecutor
"""
FFMPEG convert all mp4 to aac
ls *mp4 | parallel --dry-run "ffmpeg -i {} -vn -acodec copy {/.}.aac"
Do above command parrallel for all folders
for f in *; do ls $f/*mp4 | parallel "ffmpeg -i {} -vn -acodec copy $f/{/.}.aac"; done
"""
def seperate_real_and_fake_audio(f):
metadata = os.path.join(f, 'metadata.json')
os.makedirs(os.path.join(f, 'audio', 'real'), exist_ok=True)
os.makedirs(os.path.join(f, 'audio', 'fake'), exist_ok=True)
with open(metadata, 'r') as w:
d = json.load(w)
for key,value in d.items():
original_video = value.get('original', None)
if original_video:
# get real audio stream
real_audio_file = os.path.join(f, original_video.split('.')[0] + '.aac')
rsig, rfs = audiofile.read(real_audio_file)
# get fake audio stream
fake_audio_file = os.path.join(f, key.split('.')[0] + '.aac')
fsig, ffs = audiofile.read(fake_audio_file)
# compare
if not np.array_equal(rsig, fsig):
if os.path.exists(fake_audio_file):
shutil.move(fake_audio_file, os.path.join(f, 'audio', 'fake'))
if __name__ == '__main__':
fl = glob('../raw/*')
with ProcessPoolExecutor(max_workers=60) as executor:
executor.map(seperate_real_and_fake_audio, fl)
|
# frozen_string_literal: true
# Preview all emails at http://localhost:3000/rails/mailers/request_guest_review_mailer
class RequestGuestReviewMailerPreview < ActionMailer::Preview
def request_review_mail
demo_reservation = Reservation.first
RequestGuestReviewMailer
.with(reservation: demo_reservation)
.request_review
end
end
|
using Newtonsoft.Json;
namespace ArgentPonyWarcraftClient
{
/// <summary>
/// RGBA color information.
/// </summary>
public class ColorDetails
{
/// <summary>
/// Gets the red channel value for the color.
/// </summary>
[JsonProperty("r")]
public long Red { get; set; }
/// <summary>
/// Gets the green channel value for the color.
/// </summary>
[JsonProperty("g")]
public long Green { get; set; }
/// <summary>
/// Gets the blue channel value for the color.
/// </summary>
[JsonProperty("b")]
public long Blue { get; set; }
/// <summary>
/// Gets the alpha (opacity) channel value for the color.
/// </summary>
[JsonProperty("a")]
public long Alpha { get; set; }
}
}
|
require "yaml"
module SecureConf
module Storage
module Yaml
def self.load(path)
if File.file?(path)
YAML.load_file(path)
else
{}
end
end
def self.save(path, obj)
h = {}
h.replace(obj)
File.open(path, "w") {|f|
YAML.dump(h, f)
}
end
end
Yml = Yaml
end
end
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.kotlin.api.trace
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.shouldBe
import io.opentelemetry.kotlin.api.internal.OtelEncodingUtils
import kotlin.test.Test
/** Unit tests for {@link TraceId}. */
class TraceIdTest {
private val first: String
get() {
return "00000000000000000000000000000061"
}
private val second: String
get() {
return "ff000000000000000000000000000041"
}
@Test
fun invalid() {
TraceId.invalid shouldBe "00000000000000000000000000000000"
}
@Test
fun isValid() {
TraceId.isValid(null).shouldBeFalse()
TraceId.isValid("001").shouldBeFalse()
TraceId.isValid("000000000000004z0000000000000016").shouldBeFalse()
TraceId.isValid(TraceId.invalid).shouldBeFalse()
TraceId.isValid(first).shouldBeTrue()
TraceId.isValid(second).shouldBeTrue()
}
@Test
fun fromLongs() {
TraceId.fromLongs(0, 0) shouldBe TraceId.invalid
TraceId.fromLongs(0, 0x61) shouldBe first
TraceId.fromLongs(0xff00000000000000u.toLong(), 0x41) shouldBe second
TraceId.fromLongs(0xff01020304050600u.toLong(), 0xff0a0b0c0d0e0f00u.toLong()) shouldBe
"ff01020304050600ff0a0b0c0d0e0f00"
}
@Test
fun fromBytes() {
val traceId = "0102030405060708090a0b0c0d0e0f00"
TraceId.fromBytes(OtelEncodingUtils.bytesFromBase16(traceId, TraceId.length)) shouldBe
traceId
}
@Test
fun fromBytes_Invalid() {
TraceId.fromBytes(null) shouldBe TraceId.invalid
TraceId.fromBytes(byteArrayOf(1, 2, 3, 4)) shouldBe TraceId.invalid
}
}
|
package org.mbari.vars.ui.javafx.rectlabel;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Shape;
/**
* @author Brian Schlining
* @since 2018-05-08T16:44:00
*/
public class BoundingBoxCreatedEvent {
protected final AnchorPane anchorPane;
protected final Shape shape;
public BoundingBoxCreatedEvent(AnchorPane anchorPane, Shape shape) {
this.anchorPane = anchorPane;
this.shape = shape;
}
public AnchorPane getAnchorPane() {
return anchorPane;
}
public Shape getShape() {
return shape;
}
}
|
#/bin/bash
#
##
## Usage: archlinux
##
## This script automates the building of ownCloud documentation on the ArchLinux platform.
## While new, it should handle installing all of the required platform dependencies, and afterwards
## build the documentation.
##
## Author: Matthew Setter <[email protected]>
##
set -e
function install_dependencies()
{
sudo pacman-key --refresh-keys
sudo pacman --noconfirm -Syy
sudo pacman --noconfirm -S community/python2-rst2pdf community/python2-sphinx extra/texlive-core texlive-latexextra
sudo easy_install -U sphinxcontrib-phpdomain
}
install_dependencies
|
namespace Test.Unit.Core.Domain.Models
{
using System;
using CompanyName.Notebook.NoteTaking.Core.Domain.Models;
using NSubstitute;
using NUnit.Framework;
[TestFixture]
public class NoteTester
{
[Test]
public void CanCreateNote()
{
// ARRANGE
var expectedText = "Don't to forget to pick up bread from the grocery store.";
// ACT
var subjectUnderTest = new Note(expectedText);
// ASSERT
Assert.That(subjectUnderTest, Is.TypeOf(typeof(Note)));
Assert.That(subjectUnderTest.Text, Is.EqualTo(expectedText));
Assert.That(subjectUnderTest.Id, Is.Not.EqualTo(Guid.Empty));
Assert.That(subjectUnderTest.Created, Is.LessThanOrEqualTo(DateTime.UtcNow));
}
[Test]
public void DoesThrowArgumentExceptionDefaultConstructor()
{
// ARRANGE
var expectedExceptionMessage = "New Note must have text. (Parameter 'text')";
// ACT
// ASSERT
var ex = Assert.Throws<ArgumentException>(
() => new Note(null)
);
Assert.That(ex.Message, Is.EqualTo(expectedExceptionMessage));
}
}
}
|
import React from "react";
import { capitalize, getPriceDollars } from "./Util";
import PaymentForm from "./PaymentForm";
const SummaryTable = (props) => {
const { discountFactor, minItemsForDiscount, items, order } = props;
//Return array of selected items
var getSelectedItems = () => {
return items.filter((item) => item.selected);
};
//Calculate total before applying discount
var computeSubTotal = () => {
return getSelectedItems(items)
.map((item) => item.price)
.reduce((item1, item2) => item1 + item2, 0);
};
//Check if discount apply to order
var computeDiscountPercentage = () => {
return minItemsForDiscount <= order.length ? discountFactor : 0;
};
//Calculate total discount
var computeDiscount = () => {
return computeSubTotal() * computeDiscountPercentage();
};
//Calculate total after discount
var computeTotal = () => {
let subTotal = computeSubTotal();
let discount = computeDiscount();
return subTotal - discount;
};
//Generate order summary HTML
var buildOrderSummary = (rowClass, desc, amountCents) => {
return (
<div className="summary-row">
<div className={`${rowClass} summary-title`}>{capitalize(desc)}</div>
<div className={`${rowClass} summary-price`}>
{getPriceDollars(amountCents)}
</div>
</div>
);
};
const selectedItems = getSelectedItems();
const discount = computeDiscount();
const subTotal = computeSubTotal();
const active = order.length > 0;
return (
<div className="sr-main">
<div className="sr-summary">
<h3>Purchase Summary</h3>
<div
id="summary-preface"
className={`sr-legal-text left ${active ? "hidden" : ""}`}
>
No courses selected.
</div>
<div
id="summary-table"
className={`summary-table ${active ? "" : "hidden"}`}
>
{selectedItems.map((item) =>
buildOrderSummary("summary-product", item.title, item.price)
)}
{discount > 0
? buildOrderSummary("summary-discount", "Discount", discount)
: ""}
{discount > 0
? buildOrderSummary("summary-subtotal", "Subtotal", subTotal)
: ""}
{buildOrderSummary("summary-total", "Total", computeTotal())}
</div>
</div>
{
//Component to generate payment form
}
<PaymentForm active={active} items={selectedItems}/>
</div>
);
};
export default SummaryTable;
|
---
layout: team
title: Elsbeth Geldhof
image: /images/staff/ElsbethGeldhof.jpg
institution: External member
job-title: Independent conservator
---
Elsbeth Geldhof is an independent historic paint conservator, and researcher of longue durée painting techniques and
pigment sources from the ancient world and beyond. In this work, she frequently applies experimental archaeology and
reconstruction techniques to add an art-technological approach and craftsmanship perspective. Elsbeth also manages her
own business Bluetortoise Conservation. |
package com.mxx.blogs.dto;
import com.mxx.blogs.pojo.BlogsArticle;
import lombok.Data;
import java.util.List;
@Data
public class BLogsIndexDto {
private String uName;
private String userName;
private String uImage;
private String passWord;
private boolean isLogin;
private List<BlogsArticle> articles;
public boolean isLogin() {
return isLogin;
}
public void setLogin(boolean login) {
isLogin = login;
}
}
|
@extends('shopify-app::layouts.default')
@section('content')
<!-- You are: (shop domain name) -->
<p>You are: {{ Auth::user()->name }}</p>
<div id="app"></div>
@endsection
@section('scripts')
@parent
@endsection |
// https://getemoji.com/
const faceEmojis = new Map([
['Grinning Face', '😀'],
['Face with Tears of Joy', '😂'],
['Smiling Face with Sunglasses', '😎'],
['Face Blowing a Kiss', '😘'],
['Smiling Face with Heart-Eyes', '😍'],
['Smiling Face with Hearts', '🥰'],
['Sleeping Face', '😴'],
['Angry Face', '😠'],
['Pouting Face', '😡'],
['Face with Thermometer', '🤒'],
['Partying Face', '🥳'],
['Smiling Face with Halo', '😇'],
['', ''],
]);
const profileInfoEmojis = new Map([
['Round Pushpin', '📍'],
['E-Mail', '📧'],
['Spiral Calendar', '🗓️'],
]);
export default faceEmojis;
export { profileInfoEmojis, faceEmojis };
|
// extern crate clap;
//
// use clap::{clap_app, crate_name, crate_version, App, AppSettings};
//
// fn build_app() -> App<'static, 'static> {
// let app = clap_app!(app =>
// (name: crate_name!())
// (version: crate_version!())
// (about: "A tool stitches scripts and commands together by YAML.")
// (max_term_width: 100)
// (global_setting: AppSettings::ColoredHelp)
// (global_setting: AppSettings::UnifiedHelpMessage)
// (global_setting: AppSettings::HidePossibleValuesInHelp)
// (setting: AppSettings::ArgsNegateSubcommands)
// (setting: AppSettings::AllowExternalSubcommands)
// (setting: AppSettings::DisableHelpSubcommand)
// (setting: AppSettings::VersionlessSubcommands)
//
// (@subcommand run =>
// (about: "Execute the given YAML.")
// (@arg YAML: +required "The YAML need to run.")
// (@arg tags: -t --tag +use_delimiter ... "Execute tasks whose tags are matched.")
// (@arg exclude: -e --exclude +use_delimiter ... "Execute tasks whose tags are not matched.")
// )
// );
//
// app
// }
//
// fn main() {
// build_app().get_matches();
// }
use std::fs::File;
use std::io::{self, Write};
use std::process::{Command, Stdio};
use tempfile::{tempdir, tempfile};
fn main() {
use std::fs::{self, File};
use std::io::{self, Write};
use tempfile::tempdir;
// Create a directory inside of `std::env::temp_dir()`.
let result = (|| {
let dir = tempdir()?;
let file_path_buf = dir.path().join("script");
let file_path = String::from(file_path_buf.to_str().unwrap());
let mut file = File::create(file_path_buf)?;
writeln!(file, "echo hello")?;
let mut cmd = Command::new("bash")
.arg(file_path)
.stdout(Stdio::inherit())
.spawn()?;
cmd.wait_with_output()
})();
println!("{:?}", result);
}
|
package com.zyb.service;
import com.zyb.entity.Class;
import com.zyb.entity.Teacher;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ClassService {
//查询所有班级信息
List<Class> getClasses();
//查询所有毕业班级信息
List<Class> getClassesGraduated();
//查询所有在读班级信息
List<Class> getClassesWithOutGraduated();
//根据班级号查询班级信息
Class getClassById(Integer classId);
//查询课程对应的没有任课老师的班级
List<Class> getClassesByCourseIdWithOutTeached(Integer courseId);
//查询课程对应的没有任课老师或者任课老师为传入的id的班级
List<Class> getClassesByCourseIdWithOutTeachedOrTId(Teacher teacher);
List<Class> getClassesByTId(Integer tId);
//模糊查询班级
List<Class> getLikeClasses(Class clazz);
//模糊查询班级信息
List<Class> likeQueryClasses(Class clazz);
//模糊查询教师授课班级信息
List<Class> likeQueryClassesByTId(@Param("clazz") Class clazz, @Param("tId")Integer tId);
//模糊查询毕业班级信息
List<Class> likeQueryClassesGraduated(Class clazz);
//模糊查询在读班级信息
List<Class> likeQueryClassesWithOutGraduated(Class clazz);
//获取没有班主任管理的班级
List<Class> getClassesWithOutMainTeacher();
//获取班主任管理的班级
Class getClassByMainTId(Integer tId);
//检查班级号是否重复
boolean checkClassNo(String classNo);
//检查班级名是否重复
boolean checkClassName(String className);
//(点击修改按钮)更新班级信息
int updateClassById(Class CLASS);
//班级增加一个学生(学生数加一)
int updateClassAddOneStu(Integer classId);
//班级减少一个学生(学生数减一)
int updateClassDeleteOneStu(Integer classId);
//使单个班级毕业
int updateClassGraduatedByClassId(Integer classId);
//使多个班级毕业
int updateClassesGraduatedByClassIds(List<Integer> classIds);
//增加班级
int addClass(Class CLASS);
//删除一个班级(点击删除按钮)
int deleteClassById(int classId);
// 批量删除多个班级
int deleteBatchByClassIds(List<Integer> ids);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AOC.Year2019
{
public class Simulator
{
private readonly Dictionary<int, Instruction> _instructions;
public Simulator(Dictionary<int, Instruction> instructions)
{
_instructions = instructions;
}
public void Execute(int[] data)
{
var ip = 0;
while (true)
{
var i = data[ip];
if (_instructions.TryGetValue(i, out var instruction))
{
var done = instruction.Action(data, data.Skip(ip + 1).Take(instruction.ArgumentCount).ToArray());
ip += 1 + instruction.ArgumentCount;
if (done)
{
return;
}
}
else
{
throw new NotImplementedException($"Opcode {i} is not implemented");
}
}
}
}
public class Instruction
{
public int ArgumentCount { get; }
public Func<int[], int[], bool> Action { get; }
public Instruction(int argumentCount, Func<int[], int[], bool> action)
{
ArgumentCount = argumentCount;
Action = action;
}
}
}
|
# 2020 Tommaso Ciussani and Giacomo Giuliari
"""
This class defines the abstraction for a strategy, passed to a phase to define a specific computation step.
This class is open for custom extension, in order to create different execution strategies for specific steps.
The methods name() and param_description() are used by the phase to manage naming.
The compute() method, contains the computation logic, and must be specified according to the task.
For extension examples, see the subdirectories. Every subdirectory contains strategies for a different task, and must
have a level 2 base class specifying the constructor and compute arguments and returns for the task. All __init__()
overrides must call the superclass init and must specify **kwargs in the parameters, to enable the configuration
mechanism (see configuration.py in the main directory).
"""
from abc import ABC, abstractmethod
from typing import Any
class BaseStrat(ABC):
def __init__(self, **kwargs):
pass
# Methods to override
@property
def name(self) -> str:
raise NotImplementedError
@property
def param_description(self) -> str:
raise NotImplementedError
@abstractmethod
def compute(self, *args) -> Any:
raise NotImplementedError
# No override
@property
def description(self) -> str:
conf_desc = "-"
if self.param_description is not None:
conf_desc = f"-{self.param_description}-"
return f"{self.name}{conf_desc}"
|
module Watir
class TableRow < HTMLElement
include CellContainer
include Enumerable
#
# Yields each TableCell associated with this row.
#
# @example
# row = browser.tr
# row.each do |cell|
# puts cell.text
# end
#
# @yieldparam [Watir::TableCell] element Iterate through the cells for this row.
#
def each(&block)
cells.each(&block)
end
#
# Get the n'th cell (<th> or <td>) of this row
#
# @return Watir::Cell
#
def [](idx)
cell(index: idx)
end
end # TableRow
end # Watir
|
#!/usr/bin/env sh
# UnicodeData.txt
#
# codepoint character-name general-catagory
# canonical-combining-classes bidirectional-category
# character-decomposition-mapping decimal-digit-value
# digit-value numeric-value mirrored unicode10name
# iso10646-comment-field uppercase-mapping lowercase-mapping
# titlecase-mapping
#generate-module \
# --mod-name='GeneralCatagory' --cat='Ll,Lu,Lo,Nd,Lm,Mn,Mc' \
# --cat-field=2 UnicodeData.txt
#generate-module \
# --mod-name='Bidi' --cat='L,R,AL,AN,EN,ES,CS,ET,ON,BN,NSM' \
# --table -cat-field=4 \
# --fields=codepoint,,general-catagory,,bidirectional-category \
# UnicodeData.txt
#generate-module \
# --mod-name='Controls' --cat='Cc' -cat-field=2 UnicodeData.txt
#generate-module \
# --mod-name='Controls' --cat='Cc' \
# --fields=codepoint,character-name,general-catagory \
# --cat-field=2 --table UnicodeData.txt
#generate-module \
# --mod-name='Controls' --cat='Cc' UCD
#generate-module \
# --mod-name='JoinControl' --cat='Join_Control' \
# --fields='codepoint,property' PropList.txt
#generate-module \
# --mod-name='OldHangulJamo' --cat=V,T,L \
# --fields=codepoint,property HangulSyllableType.txt
#generate-module \
# --mod-name='Unassigned' --cat='Cn' \
# --fields=codepoint,property extracted/DerivedGeneralCategory.txt
generate-module \
--mod-name='NonCharCodepoint' --cat='Noncharacter_Code_Point' \
--fields='codepoint,property' PropList.txt
#generate-module \
# --mod-name='Bidi1stChar' --cat=L,R,AL \
# --fields=codepoint,property extracted/DerivedBidiClass.txt
|
---
title: Knowledge Base
---
!!!note
[Submit a ticket if your question is not listed here](https://github.com/awslabs/scale-out-computing-on-aws/issues)
###Job & Scheduler
- [JS1) I submitted a job but the job stays in the Q state](../troubleshooting/troubleshoot-job-queue)
## Virtual Desktops
- [DCV1) I cannot access my Linux/Windows DCV session](../troubleshooting/troubleshoot-dcv)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import argparse
from DBGater.db_singleton_mongo import SynDevAdmin
__author__ = 'Ziqin (Shaun) Rong'
__maintainer__ = 'Ziqin (Shaun) Rong'
__email__ = '[email protected]'
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-c", type=str, help="collection name where the flag is added")
args = parser.parse_args()
db = SynDevAdmin.db_access()
db.connect()
col = db.collection(args.c)
for doc in col.find():
if 'Crawled' not in doc.keys() or doc['Crawled']:
col.update({'_id': doc['_id']}, {'$set': {'Crawled': False}})
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.Commons;
namespace Charlotte
{
public class Test0001
{
public void Test01()
{
for (int c = 0; c < 1000; c++) // テスト回数
{
Test01_a();
}
}
private void Test01_a()
{
for (int c = 1; c <= 26; c++)
{
Test01_a2(c);
}
}
private int AskedCountMax;
private void Test01_a2(int len)
{
Console.WriteLine("len: " + len);
int[] sq = Enumerable.Range(0, len).ToArray();
SCommon.CRandom.Shuffle(sq);
Contest0001 contest = new Contest0001()
{
N = sq.Length,
P_Ask = (a, b) =>
{
if (a == b)
throw null; // never
return SCommon.Comp(
SCommon.IndexOf(sq, v => v == a),
SCommon.IndexOf(sq, v => v == b)
);
},
};
contest.Perform();
if (SCommon.Comp(sq, contest.Ans, SCommon.Comp) != 0)
throw null; // 不正解
AskedCountMax = Math.Max(AskedCountMax, contest.AskedCount);
Console.WriteLine("OK " + AskedCountMax + " " + contest.AskedCount);
}
}
}
|
import 'package:example/models/event.dart';
import 'package:flutter/material.dart';
import 'package:simple_timetable/simple_timetable.dart';
import 'package:dart_date/dart_date.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Simple timetable',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
darkTheme: ThemeData.dark(),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DateTime _month = DateTime.now();
DateTime _initDate = DateTime.now();
int visibleRange = 7;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_month != null
? '${_month.year}-${_month.month}-${_month.day}'
: ''),
actions: [],
),
body: Column(
children: [
Container(
color: Colors.grey[300],
child: Row(
children: [
SizedBox(width: 24),
ElevatedButton(
child: Text('Change visible range'),
onPressed: () {
setState(() {
visibleRange = visibleRange == 7 ? 3 : 7;
});
},
),
SizedBox(width: 24),
ElevatedButton(
child: Text('Change initial date '),
onPressed: () {
setState(() {
_initDate = DateTime.now().addMonths(1);
});
},
),
SizedBox(width: 24),
],
),
),
SizedBox(height: 24),
Expanded(
child: SimpleTimetable<TimeTableEvent>(
onChange: (
List<DateTime> current,
TimetableDirection dir,
) {
print('On change date: ${current[0]}');
print('On change direction: $dir');
print('On change columns $current');
setState(() {
_month = current[0];
});
},
initialDate: _initDate,
dayStart: 8,
dayEnd: 24,
visibleRange: visibleRange,
events: eventsList,
buildCard: (event, isPast) {
return GestureDetector(
onTap: () {
print(event.payload.data.title);
},
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(4),
color: isPast
? Colors.grey[400]
: Colors.blue[200].withOpacity(0.5),
),
child: Column(
children: [
Text(
'${event.payload.data.title}',
style: TextStyle(fontSize: 10),
),
Text(
'${event.start.format('hh:mm')}\n${event.end.format('hh:mm')}',
style: TextStyle(fontSize: 10),
),
Text(
'isPast: $isPast',
style: TextStyle(fontSize: 10),
)
],
),
),
);
},
),
),
],
),
);
}
}
List<Event<TimeTableEvent>> eventsList = [
Event<TimeTableEvent>(
id: UniqueKey().toString(),
start: DateTime.now().startOfDay.add(Duration(hours: 9)),
end: DateTime.now().startOfDay.add(Duration(hours: 10)),
date: DateTime.now().startOfDay,
payload: TimeTableEvent(
data: EventPayload(title: 'Event 1'),
),
),
Event<TimeTableEvent>(
id: UniqueKey().toString(),
start: DateTime.now().startOfDay.add(Duration(hours: 12)),
end: DateTime.now().startOfDay.add(Duration(hours: 13, minutes: 45)),
date: DateTime.now().startOfDay,
payload: TimeTableEvent(
data: EventPayload(title: 'Event 2'),
),
),
Event<TimeTableEvent>(
id: UniqueKey().toString(),
start: DateTime.now().startOfDay.add(Duration(hours: 11)),
end: DateTime.now().startOfDay.add(Duration(hours: 12, minutes: 18)),
date: DateTime.now().startOfDay,
payload: TimeTableEvent(
data: EventPayload(title: 'Event 3'),
),
),
Event<TimeTableEvent>(
id: UniqueKey().toString(),
start: DateTime.now().startOfDay.add(Duration(hours: 15)),
end: DateTime.now().startOfDay.add(Duration(hours: 16, minutes: 30)),
date: DateTime.now().startOfDay,
payload: TimeTableEvent(
data: EventPayload(title: 'Event 3'),
),
),
Event<TimeTableEvent>(
id: UniqueKey().toString(),
start: DateTime.now().startOfDay.add(
Duration(
days: 1,
hours: 9,
),
),
end: DateTime.now().startOfDay.add(
Duration(
days: 1,
hours: 10,
minutes: 15,
),
),
date: DateTime.now().startOfDay.add(Duration(days: 1)),
payload: TimeTableEvent(
data: EventPayload(title: 'Event 4'),
),
),
Event<TimeTableEvent>(
id: UniqueKey().toString(),
start: DateTime.now().startOfDay.add(
Duration(
days: 1,
hours: 9,
),
),
end: DateTime.now().startOfDay.add(
Duration(
days: 1,
hours: 10,
minutes: 15,
),
),
date: DateTime.now().startOfDay.add(Duration(days: 1)),
payload: TimeTableEvent(
data: EventPayload(title: 'Event 5'),
),
),
Event<TimeTableEvent>(
id: UniqueKey().toString(),
start: DateTime.now().startOfDay.add(
Duration(
days: 2,
hours: 10,
),
),
end: DateTime.now().startOfDay.add(
Duration(
days: 2,
hours: 11,
minutes: 30,
),
),
date: DateTime.now().startOfDay.add(Duration(days: 2)),
payload: TimeTableEvent(
data: EventPayload(title: 'Event 6'),
),
),
];
|
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_teaslate/flutter_teaslate.dart';
String API_KEY = "type_your_api_key_here";
void main() {
print("Starting tests unit");
test('can connect to API', () {
String goodKey = API_KEY;
String badKey = "wrong";
TeaSlate teaslate =
TeaSlate(key: badKey, debug: true, ignoreCertErrors: true);
expect(
teaslate.connect().then((bool connected) => expect(connected, false)),
completes);
TeaSlate teaslate_2 =
TeaSlate(key: goodKey, debug: true, ignoreCertErrors: true);
expect(
teaslate_2.connect().then((bool connected) => expect(connected, true)),
completes);
});
test('can retrieve a specific translation', () {
String translation = "whatIsYourName";
TeaSlate teaslate =
TeaSlate(key: API_KEY, debug: true, ignoreCertErrors: true);
expect(
teaslate.connect().then((bool connected) {
if (connected) {
expect(teaslate.translate(translation, lang: "en"),
"What is your name?");
expect(teaslate.translate(translation, lang: "fr"),
"Quel est votre nom ?");
expect(teaslate.translate(translation, lang: "hu"),
"What is your name?",
reason: "not found translation returns the first one");
} else {
fail("wasn't able to connect API");
}
}),
completes);
});
test('can retrieve a default translation', () {
String translation = "whatIsYourName";
TeaSlate teaslate = TeaSlate(
key: API_KEY, defaultLang: "en", debug: true, ignoreCertErrors: true);
expect(
teaslate.connect().then((bool connected) {
if (connected) {
expect(teaslate.translate(translation), "What is your name?");
expect(teaslate.translate(translation, lang: "fr"),
"Quel est votre nom ?",
reason: "the translation force did not work");
} else {
fail("wasn't able to connect API");
}
}),
completes);
});
print("Ending test units");
}
|
import React, { useState, useMemo, useEffect } from 'react';
import { toast } from 'react-toastify';
import { useLazyQuery, useMutation } from '@apollo/react-hooks';
import { SINGLE_POST } from '../../graphql/queries';
import { POST_UPDATE } from '../../graphql/mutations';
import omitDeep from 'omit-deep';
import { useParams } from 'react-router-dom';
import FileUpload from '../../components/FileUpload';
const PostUpdate = () => {
const [values, setValues] = useState({
content: '',
image: {
url: '',
public_id: ''
}
});
const [getSinglePost, { data: singlePost }] = useLazyQuery(SINGLE_POST);
const [postUpdate] = useMutation(POST_UPDATE);
const [loading, setLoading] = useState(false);
// router
const { postid } = useParams();
// destructure
const { content, image } = values;
useMemo(() => {
if (singlePost) {
setValues({
...values,
_id: singlePost.singlePost._id,
content: singlePost.singlePost.content,
image: omitDeep(singlePost.singlePost.image, ['__typename'])
});
}
}, [singlePost]);
useEffect(() => {
console.log(postid);
getSinglePost({ variables: { postId: postid } });
}, []);
const handleChange = (e) => {
setValues({ ...values, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
setLoading(true);
postUpdate({ variables: { input: values } });
setLoading(false);
toast.success('Post Updated');
};
const updateForm = () => (
<form onSubmit={handleSubmit}>
<div className="form-group">
<textarea
value={content}
onChange={handleChange}
name="content"
rows="5"
className="md-textarea form-control"
placeholder="Write something cool"
maxLength="150"
disabled={loading}
></textarea>
</div>
<button className="btn btn-primary" type="submit" disabled={loading || !content}>
Post
</button>
</form>
);
return (
<div className="container p-5">
{loading ? <h4 className="text-danger">Loading...</h4> : <h4>Update</h4>}
<FileUpload
values={values}
loading={loading}
setValues={setValues}
setLoading={setLoading}
singleUpload={true}
/>
{updateForm()}
</div>
);
};
export default PostUpdate;
|
require File.dirname(__FILE__) + '/rails/test/lib/key_structure.rb'
require File.dirname(__FILE__) + '/rails/test/lib/normalize.rb'
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/lib') unless $LOAD_PATH.include?(File.dirname(__FILE__) + '/lib')
class Locales < Thor
desc 'test_all', 'Check formality of all locale files.'
def test_all
Dir.glob(File.dirname(__FILE__) + '/rails/locale/*.{rb,yml}') do |filename|
if md = filename.match(/([\w\-]+)\.(rb|yml)$/)
locale = md[1]
missing_keys, broken_keys, missing_pluralizations = KeyStructure.check(locale)
unless missing_keys.empty?
puts "[#{locale}] Some keys are missing."
end
unless broken_keys.empty?
puts "[#{locale}] Some keys have broken data."
end
unless missing_pluralizations.empty?
puts "[#{locale}] Some keys have missing pluralizations."
end
end
end
end
desc 'test LOCALE', 'Check formality of a locale file.'
def test(locale)
good = true
missing_keys, broken_keys, missing_pluralizations = KeyStructure.check(locale)
unless missing_keys.empty?
puts "The following keys are missing."
missing_keys.each do |key|
puts " " + key
end
good = false
end
unless broken_keys.empty?
puts "The following keys have broken data."
broken_keys.uniq.each do |key|
puts " " + key
end
good = false
end
unless missing_pluralizations.empty?
puts "The following keys have missing pluralizations."
missing_pluralizations.uniq.each do |key|
puts " " + key
end
good = false
end
puts "The structure is good." if good
end
desc 'normalize LOCALE', 'Normalize locale file.'
def normalize(locale)
Dir.glob(format('%s/rails/locale/%s.{rb,yml}', File.dirname(__FILE__), locale)) do |filename|
h = YAML.load_file(filename)
File.write(filename, Normalize.deep_sort(h).to_yaml)
end
end
desc 'normalize_all', 'Normalize all locale files.'
def normalize_all
Dir.glob(format('%s/rails/locale/*.{rb,yml}', File.dirname(__FILE__))) do |filename|
h = YAML.load_file(filename)
File.write(filename, Normalize.deep_sort(h).to_yaml)
end
end
desc 'list', 'List locale names.'
def list
locales = []
Dir.glob(File.dirname(__FILE__) + '/rails/locale/*.{rb,yml}') do |filename|
if md = filename.match(/([\w\-]+)\.(rb|yml)$/)
locales << md[1]
end
end
puts locales.sort.join(', ')
end
desc 'complete', 'List complete locales'
def complete
locales = []
Dir.glob(File.dirname(__FILE__) + '/rails/locale/*.{rb,yml}') do |filename|
if md = filename.match(/([\w\-]+)\.(rb|yml)$/)
locale = md[1]
missing_keys, broken_keys, missing_pluralizations = KeyStructure.check(locale)
if missing_keys.empty? && broken_keys.empty? && missing_pluralizations.empty?
locales << locale
end
end
end
puts locales.sort.join(', ')
end
desc 'incomplete', 'List incomplete locales'
def incomplete
locales = []
Dir.glob(File.dirname(__FILE__) + '/rails/locale/*.{rb,yml}') do |filename|
if md = filename.match(/([\w\-]+)\.(rb|yml)$/)
locale = md[1]
missing_keys, broken_keys, missing_pluralizations = KeyStructure.check(locale)
unless missing_keys.empty? && broken_keys.empty? && missing_pluralizations.empty?
locales << locale
end
end
end
puts locales.sort.join(', ')
end
end
|
require 'test_helper'
class AbstractControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = 'Ruby on Rails Tutorial Sample App'
end
end
|
# frozen_string_literal: true
module Gitlab
module AlertManagement
# Represents counts of each status or category of statuses
class AlertStatusCounts
include Gitlab::Utils::StrongMemoize
STATUSES = ::AlertManagement::Alert::STATUSES
attr_reader :project
def self.declarative_policy_class
'AlertManagement::AlertPolicy'
end
def initialize(current_user, project, params)
@project = project
@current_user = current_user
@params = params
end
# Define method for each status
STATUSES.each_key do |status|
define_method(status) { counts[status] }
end
def open
counts[:triggered] + counts[:acknowledged]
end
def all
counts.values.sum # rubocop:disable CodeReuse/ActiveRecord
end
private
attr_reader :current_user, :params
def counts
strong_memoize(:counts) do
Hash.new(0).merge(counts_by_status)
end
end
def counts_by_status
::AlertManagement::AlertsFinder
.counts_by_status(current_user, project, params)
.transform_keys { |status_id| STATUSES.key(status_id) }
end
end
end
end
|
-- | Defines the endpoints listed in the
-- <http://developer.oanda.com/rest-live-v20/account-ep/ Account> section of the
-- API.
module OANDA.Accounts
( AccountProperties (..)
, oandaAccounts
, AccountsResponse (..)
, oandaAccountDetails
, AccountDetailsResponse (..)
, oandaAccountChanges
, AccountChangesResponse (..)
, AccountChanges (..)
, AccountChangesState (..)
, Account (..)
, Position (..)
, PositionSide (..)
) where
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Vector as V
import OANDA.Instrument
import OANDA.Internal
import OANDA.Orders
import OANDA.Transactions
-- | Wraps the JSON response for accounts
data AccountProperties = AccountProperties
{ accountPropertiesId :: AccountID
, accountPropertiesMt4AccountID :: Maybe Text
, accountPropertiesTags :: [Text]
} deriving (Show)
deriveJSON (unPrefix "accountProperties") ''AccountProperties
oandaAccounts :: OandaEnv -> OANDARequest AccountsResponse
oandaAccounts env = OANDARequest $ baseApiRequest env "GET" "/v3/accounts"
data AccountsResponse
= AccountsResponse
{ accountsResponseAccounts :: V.Vector AccountProperties
} deriving (Show)
deriveJSON (unPrefix "accountsResponse") ''AccountsResponse
data PositionSide =
PositionSide
{ positionSideUnits :: Decimal
, positionSideAveragePrice :: Maybe PriceValue
, positionSideTradeIDs :: Maybe [TradeID]
, positionSidePl :: AccountUnits
, positionSideUnrealizedPL :: Maybe AccountUnits
, positionSideResettablePL :: Maybe AccountUnits
} deriving (Show)
deriveJSON (unPrefix "positionSide") ''PositionSide
data Position =
Position
{ positionInstrument :: InstrumentName
, positionPl :: AccountUnits
, positionUnrealizedPL :: Maybe AccountUnits
, positionResettablePL :: Maybe AccountUnits
, positionLong :: PositionSide
, positionShort :: PositionSide
} deriving (Show)
deriveJSON (unPrefix "position") ''Position
data Account =
Account
{ accountId :: AccountID
, accountAlias :: Text
, accountCurrency :: Currency
, accountBalance :: AccountUnits
, accountCreatedByUserID :: Integer
, accountCreatedTime :: OandaZonedTime
, accountPl :: AccountUnits
, accountResettablePL :: AccountUnits
, accountResettablePLTime :: Maybe OandaZonedTime
, accountMarginRate :: Decimal
, accountMarginCallEnterTime :: Maybe OandaZonedTime
, accountMarginCallExtensionCount :: Maybe Integer
, accountLastMarginCallExtensionTime :: Maybe OandaZonedTime
, accountOpenTradeCount :: Integer
, accountOpenPositionCount :: Integer
, accountPendingOrderCount :: Integer
, accountHedgingEnabled :: Bool
, accountUnrealizedPL :: AccountUnits
-- TODO: accountNAV :: AccountUnits
, accountMarginUsed :: AccountUnits
, accountMarginAvailable :: AccountUnits
, accountPositionValue :: AccountUnits
, accountMarginCloseoutUnrealizedPL :: AccountUnits
, accountMarginCloseoutNAV :: AccountUnits
, accountMarginCloseoutMarginUsed :: AccountUnits
, accountMarginCloseoutPercent :: Decimal
, accountWithdrawalLimit :: AccountUnits
, accountMarginCallMarginUsed :: AccountUnits
, accountMarginCallPercent :: Decimal
, accountLastTransactionID :: TransactionID
-- TODO: accountTrades :: [TradeSummary]
, accountPositions :: [Position]
, accountOrders :: [Order]
} deriving (Show)
deriveJSON (unPrefix "account") ''Account
data AccountDetailsResponse =
AccountDetailsResponse
{ accountDetailsResponseAccount :: Account
, accountDetailsResponseLastTransactionID :: TransactionID
} deriving (Show)
deriveJSON (unPrefix "accountDetailsResponse") ''AccountDetailsResponse
oandaAccountDetails :: OandaEnv -> AccountID -> OANDARequest AccountDetailsResponse
oandaAccountDetails env (AccountID accountId) = OANDARequest request
where
request =
baseApiRequest env "GET" ("/v3/accounts/" ++ accountId)
data AccountChanges =
AccountChanges
{ accountChangesOrdersCreated :: [Order]
, accountChangesOrdersCancelled :: [Order]
, accountChangesOrdersFilled :: [Order]
, accountChangesOrdersTriggered :: [Order]
-- TODO: accountChangesTradesOpened :: [TradeSummary]
-- TODO: accountChangesTradesReduced :: [TradeSummary]
-- TODO: accountChangesTradesClosed :: [TradeSummary]
, accountChangesPositions :: [Position]
, accountChangesTransactions :: [Transaction]
} deriving (Show)
deriveJSON (unPrefix "accountChanges") ''AccountChanges
data AccountChangesState =
AccountChangesState
{ accountChangesStateUnrealizedPL :: AccountUnits
-- TODO: accountChangesStateNAV :: AccountUnits
, accountChangesStateMarginUsed :: AccountUnits
, accountChangesStateMarginAvailable :: AccountUnits
, accountChangesStatePositionValue :: AccountUnits
, accountChangesStateMarginCloseoutUnrealizedPL :: Maybe AccountUnits
, accountChangesStateMarginCloseoutNAV :: Maybe AccountUnits
, accountChangesStateMarginCloseoutMarginUsed :: Maybe AccountUnits
, accountChangesStateMarginCloseoutPercent :: Maybe Decimal
, accountChangesStateMarginCloseoutPositionValue :: Maybe Decimal
, accountChangesStateWithdrawalLimit :: AccountUnits
, accountChangesStateMarginCallMarginUsed :: AccountUnits
, accountChangesStateMarginCallPercent :: Decimal
-- TODO: accountChangesStateOrders :: [DynamicOrderState]
-- TODO: accountChangesStateTrades :: [CalculatedTradeState]
-- TODO: accountChangesStatePositions :: [CalculatedPositionState]
} deriving (Show)
deriveJSON (unPrefix "accountChangesState") ''AccountChangesState
data AccountChangesResponse =
AccountChangesResponse
{ accountChangesResponseChanges :: AccountChanges
, accountChangesResponseState :: AccountChangesState
, accountChangesResponseLastTransactionID :: TransactionID
} deriving (Show)
deriveJSON (unPrefix "accountChangesResponse") ''AccountChangesResponse
oandaAccountChanges :: OandaEnv -> AccountID -> TransactionID -> OANDARequest AccountChangesResponse
oandaAccountChanges env (AccountID accountId) (TransactionID sinceId) = OANDARequest request
where
request =
baseApiRequest env "GET" ("/v3/accounts/" ++ accountId ++ "/changes")
& setRequestQueryString params
params = [("sinceTransactionID", Just (BS8.pack $ show sinceId))]
-- TODO:
-- GET /v3/accounts/{AccoundId}/summary
-- GET /v3/accounts/{AccoundId}/instruments
-- PATCH /v3/accounts/{AccoundId}/configuration
|
class Comment
module Subscribing
extend ActiveSupport::Concern
included do
after_create :subscribe_user
after_commit :notify_subscribers_later, on: :create
end
def notify_subscribers_later
CommentSubscriptionWorker.perform_async id
end
def notify_subscribers
subscriptions_to_notify.each do |subscription|
Notification.create({
source: self,
user_id: subscription.user.id,
message: "#{ user.display_name } commented on #{ discussion.title }",
url: FrontEnd.link_to(self),
section: section,
subscription: subscription
}) if subscription.try(:enabled?)
end
end
def subscriptions_to_notify
list = discussion.subscriptions.participating_discussions.enabled.where 'user_id <> ?', user.id
list += discussion.subscriptions.followed_discussions.enabled.where 'user_id <> ?', user.id
list.uniq{ |subscription| subscription.user_id }
end
def subscribe_user
user.subscribe_to discussion, :participating_discussions
end
end
end
|
class SiteImage < ApplicationRecord
include Maawol::Models::Concerns::TmpUploadable
before_create :generate_slug
mount_uploader :image, SiteImageUploader
after_save :perform_migrate_tmp_file_job, if: -> { self.image_tmp_media_id.present? }
def fields_for_upload
[:image]
end
def perform_migrate_tmp_file_job
MigrateTmpMediaFileJob.set(wait: 5.seconds).perform_later(self)
end
def generate_slug
self.slug = self.name.downcase.underscore if self.slug.nil?
end
def self.email_banner_url
find_by(slug: 'email-banner').image.url(:large_landscape)
end
end |
import boto3
from m3d.util.aws_credentials import AWSCredentials
class Boto3Util(object):
@staticmethod
def create_s3_resource(
aws_credentials=None
):
"""
Initialize and return boto3 resource for S3.
:param aws_credentials: AWS credentials. Empty values will be used if it is None.
:return: initialized boto3 resource object for S3
"""
if not aws_credentials:
aws_credentials = AWSCredentials("", "")
s3_resource = boto3.resource(
"s3",
aws_access_key_id=aws_credentials.access_key_id,
aws_secret_access_key=aws_credentials.secret_access_key
)
return s3_resource
@staticmethod
def create_emr_client(
aws_region,
aws_credentials=None
):
"""
Initialize and return boto3 client for EMR.
:param aws_region: AWS region
:param aws_credentials: AWS credentials. Empty values will be used if it is None.
:return: initialized boto3 client object for EMR
"""
if not aws_credentials:
aws_credentials = AWSCredentials("", "")
emr_client = boto3.client(
'emr',
region_name=aws_region,
aws_access_key_id=aws_credentials.access_key_id,
aws_secret_access_key=aws_credentials.secret_access_key
)
return emr_client
|
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Hamster.States {
// State for asking how the user wants to sign in -
// Through an auth provider, creating an account, or
// doing an anonymous signin for later.
class ChooseSignInMenu : BaseState {
Firebase.Auth.FirebaseAuth auth;
Menus.ChooseSignInGUI dialogComponent;
public override StateExitValue Cleanup() {
DestroyUI();
return new StateExitValue(typeof(ChooseSignInMenu), null);
}
public override void Resume(StateExitValue results) {
ShowUI();
// SignInResult is used with a email/password, while WaitForTask.Results
// is used when signing in with an anonymous account.
SignInResult result = results.data as SignInResult;
WaitForTask.Results taskResult = results.data as WaitForTask.Results;
if ((result != null && !result.Canceled) ||
(taskResult != null && !taskResult.task.IsCanceled)) {
if (auth.CurrentUser != null) {
CommonData.isNotSignedIn = false;
manager.PopState();
} else {
manager.PushState(new BasicDialog(
Utilities.StringHelper.SigninInFailureString(taskResult.task)));
}
}
}
public override void Suspend() {
HideUI();
}
// Initialization method. Called after the state
// is added to the stack.
public override void Initialize() {
auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
dialogComponent = SpawnUI<Menus.ChooseSignInGUI>(StringConstants.PrefabsChooseSigninMenu);
dialogComponent.GooglePlaySignIn.gameObject.SetActive(
GooglePlayServicesSignIn.GooglePlayServicesEnabled());
InitializeGameCenterUI();
}
private void InitializeGameCenterUI() {
// Determine whether we should show the button, and whether GameCenter is enabled.
// Note that these values may differ (for example, we should show the button in the Editor on
// MacOS to help with debugging and development, but gameCenter doesn't work on that platform,
// so we don't want to allow the button to be clicked)
bool showGameCenter = GameCenterSignIn.ShouldShowGameCenterSignIn();
bool gameCenterEnabled = GameCenterSignIn.IsGameCenterEnabled();
dialogComponent.GameCenterSignIn.gameObject.SetActive(showGameCenter);
SetButtonActive(dialogComponent.GameCenterSignIn, false);
if(gameCenterEnabled) {
Action updateButtonBasedOnSignedInState = () => {
bool gameCenterSignedIn = Firebase.Auth.GameCenterAuthProvider.IsPlayerAuthenticated();
SetButtonActive(dialogComponent.GameCenterSignIn, gameCenterSignedIn);
};
GameCenterSignIn.InitializeGameCenterAuthentication(updateButtonBasedOnSignedInState);
}
}
private void SetButtonActive(Hamster.Menus.GUIButton button, bool newActive) {
button.enabled = newActive;
var buttonText = button.GetComponentInChildren<UnityEngine.UI.Text>();
if(buttonText != null) {
float newAlpha = (newActive ? 1.0f : 0.3f);
Color newColor = buttonText.color;
newColor.a = newAlpha;
buttonText.color = newColor;
}
}
public override void HandleUIEvent(GameObject source, object eventData) {
if (source == dialogComponent.CreateAccountButton.gameObject) {
manager.PushState(new CreateAccount());
} else if (source == dialogComponent.SignInButton.gameObject) {
manager.PushState(new SignInWithEmail());
} else if (source == dialogComponent.AnonymousSignIn.gameObject) {
manager.PushState(
new WaitForTask(auth.SignInAnonymouslyAsync().ContinueWith(t => {
SignInState.SetState(SignInState.State.Anonymous);}),
StringConstants.LabelSigningIn, true));
} else if (source == dialogComponent.DontSignIn.gameObject) {
CommonData.isNotSignedIn = true;
manager.PopState();
} else if (source == dialogComponent.GooglePlaySignIn.gameObject) {
manager.PushState(
new WaitForTask(GooglePlayServicesSignIn.SignIn(),
StringConstants.LabelSigningIn, true));
} else if (source == dialogComponent.GameCenterSignIn.gameObject) {
manager.PushState(
new WaitForTask(GameCenterSignIn.SignIn(),
StringConstants.LabelSigningIn, true));
}
}
}
public class SignInResult {
public bool Canceled = false;
public SignInResult(bool canceled) {
this.Canceled = canceled;
}
}
}
|
import mongoose from 'mongoose';
export const TestModel = mongoose.model(
'TestModel',
new mongoose.Schema({
name: String,
}),
);
|
require 'case'
class IndexPageTest < Case
def setup
get '/'
end
def test_it_should_redirect_to_the_last_post
assert_equal 302, status
end
def test_it_shoud_redirect_to_an_existing_page
follow_redirect!
assert_equal 200, status, "Index page should respond"
assert_match %r{text/html}, content_type, "Index should be text/html"
assert last_response['Cache-Control'] != nil
assert last_response['Last-Modified'] != nil
end
def test_stylesheets_should_respond
follow_redirect!
body.scan %r{<link.*?href="(.*?)"} do |match|
head (css = match.first)
next unless internal?(css)
assert_equal 200, status, "Stylesheet #{css} should respond"
assert_match %r{text/css}, content_type, "Stylesheet #{css} should be text/css"
end
end
def test_javascripts_should_respond
follow_redirect!
body.scan %r{<script.*src="(.*?)"} do |match|
head (js = match.first)
next unless internal?(js)
assert_equal 200, status, "Script #{js} should respond"
assert_match %r{application/javascript}, content_type, "Javascript #{js} should be application/javascript"
end
end
end
|
import React from 'react';
import Page from '../../components/Page';
import { DataProviders } from '@burner-wallet/ui-core';
const { PluginElements } = DataProviders;
const AdvancedPage: React.FC = () => {
return (
<Page title="Advanced">
<PluginElements position='advanced' />
</Page>
);
};
export default AdvancedPage;
|
# Тестовое задание
## Окружение для разработки
### Требования
- Vagrant
- VirtualBox
### Запуск
Чтоб запустить контейнер с настроенным окружением, необходимо
запустить команду `vagrant up`.
При первом запуске, скачается образ системы и установятся необходимые пакеты.
Затем команда будет запускать настроенную систему.
### Данные
#### HTTP
Адрес сервера: [http://192.168.33.10](http://192.168.33.10)
#### MySQL
- Сервер: `localhost`
- Пользователь: `vagrant`
- База данных: `vagrant`
- Пароль: `secret`
#### Путь к файлам сайта
Сайт находится в `/home/ubuntu/site/`
## Миграции
Чтоб запустить миграцию, необходимо запустить команду
`php index.php migrate`
### Vagrant
Для начала нужно подключится к виртуальной машине по ssh,
выполнив команду `vagrant ssh`.
Для запуска миграции в Vagrant, необходимо перед запуском комады
объявить переменную окружения `CI_ENV` со значением `development-vagrant`.
Например `export CI_ENV=development-vagrant; php index.php migrate` |
#include <stdio.h>
#define SIZE 16
void toBin(int num)
{
for (int k = SIZE; k > 0; --k) {
if ((num>>k)&1) printf("x^%d+",k);
}
printf("1\n");
}
int power(int base, int power)
{
int ret = 1;
for (int i = 0; i < power; ++i)
ret = ret * base;
return ret;
}
int mul(int m, int n)
{
int num1 = m;
int num2 =n;
int ret = 0;
for (int i = 0; i < SIZE; ++i) {
if (num2&1) ret = ret^num1;
if (num2 == 0 ) break;
num1 <<= 1;
num2 >>= 1;
}
return ret;
}
int isValid(int num) // Will check if the polynominal has 1 as a solution.
{
if (num&1) return 0;
int sum = 0;
for (int k = 1; k < SIZE; ++k) {
if (num & 1)
sum += 1;
num >>= 1;
}
if (sum&1)
return 0;
else
return 1;
}
int main(void)
{
int len = power(2,SIZE+1);
char Arr[len];
for (int i = 1; i < len; ++i) {
Arr[i] = 1;
}
for (unsigned int i = 3; i < len; i++) {
if (Arr[i]==1) {
for (int k = 2; k < len; ++k) {
int value = mul(i,k);
if (value > len) {
break;
} else if (!((value&1) && isValid(value))) {
Arr[value] = 0;
}
}
}
}
for (unsigned int i = 6; i < len; ++i) {
if (Arr[i]==1) {
toBin(i);
}
}
return 0;
}
|
// https://github.com/netlify-labs/oauth-example/blob/master/src/utils/sort.js
// License MIT
export function matchText(search, text) {
if (!text || !search) {
return false
}
return text.toLowerCase().indexOf(search.toLowerCase()) > -1
}
export function sortByDate(dateType, order) {
return function (a, b) {
const timeA = new Date(a[dateType]).getTime()
const timeB = new Date(b[dateType]).getTime()
if (order === 'asc') {
return timeA - timeB
}
// default 'desc' descending order
return timeB - timeA
}
}
const oldNumber = '2012-02-25T22:21:57.581Z'
export function sortByPublishDate(order) {
return function (a, b) {
const timeOne = (!a.published_deploy) ? oldNumber : a.published_deploy.published_at
const timeTwo = (!b.published_deploy) ? oldNumber : b.published_deploy.published_at
const timeA = new Date(timeOne).getTime()
const timeB = new Date(timeTwo).getTime()
if (order === 'asc') {
return timeA - timeB
}
// default 'desc' descending order
return timeB - timeA
}
}
export function sortByName(key, order) {
return function (a, b) {
if (order === 'asc') {
if (a[key] < b[key]) return -1
if (a[key] > b[key]) return 1
}
if (a[key] > b[key]) return -1
if (a[key] < b[key]) return 1
return 0
}
}
export function sortByFunctions(order) {
return function (a, b) {
const functionsOne = (!a.published_deploy) ? [] : a.published_deploy.available_functions
const functionsTwo = (!b.published_deploy) ? [] : b.published_deploy.available_functions
if (order === 'desc') {
if (functionsOne.length < functionsTwo.length) return -1
if (functionsOne.length > functionsTwo.length) return 1
}
if (functionsOne.length > functionsTwo.length) return -1
if (functionsOne.length < functionsTwo.length) return 1
return 0
}
}
export function sortByRepo(order) {
return function (a, b) {
const settingsOne = a.build_settings || { repo_url: 'a' }
const settingsTwo = b.build_settings || { repo_url: 'a' }
if (order === 'asc') {
if (settingsOne.repo_url < settingsTwo.repo_url) return -1
if (settingsOne.repo_url > settingsTwo.repo_url) return 1
}
if (settingsOne.repo_url > settingsTwo.repo_url) return -1
if (settingsOne.repo_url < settingsTwo.repo_url) return 1
return 0
}
} |
/*
Converts array <-> number in SICStus Prolog.
toNum(List, Base, Num) converts a list of integers to a number for a
base Base. It is bidirectional but it is really recommended that
the length of List is fixed.
See examples below.
Compare with the following models:
* Comet : http://www.hakank.org/comet/toNum.co
* ECLiPSe: http://www.hakank.org/eclipse/tonum.ecl
* Essence'/Tailor: http://www.hakank.org/tailor/to_num.eprime
* Gecode: http://www.hakank.org/gecode/to_num.cpp
Model created by Hakan Kjellerstrand, [email protected]
See also my SICStus Prolog page: http://www.hakank.org/sicstus/
*/
:-use_module(library(clpfd)).
:-use_module(library(lists)).
%
% toNum/3
% toNum(-List, +Base, -Num)
%
% Converts a list of integers in base Base to a number Num, or
% vice versa.
%
% This is a bidirectional predicate, but if the length of List
% is not bounded there is an infinite solutions with 0 added
% to the head of the list for each solution.
%
% Examples:
%
% toNum([1,2,3,4], 10, Num). -> Num = 1234
%
% L is of bounded length
% length(L,3), toNum(L, 10, 123). -> L = [1,2,3]
% length(L,3), toNum(L, 10, 12). -> L = [0,1,2]
%
% another base:
% toNum([1,2,3], 12, Num). -> Num = 171
%
% L is of unbounded length:
% toNum(L, 10, 12). -> L = [1,2], L = [0,1,2], L = [0,0,1,2], ....
%
toNum(List, Base, Num) :-
length(List, Len),
length(Xs, Len),
exp_list(Len, Base, Xs), % calculate exponents
Base1 is Base-1,
domain(List, 0, Base1),
scalar_product(Xs,List, #=, Num).
%
% Defaults to Base 10
%
toNum(List, Num) :-
toNum(List, 10, Num).
%
% exp_list/3
% exp_list(+N, +Base, -ExpList)
%
% ExpList is a list of the exponents
% [Base^(N-1), Base^(N-2),...,Base^0],
%
% Example:
% exp_list(3, 10, ExpList). -> ExpList = [100,10,1]
%
exp_list(N, Base, ExpList) :-
(
for(I, 0, N-1),
fromto([], In, Out, ExpList),
param(Base)
do
B is integer(Base**I),
Out = [B|In]
).
%
% explist/2
%
% exponent list for base 10.
exp_list(N, ExpList) :-
exp_list(N, 10, ExpList).
%
% Tests
%
go :-
length(A, 4),
toNum(A, 10, 1234),
write(a:A),nl,
B = [3,1,4,1,5,9],
toNum(B, 10, Num),
write(num:Num),nl,
N = 2,
length(C, N),
% labeling of the list in the goal is needed
format('base 11 with ~d digits',N),nl,
findall([Num2, C], (toNum(C, 11, Num2), labeling([ff],C)), L),
length(L, Len),
write([Len, L]),nl.
% % this non-CP (and unidirectional) version also works
go2 :-
Xs = [3,2,1,0], % len-1 .. 0
Ys = [2,0,1,2],
(foreach(X, Xs),
foreach(Y, Ys),
foreach(Z, Zs)
do
Z is Y*integer(10**X)
),
sum(Zs,#=,Sum),
write([Xs, Ys, Zs, Sum]),nl.
|
BeforeAll {
. (Resolve-Path -Path "$PSScriptRoot\..\..\source\public\Add-DataSetTable.ps1")
}
Describe -Name "Add-DataSetTable.ps1" -Fixture {
BeforeAll {
$DataTable = New-Object System.Data.Datatable
$DataTable.TableName = 'TableName'
$DataSet = New-Object -TypeName System.Data.DataSet
}
Context -Name 'When calling with valid DataSet and DataTable' {
It -Name 'Should not throw' -Test {
{Add-DataSetTable -DataSet $DataSet -DataTable $DataTable} | should -not -throw
}
It -Name 'Dataset should contain datatable' -Test {
$DataSet.Tables.Contains('TableName') | should -BeTrue
}
}
Context -Name 'When calling with an invalid data table' {
It -Name 'Should throw' {
{ Add-DataSetTable -DataSet $DataSet -DataTable $null } | should -throw
}
}
Context -Name 'When calling with an invalid data set' {
It -Name 'Should throw' {
{ Add-DataSetTable -DataSet $null -DataTable $DataTable } | should -throw
}
}
}
|
// 哪些类型的变量值会随时间改变呢
package main
import (
"fmt"
"sync"
"time"
)
func main() {
fmt.Println("begin", intClosure, stringClosure, sliceClosure, mapClosure, syncMapClosure)
time.Sleep(10 * time.Second)
fmt.Println("end", intClosure, stringClosure, sliceClosure, mapClosure, syncMapClosure)
}
var intClosure = func() int {
var a int
refresh := func() {
a++
fmt.Println(time.Now(), a)
}
refresh()
go func() {
for range time.NewTicker(time.Second).C {
refresh()
}
}()
return a
}()
var stringClosure = func() string {
var str string
refresh := func() {
str += "go"
fmt.Println(time.Now(), str)
}
refresh()
go func() {
for range time.NewTicker(time.Second).C {
refresh()
}
}()
return str
}()
var sliceClosure = func() []int {
var s []int
// var s = make([]int, 20) // 长度够也不会变
var i int
refresh := func() {
i++
s = append(s, i)
fmt.Println(time.Now(), s)
}
refresh()
go func() {
for range time.NewTicker(time.Second).C {
refresh()
}
}()
return s
}()
var mapClosure = func() map[int]int {
var m = make(map[int]int)
var i int
refresh := func() {
i++
m[i] = i
fmt.Println(time.Now(), m)
}
refresh()
go func() {
for range time.NewTicker(time.Second).C {
refresh()
}
}()
return m
}()
var syncMapClosure = func() *sync.Map {
var sm = new(sync.Map)
var i int
refresh := func() {
i++
sm.Store(i, i)
fmt.Println(time.Now(), sm)
}
refresh()
go func() {
for range time.NewTicker(time.Second).C {
refresh()
}
}()
return sm
}()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.