text
stringlengths 27
775k
|
|---|
# SimpleAdminLTE
: is the AdminLTE template without example pages
# Complete AdminLTE: https://github.com/almasaeed2010/AdminLTE
|
class SessionsController < ApplicationController
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
if SharedBasket.where(user_id: user.id).first == nil
SharedBasket.where(user_id: user.id).create
Folder.where(name: "Save For Later", user_id: user.id).first_or_create
else
SharedBasket.where(user_id: user.id).first
end
redirect_to root_path
end
def destroy
session[:user_id] = nil
redirect_to root_path
end
end
|
/*
* Copyright 2019 nwillc@gmail.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
package com.github.nwillc.ksvg.elements
import com.github.javafaker.Faker
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
@DisplayName("TEST tag")
class TEXTTest : HasSvg() {
private val faker = Faker()
@Test
fun `format a text tag`() {
val xValue = faker.number().numberBetween(1, 50).toString()
val yValue = faker.number().numberBetween(1, 50).toString()
val bodyValue = faker.shakespeare().hamletQuote()
svg.text {
x = xValue
y = yValue
body = bodyValue
}
Assertions.assertThat(svg.toString())
.isEqualTo("<svg>\n<text x=\"$xValue\" y=\"$yValue\">$bodyValue</text>\n</svg>\n")
}
}
|
@if (count($errors) > 0)
@foreach ($errors->all() as $message)
<div class="uk-alert-danger" uk-alert>
<a class="uk-alert-close" uk-close></a>
{{ $message }}
</div>
@endforeach
@endif
|
-- This should give me the number of buses on each route at a given time
DROP TABLE IF EXISTS temp.variables;
CREATE TEMP TABLE variables AS
SELECT
'17:00:00' AS query_time;
DROP TABLE IF EXISTS temp.buses_per_route;
CREATE TEMP TABLE buses_per_route AS
SELECT
route_id AS "route",
COUNT(trip_id) AS "buses"
FROM trips
WHERE trip_id IN (
SELECT DISTINCT trip_id FROM stop_times
WHERE departure_time >= (SELECT query_time FROM variables)
) AND trip_id IN (
SELECT DISTINCT trip_id FROM stop_times
WHERE arrival_time <= (SELECT query_time FROM variables)
) AND (service_id = 'weekday' OR service_id = 'weekdaynoph' OR service_id = 'weekdaynorf')
GROUP BY route_id;
SELECT * FROM buses_per_route;
SELECT
buses,
COUNT("route") AS "# of routes",
GROUP_CONCAT("route", ', ') AS "list of routes",
buses * COUNT("route") AS "total buses"
FROM buses_per_route
GROUP BY buses;
SELECT sum(buses) FROM buses_per_route;
-- Part two: Get sums for all hours
DROP TABLE IF EXISTS temp.trip_time_info;
CREATE TABLE temp.trip_time_info AS
SELECT
trip_id AS id,
NULL AS start_time,
NULL AS end_time
FROM trips
WHERE service_id = 'weekday'
OR service_id = 'weekdaynoph'
OR service_id = 'weekdaynorf';
UPDATE trip_time_info
SET start_time = (
SELECT MIN(departure_time)
FROM stop_times
WHERE trip_id = id
);
UPDATE trip_time_info
SET end_time = (
SELECT MAX(arrival_time)
FROM stop_times
WHERE trip_id = id
);
DROP TABLE IF EXISTS temp.time_counts;
CREATE TABLE temp.time_counts AS
SELECT
hour10 || hour1 || ':' || minute10 || minute1 || ':00' AS "time",
NULL as "starting",
NULL as "persistent",
NULL as "ending"
FROM temp.hour10 JOIN temp.hour JOIN temp.minute10 JOIN temp.minute;
UPDATE time_counts
SET "starting" = (
SELECT COUNT(id)
FROM trip_time_info
WHERE start_time = "time"
);
UPDATE time_counts
SET "persistent" = (
SELECT COUNT(id)
FROM trip_time_info
WHERE start_time < "time"
AND end_time > "time"
);
UPDATE time_counts
SET "ending" = (
SELECT COUNT(id)
FROM trip_time_info
WHERE end_time = "time"
);
SELECT * FROM time_counts;
|
---
layout: post
title: "awils3126 must have cheated flatstickpub"
category: photos
---
[](https://www.instagram.com/p/BwvdsuXp2aH/)
|
class Debt {
int id;
int parentId;
String date;
double value;
String description;
Debt({
this.id,
this.parentId,
this.date,
this.description,
this.value = 0.0,
});
}
|
import { createSelector } from 'reselect';
export const getAttributeHealingPower = createSelector(
[],
() => {
return 0;
}
);
|
function kube_shell() {
IMAGE=`pwd`
IMAGE=`basename $IMAGE`
if [ -n "$1" ]; then
IMAGE="$1"
fi
echo "Opening shell into pod '$IMAGE'..."
kubectl exec -it "$IMAGE" sh
}
|
using System;
namespace AVR.Debugger.Interfaces
{
public interface IServiceProvider
{
T GetService<T>();
void AddService<T>(object instance);
void AddService<T>(Func<object> factory);
}
}
|
import Steering from './steering';
import Phaser from 'phaser';
import Vector2 = Phaser.Math.Vector2;
import Sprite = Phaser.Physics.Arcade.Sprite;
export class Flee implements Steering {
constructor(
private owner: Sprite,
private pursuer: { x: number; y: number },
public force: number
) {}
calculateImpulse() {
const toPursuer = new Vector2(
this.pursuer.x - this.owner.x,
this.pursuer.y - this.owner.y
);
if (isNaN(toPursuer.x)) return new Vector2(0, 0);
const x = Math.abs(toPursuer.x) < 1 ? 0 : -Math.sign(toPursuer.x);
const y = Math.abs(toPursuer.y) < 1 ? 0 : -Math.sign(toPursuer.y);
return new Vector2(x, y);
}
}
|
//--------------------------------------------------------------------------------------------------
//
// Copyright (c) 2018 Denis Dyakov
// poritons Copyright (c) 2019 Iron Heart Consulting, LLC
// Adapted for ADS1115 device by Steve Conklin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//--------------------------------------------------------------------------------------------------
// Package ads implements controlling the A/D and reading sampled values for the ADS1115 A/D Converter
package ads
import (
"github.com/sconklin/go-i2c"
)
// SensorType identify which Bosch Sensortec
// temperature and pressure sensor is used.
// BMP180 and BMP280 are supported.
type SensorType int
// Implement Stringer interface.
func (v SensorType) String() string {
if v == ADS1115 {
return "ADS1115"
}
return "!!! unknown !!!"
}
const (
// ADS1115 A/D Converter
ADS1115 SensorType = iota
)
// InputMuxMode : Input Multiplexer Mode
const (
MUX_DIFFERENTIAL_0_1 = 0 // Differential, 0 Positive, 1 Negative
MUX_DIFFERENTIAL_0_3 = 1 // Differential, 0 Positive, 3 Negative
MUX_DIFFERENTIAL_1_3 = 2 // Differential, 1 Positive, 3 Negative
MUX_DIFFERENTIAL_2_3 = 3 // Differential, 2 Positive, 3 Negative
MUX_SINGLE_0 = 4 // Single Ended 0
MUX_SINGLE_1 = 5 // Single Ended 1
MUX_SINGLE_2 = 6 // Single Ended 2
MUX_SINGLE_3 = 7 // Single Ended 3
MUX_MAX = 7
)
// PGAMode : Programmable Gain Amplifier config
const (
PGA_6_144 = 0 // Full Scale Range = +/- 6.144V
PGA_4_096 = 1 // Full Scale Range = +/- 4.096V
PGA_2_048 = 2 // Full Scale Range = +/- 2.048V
PGA_1_024 = 3 // Full Scale Range = +/- 1.024V
PGA_0_512 = 4 // Full Scale Range = +/- 0.512V
PGA_0_256 = 5 // Full Scale Range = +/- 0.128V
// PGA_0_256a = 6 // Full Scale Range = +/- 0.128V
// PGA_0_256b = 7 // Full Scale Range = +/- 0.128V
PGA_MAX = 5
)
// Mode : Conversion Mode
const (
MODE_CONTINUOUS = 0 // Continuous Conversion
MODE_SINGLE_SHOT = 1 // Single Shot Conversion
MODE_MAX = 1
)
// Datarate is the A/D sampling rate
const (
RATE_8 = 0 // 8 Samples per Second
RATE_16 = 1 // 16 Samples per Second
RATE_32 = 2 // 32 Samples per Second
RATE_64 = 3 // 64 Samples per Second
RATE_128 = 4 // 128 Samples per Second
RATE_150 = 5 // 150 Samples per Second
RATE_475 = 6 // 475 Samples per Second
RATE_860 = 7 // 860 Samples per Second
RATE_MAX = 7
)
// Comparator Mode
const (
COMP_MODE_TRADITIONAL = 0
COMP_MODE_WINDOW = 1
COMP_MODE_MAX = 1
)
// Comparator Polarity
const (
COMP_POL_ACTIVE_LOW = 0
COMP_POL_ACTIVE_HIGH = 1
COMP_POL_MAX = 1
)
// Comparator Latch
const (
COMP_LAT_OFF = 0
COMP_LAT_ON = 1
COMP_LAT_MAX = 1
)
// Comparator Queue
const (
COMP_QUE_ONE = 0
COMP_QUE_TWO = 1
COMP_QUE_FOUR = 2
COMP_QUE_DISABLE = 3
COMP_QUE_MAX = 3
)
// SensorInterface is an Abstract ADSx sensor interface
type SensorInterface interface {
// ReadConfig reads configuration from the chip
ReadConfig(i2c *i2c.I2C) (uint16, error)
// WriteConfig writes the stored configuration to the chip
WriteConfig(i2c *i2c.I2C) error
// SetMuxMode sets the stored configuration (does not write to chip)
SetMuxMode(uint16) error
// SetPGAMode sets the stored configuration (does not write to chip)
SetPgaMode(uint16) error
// SetConversionMode sets the stored configuration (does not write to chip)
SetConversionMode(uint16) error
// SetDataRate sets the stored configuration (does not write to chip)
SetDataRate(uint16) error
// SetComparatorMode sets the stored configuration (does not write to chip)
SetComparatorMode(uint16) error
// SetComparatorPolarity sets the stored configuration (does not write to chip)
SetComparatorPolarity(uint16) error
// SetComparatorLatch sets the stored configuration (does not write to chip)
SetComparatorLatch(uint16) error
// SetComparatorQueue sets the stored configuration (does not write to chip)
SetComparatorQueue(uint16) error
// ReadStatus reads the status register from the chip
// returns nonzero if a conversion is in progress
ReadStatus(i2c *i2c.I2C) (uint16, error)
// StartConversion will start a conversion in single-shot mode
StartConversion(i2c *i2c.I2C) error
// ReadLoThreshold reads the low comparator threshold from the chip
ReadLoThreshold(i2c *i2c.I2C) (int16, error)
// ReadHiThreshold reads the high comparator threshold from the chip
ReadHiThreshold(i2c *i2c.I2C) (int16, error)
// ReadConversion reads the converted value from the chip
ReadConversion(i2c *i2c.I2C) (int16, error)
}
// ADS represents only one model of A/D so far
type ADS struct {
sensorType SensorType
i2c *i2c.I2C
ads SensorInterface
}
// NewADS creats a new device interface
func NewADS(sensorType SensorType, i2c *i2c.I2C) (*ADS, error) {
v := &ADS{sensorType: sensorType, i2c: i2c}
switch sensorType {
case ADS1115:
v.ads = &SensorADS1115{}
}
_, err := v.ads.ReadConfig(i2c)
if err != nil {
return nil, err
}
return v, nil
}
// ReadConfig from the chip
func (v *ADS) ReadConfig() (uint16, error) {
t, err := v.ads.ReadConfig(v.i2c)
return t, err
}
// WriteConfig to the chip from the stored config data
func (v *ADS) WriteConfig() error {
err := v.ads.WriteConfig(v.i2c)
return err
}
// SetMuxMode in stored config
func (v *ADS) SetMuxMode(imm uint16) error {
err := v.ads.SetMuxMode(imm)
return err
}
// SetPgaMode in stored config
func (v *ADS) SetPgaMode(pm uint16) error {
err := v.ads.SetPgaMode(pm)
return err
}
// SetConversionMode in stored config
func (v *ADS) SetConversionMode(md uint16) error {
err := v.ads.SetConversionMode(md)
return err
}
// SetDataRate in stored config
func (v *ADS) SetDataRate(dr uint16) error {
err := v.ads.SetDataRate(dr)
return err
}
// SetComparatorMode in stored config
func (v *ADS) SetComparatorMode(cm uint16) error {
err := v.ads.SetComparatorMode(cm)
return err
}
// SetComparatorPolarity in stored config
func (v *ADS) SetComparatorPolarity(cp uint16) error {
err := v.ads.SetComparatorPolarity(cp)
return err
}
// SetComparatorLatch in stored config
func (v *ADS) SetComparatorLatch(cl uint16) error {
err := v.ads.SetComparatorLatch(cl)
return err
}
// SetComparatorQueue in stored config
func (v *ADS) SetComparatorQueue(cq uint16) error {
err := v.ads.SetComparatorQueue(cq)
return err
}
// ReadStatus from the chip
func (v *ADS) ReadStatus() (uint16, error) {
t, err := v.ads.ReadStatus(v.i2c)
return t, err
}
// StartConversion if in single-shot mode
func (v *ADS) StartConversion() error {
err := v.ads.StartConversion(v.i2c)
return err
}
// ReadLoThreshold for comparator from the chip
func (v *ADS) ReadLoThreshold() (int16, error) {
t, err := v.ads.ReadLoThreshold(v.i2c)
return t, err
}
// ReadHiThreshold for comparator from the chip
func (v *ADS) ReadHiThreshold() (int16, error) {
t, err := v.ads.ReadHiThreshold(v.i2c)
return t, err
}
// ReadConversion value from the chip
func (v *ADS) ReadConversion() (int16, error) {
t, err := v.ads.ReadConversion(v.i2c)
return t, err
}
|
from os.path import basename
from pyriksprot import interface, to_speech, workflows
from pyriksprot.dispatch import dispatch
# pylint: disable=redefined-outer-name
TAG = "vx.y.z"
def main(target_type: dispatch.TargetTypeKey, source_folder: str):
workflows.extract_corpus_tags(
source_folder=source_folder,
metadata_filename=f"/data/westac/riksdagen_corpus_data/metadata/riksprot_metadata.{TAG}.db",
target_name=f'/data/westac/riksdagen_corpus_data/{target_type}_{basename(source_folder)}/',
target_type=target_type,
content_type=interface.ContentType.TaggedFrame,
compress_type=dispatch.CompressType.Feather,
segment_level=interface.SegmentLevel.Speech,
merge_strategy=to_speech.MergeStrategyType.chain,
temporal_key=None,
group_keys=None,
years=None,
segment_skip_size=1,
multiproc_keep_order=False,
multiproc_processes=3,
multiproc_chunksize=100,
force=True,
progress=True,
)
if __name__ == '__main__':
target_type: dispatch.TargetTypeKey = 'single-id-tagged-frame'
source_folder: str = '/data/riksdagen_corpus_data/tagged_frames_{TAG}_profile'
main(target_type, source_folder=source_folder)
|
/*
Class: Graphic.Image
Shape implementation of an image.
Author:
Sébastien Gruhier, <http://www.xilinus.com>
License:
MIT-style license.
*/
Graphic.Image = Class.create();
Object.extend(Graphic.Image.prototype, Graphic.Rectangle.prototype);
// Keep parent initialize
Graphic.Image.prototype._shapeInitialize = Graphic.Shape.prototype.initialize;
Object.extend(Graphic.Image.prototype, {
initialize: function(renderer, image) {
this._shapeInitialize(renderer, "image");
Object.extend(this.attributes, {x:0, y:0, width:0, height:0});
return this;
},
// Group: Specific Image Functions
/*
Function: setSource
Sets image source
Parameters:
url - image url
autoSize - Set width and height from image (default false)
Returns:
this
*/
setSource: function(url, autoSize) {
if (autoSize) {
this.image = new Image();
this.image.src= url;
Event.observe(this.image, "load",function() {
this.setSize(this.image.width, this.image.height);
this._setAttribute('href', url);
}.bind(this));
}
else
this._setAttribute('href', url);
return this;
}
});
|
if [ -e ~/.secrets ]; then
source ~/.secrets
fi
|
#!/bin/ksh
MenuItems=5
(( secshi = $(date +%s) + ((5-$(date +%w)+7) % 7)*86400 ))
n=$MenuItems
print "<select name=\"PayWeek\">"
while (( --n >= 0 ))
do
hi=$(date --date=@$secshi "+%Y-%m-%d")
(( secslo = secshi-6*86400+3600 ))
secslo=$(date --date=$(date --date=@$secslo "+%Y-%m-%d") "+%s")
lo=$(date --date=@$secslo "+%Y-%m-%d")
(( secshi = secshi-7*86400+3600 ))
secshi=$(date --date=$(date --date=@$secshi "+%Y-%m-%d") "+%s")
print "<option value=\"$lo,$hi\">$hi</option>"
done
print "</select>"
|
name := "iiot-demo"
version := "1.0"
scalaVersion := "2.10.5"
val sparkVersion = "1.6.0"
val kuduVersion = "1.2.0-cdh5.10.0"
// protocol buffer support
//PB.protobufSettings
//PB.targets in Compile := Seq(
// scalapb.gen() -> (sourceManaged in Compile).value
//)
libraryDependencies ++= Seq(
"org.scalatest" %% "scalatest" % "2.2.1" % "test",
"com.trueaccord.scalapb" %% "sparksql-scalapb" % "0.1.8",
"org.apache.spark" %% "spark-core" % sparkVersion,
"org.apache.spark" %% "spark-mllib" % sparkVersion,
"org.apache.spark" %% "spark-streaming" % sparkVersion,
"org.apache.spark" %% "spark-streaming-kafka" % sparkVersion,
"org.apache.spark" %% "spark-sql" % sparkVersion,
"org.apache.kudu" % "kudu-spark_2.10" % kuduVersion,
"org.apache.kudu" % "kudu-client" % kuduVersion,
"org.eclipse.paho" % "org.eclipse.paho.client.mqttv3" % "1.2.0"
)
PB.targets in Compile := Seq(
scalapb.gen() -> (sourceManaged in Compile).value
)
PB.protocVersion := "-v261"
resolvers ++= Seq(
"Cloudera Repository" at "https://repository.cloudera.com/artifactory/cloudera-repos/",
"scala-tools" at "https://oss.sonatype.org/content/groups/scala-tools",
"Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/",
"Second Typesafe repo" at "http://repo.typesafe.com/typesafe/maven-releases/",
"Mesosphere Public Repository" at "http://downloads.mesosphere.io/maven",
"Bintray sbt plugin releases" at "http://dl.bintray.com/sbt/sbt-plugin-releases/",
"MQTT Repository" at "https://repo.eclipse.org/content/repositories/paho-releases/",
Resolver.sonatypeRepo("public")
)
assemblyMergeStrategy in assembly <<= (assemblyMergeStrategy in assembly) { (old) =>
{
case m if m.toLowerCase.endsWith("manifest.mf") => MergeStrategy.discard
case m if m.startsWith("META-INF") => MergeStrategy.discard
case PathList("javax", "servlet", xs @ _*) => MergeStrategy.first
case PathList("org", "apache", xs @ _*) => MergeStrategy.first
case PathList("org", "jboss", xs @ _*) => MergeStrategy.first
case "about.html" => MergeStrategy.rename
case "reference.conf" => MergeStrategy.concat
case _ => MergeStrategy.first
}
}
assemblyShadeRules in assembly := Seq(
ShadeRule.rename("io.netty.handler.**" -> "shadeio.io.netty.handler.@1").inAll,
ShadeRule.rename("io.netty.channel.**" -> "shadeioi.io.netty.channel.@1").inAll,
ShadeRule.rename("io.netty.util.**" -> "shadeio.io.netty.util.@1").inAll,
ShadeRule.rename("io.netty.bootstrap.**" -> "shadeio.io.netty.bootstrap.@1").inAll,
ShadeRule.rename("com.google.common.**" -> "shade.com.google.common.@1").inAll,
ShadeRule.rename("com.google.protobuf.**" -> "shadeproto.@1").inAll
)
|
/*eslint-disable no-magic-numbers*/
module.exports = function jsonTree(modules) {
let maxDepth = 1;
let rootSize = 0;
const root = {
children: [],
name: "root"
};
const getChild = function (arr, name) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].name === name) {
return arr[i];
}
}
};
const getFile = function (module, fileName, parentTree) {
const charIndex = fileName.indexOf("/");
if (charIndex !== -1) {
let folder = fileName.slice(0, charIndex);
if (folder === "~") {
folder = "node_modules";
}
let childFolder = getChild(parentTree.children, folder);
if (!childFolder) {
childFolder = {
name: folder,
children: []
};
parentTree.children.push(childFolder);
}
getFile(module, fileName.slice(charIndex + 1), childFolder);
} else {
module.name = fileName;
parentTree.children.push(module);
}
};
const dirsizes = function (child) {
return child.size = "size" in child //eslint-disable-line no-return-assign
? child.size
: child.children.reduce((size, child) => { //eslint-disable-line no-shadow
return size + ("size" in child ? child.size : dirsizes(child));
}, 0);
};
modules.forEach(
function addToTree(module) { //eslint-disable-line prefer-arrow-callback
let size;
if (module.source) {
size = module.source.length;
} else {
size = module.size;
}
rootSize += size;
const mod = {
id: module.id,
fullName: module.name,
size,
reasons: module.reasons
};
const depth = mod.fullName.split("/").length - 1;
if (depth > maxDepth) {
maxDepth = depth;
}
let fileName = mod.fullName;
const beginning = mod.fullName.slice(0, 2);
if (beginning === "./") {
fileName = fileName.slice(2);
}
getFile(mod, fileName, root);
});
root.maxDepth = maxDepth;
root.size = rootSize;
return root;
};
|
# Lingua-Poly Language Disassembling Library
# Copyright (C) 2018-2019 Guido Flohr <guido.flohr@cantanea.com>
# All rights reserved
#
# This library is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What the Fuck You Want
# to Public License, Version 2, as published by Sam Hocevar. See
# http://www.wtfpl.net/ for more details.
use strict;
use utf8;
use Test::More;
use Lingua::Poly::FI::Word::Verb;
my $word;
$word = Lingua::Poly::FI::Word::Verb->new('haluta');
is $word->inflect(1, 1), 'haluan';
is $word->inflect(2, 1), 'haluat';
is $word->inflect(3, 1), 'haluaa';
is $word->inflect(1, 2)->[0], 'haluamme';
is $word->inflect(1, 2)->[1], 'halutaan';
is $word->inflect(2, 2), 'haluatte';
is $word->inflect(3, 2), 'haluavat';
$word = Lingua::Poly::FI::Word::Verb->new('pakata');
is $word->inflect(1, 1), 'pakkaan';
is $word->inflect(2, 1), 'pakkaat';
is $word->inflect(3, 1), 'pakkaa';
is $word->inflect(1, 2)->[0], 'pakkaamme';
is $word->inflect(1, 2)->[1], 'pakataan';
is $word->inflect(2, 2), 'pakkaatte';
is $word->inflect(3, 2), 'pakkaavat';
$word = Lingua::Poly::FI::Word::Verb->new('napata');
is $word->inflect(1, 1), 'nappaan';
is $word->inflect(2, 1), 'nappaat';
is $word->inflect(3, 1), 'nappaa';
is $word->inflect(1, 2)->[0], 'nappaamme';
is $word->inflect(1, 2)->[1], 'napataan';
is $word->inflect(2, 2), 'nappaatte';
is $word->inflect(3, 2), 'nappaavat';
$word = Lingua::Poly::FI::Word::Verb->new('mitata');
is $word->inflect(1, 1), 'mittaan';
is $word->inflect(2, 1), 'mittaat';
is $word->inflect(3, 1), 'mittaa';
is $word->inflect(1, 2)->[0], 'mittaamme';
is $word->inflect(1, 2)->[1], 'mitataan';
is $word->inflect(2, 2), 'mittaatte';
is $word->inflect(3, 2), 'mittaavat';
$word = Lingua::Poly::FI::Word::Verb->new('tavata');
is $word->inflect(1, 1), 'tapaan';
is $word->inflect(2, 1), 'tapaat';
is $word->inflect(3, 1), 'tapaa';
is $word->inflect(1, 2)->[0], 'tapaamme';
is $word->inflect(1, 2)->[1], 'tavataan';
is $word->inflect(2, 2), 'tapaatte';
is $word->inflect(3, 2), 'tapaavat';
done_testing;
|
export default function formatBytes(value: number) {
if (value / 1000 / 1000 > 1) {
return `${(value / 1000 / 1000).toFixed(2)} MB`;
} else if (value / 1000 > 1) {
return `${(value / 1000).toFixed(2)} KB`;
} else {
return `${value.toFixed(2)} B`;
}
}
|
/*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.mapper
import com.github.andrewoma.kwery.core.Row
import java.math.BigDecimal
import java.sql.Connection
import java.sql.Date
import java.sql.Time
import java.sql.Timestamp
open class Converter<R>(
val from: (Row, String) -> R,
val to: (Connection, R) -> Any?
)
abstract class SimpleConverter<R>(from: (Row, String) -> R, to: (R) -> Any? = { it }) : Converter<R>(from, { _, v -> to(v) })
val standardConverters: Map<Class<*>, Converter<*>> = listOf(
reifiedConverter(booleanConverter),
reifiedConverter(byteConverter),
reifiedConverter(shortConverter),
reifiedConverter(intConverter),
reifiedConverter(longConverter),
reifiedConverter(floatConverter),
reifiedConverter(doubleConverter),
reifiedConverter(bigDecimalConverter),
reifiedConverter(stringConverter),
reifiedConverter(bytesConverter),
reifiedConverter(timestampConverter),
reifiedConverter(timeConverter),
reifiedConverter(dateConverter)
).toMap() + mapOf<Class<*>, Converter<*>>(
java.lang.Boolean.TYPE to booleanConverter,
java.lang.Byte.TYPE to byteConverter,
java.lang.Short.TYPE to shortConverter,
java.lang.Integer.TYPE to intConverter,
java.lang.Long.TYPE to longConverter,
java.lang.Float.TYPE to floatConverter,
java.lang.Double.TYPE to doubleConverter
)
inline fun <reified T : Any> reifiedConverter(converter: Converter<T>): Pair<Class<*>, Converter<T>> {
return T::class.java to converter
}
inline fun <reified T> ArrayConverter(sqlType: String): Converter<List<T>> {
return Converter(
{ row, c -> row.array<T>(c).toList() },
{ c, v -> c.createArrayOf(sqlType, v.toTypedArray()) }
)
}
object booleanConverter : SimpleConverter<Boolean>({ row, c -> row.boolean(c) })
object byteConverter : SimpleConverter<Byte>({ row, c -> row.byte(c) })
object shortConverter : SimpleConverter<Short>({ row, c -> row.short(c) })
object intConverter : SimpleConverter<Int>({ row, c -> row.int(c) })
object longConverter : SimpleConverter<Long>({ row, c -> row.long(c) })
object floatConverter : SimpleConverter<Float>({ row, c -> row.float(c) })
object doubleConverter : SimpleConverter<Double>({ row, c -> row.double(c) })
object bigDecimalConverter : SimpleConverter<BigDecimal>({ row, c -> row.bigDecimal(c) })
object stringConverter : SimpleConverter<String>({ row, c -> row.string(c) })
object bytesConverter : SimpleConverter<ByteArray>({ row, c -> row.bytes(c) })
object timestampConverter : SimpleConverter<Timestamp>({ row, c -> row.timestamp(c) })
object timeConverter : SimpleConverter<Time>({ row, c -> row.time(c) })
object dateConverter : SimpleConverter<Date>({ row, c -> row.date(c) })
object clobConverter : Converter<String>(
{ row, c -> row.clob(c).let { it.getSubString(1, it.length().toInt()) } },
{ c, v -> c.createClob().let { it.setString(1, v); it } }
)
object blobConverter : Converter<ByteArray>(
{ row, c -> row.blob(c).let { it.getBytes(1, it.length().toInt()) } },
{ c, v -> c.createBlob().let { it.setBytes(1, v); it } }
)
fun <R> optional(converter: Converter<R>): Converter<R?> = Converter(
{ row, c -> if (row.objectOrNull(c) == null) null else converter.from(row, c) },
{ c, v -> if (v == null) null else converter.to(c, v) }
)
class EnumByNameConverter<T : Enum<T>>(type: Class<T>) : SimpleConverter<T>(
{ row, c -> java.lang.Enum.valueOf(type, row.string(c)) },
{ it.name }
)
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :authenticate_user_from_token
before_filter :miniprofiler
before_filter :redirect_to_real_domain
def current_user
super || Guest.new
end
helper_method :current_user
private
def authenticate_user_from_token
return unless params[:auth_email].presence && params[:auth_token].presence
user = User.from_token_auth(token_auth_params)
sign_in(user, store: false) if user
end
def token_auth_params
params.permit(:auth_email, :auth_token)
end
def miniprofiler
# Rack::MiniProfiler.authorize_request if current_user.admin?
end
def redirect_to_real_domain
return unless request.host =~ /herokuapp./
redirect_to request.url.gsub(/herokuapp./, '')
end
def render_bad_response(message)
render json: { success: false, error: message },
status: :unprocessable_entity
end
end
|
---
layout: post
title: "数据结构-线性查找和二分查找"
subtitle: "linear search and n\binary search"
date: 2017-11-10 13:48:00
author: "xuepro"
header-img: "img/home_bg.jpg"
header-mask: 0.3
catalog: true
multilingual: true
tags:
- DS
---
哈夫曼编码
```cpp
// copyright by hwdong
#include <stdio.h>
typedef struct {
double weight;
int p, l, r;
}HNode;
typedef struct {
HNode *data;
int n;
}HuffmanTree;
void printHuffmanNodes(HuffmanTree &htree, const int M) {
for (int i = 1; i < M; i++) {
printf("%d: %f %d %d %d\n", i, htree.data[i].weight, htree.data[i].p, htree.data[i].l, htree.data[i].r);
}
printf("\n");
}
void select_tree_root(HuffmanTree &htree, const int M, int &m1, int &m2) {
int i = 1;
while (htree.data[i].p != 0) i++;
m1 = i++;
while (htree.data[i].p != 0) i++;
m2 = i;
if (htree.data[m2].weight < htree.data[m1].weight) {
int t = m1; m1 = m2; m2 = t;
}
i++;
for (; i < M; i++) {
if (htree.data[i].p != 0) continue;
if (htree.data[i].weight < htree.data[m1].weight) {
m2 = m1;
m1 = i;
}
else if (htree.data[i].weight < htree.data[m2].weight)
m2 = i;
}
return;
}
void select_tree_root_(HuffmanTree &htree, const int M, int &m1, int &m2) {
int i = 1;
while (htree.data[i].p != 0) i++;
m1 = i; i++;
double m2_value = 1e10;
for (; i < M; i++) {
if (htree.data[i].p != 0) continue;
if (htree.data[i].weight < htree.data[m1].weight) {
m2 = m1; m2_value = htree.data[m1].weight;
m1 = i;
}
else if (htree.data[i].weight < m2_value) {
m2 = i; m2_value = htree.data[i].weight;
}
}
return;
}
void select_tree_root__(HuffmanTree &htree, const int M, int &m1, int &m2) {
double m1_value = 1e10, m2_value = 1e10;
m1 = m2 = 0;
for (int i = 1; i < M; i++) {
if (htree.data[i].p != 0) continue;
if (htree.data[i].weight < m1_value) {
m2 = m1; m2_value = m1_value;
m1 = i; m1_value = htree.data[m1].weight;
}
else if (htree.data[i].weight < m2_value) {
m2 = i; m2_value = htree.data[i].weight;
}
}
return;
}
bool creatHuffmanTree(const double weights[], const int n, HuffmanTree &htree) {
htree.data = new HNode[2 * n]; if (!htree.data) return false;
htree.n = n;
int i;
for (i = 1; i <= n; i++) {
htree.data[i].weight = weights[i - 1];
htree.data[i].p = htree.data[i].l = htree.data[i].r = 0;
}
int n_2 = 2 * n - 1;
for (i = n + 1; i <= n_2; i++) {
int m1, m2;
// printHuffmanNodes(htree,i);
select_tree_root_(htree, i, m1, m2);
htree.data[i].weight = htree.data[m1].weight + htree.data[m2].weight;
htree.data[i].l = m1; htree.data[i].r = m2; htree.data[i].p = 0;
htree.data[m1].p = i; htree.data[m2].p = i;
}
return true;
}
typedef char * HuffmanCode;
HuffmanCode * genHuffmanCode(HuffmanTree &htree) {
HuffmanCode *codes = new HuffmanCode[htree.n];
char *cd = new char[htree.n]; //
for (int i = 1; i <= htree.n; i++) {
int j = i, p, k = 0;
while (htree.data[j].p != 0) {
p = htree.data[j].p;
if (htree.data[p].l == j)
cd[k++] = '0';
else cd[k++] = '1';
j = p;
}
codes[i - 1] = new char[k + 1];
for (j = k-1; j >=0; j--)
codes[i - 1][k-1-j] = cd[j]; //codes[i - 1][j] = cd[j];
codes[i - 1][k] = '\0';
}
delete[] cd;
return codes;
}
void printHuffmanCode(HuffmanCode * codes, int n) {
for (int i = 0; i < n; i++) {
printf("%s\n", codes[i]);
}
printf("\n");
}
int main() {
double weights[] = { 0.05,0.29,0.07,0.08,0.14,0.23,0.03,0.11 };
const int n = 8;
HuffmanTree htree;
creatHuffmanTree(weights, n, htree);
printHuffmanNodes(htree, 16);
HuffmanCode * codes = genHuffmanCode(htree);
printHuffmanCode(codes, n);
return 0;
}
```
|
/*
* Copyright (C) 2016 "IoT.bzh"
* Author Fulup Ar Foll <fulup@iot.bzh>
*
* 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.
*
*/
#define _GNU_SOURCE // needed for vasprintf
#include <stdio.h>
#include <strings.h>
#include "hal-interface.h"
PUBLIC const char *halCtlsLabels[] = {
[Master_Playback_Volume] = "Master_Playback_Volume",
[Master_OnOff_Switch] = "Master_OnOff_Switch",
[Master_Playback_Ramp]= "Master_Playback_Ramp",
[PCM_Playback_Volume] = "PCM_Playback_Volume",
[PCM_Playback_Switch] = "PCM_Playback_Switch",
[Capture_Volume] = "Capture_Volume",
[Vol_Ramp_Set_Mode] = "Volume_Ramp_Mode",
[Vol_Ramp_Set_Delay] = "Volume_Ramp_Delay",
[Vol_Ramp_Set_Down] = "Volume_Ramp_Down",
[Vol_Ramp_Set_Up] = "Volume_Ramp_Up",
[Vol_Ramp_Set_Slave] = "Volume_Ramp_Slave",
// Application Virtual Channels
[Multimedia_Playback_Volume] = "Multimedia_Playback_Volume",
[Navigation_Playback_Volume] = "Navigation_Playback_Volume",
[Emergency_Playback_Volume] = "Emergency_Playback_Volume",
[Telephony_Playback_Volume] = "Telephony_Playback_Volume",
[Multimedia_Playback_Switch] = "Multimedia_Playback_Switch",
[Navigation_Playback_Switch] = "Navigation_Playback_Switch",
[Emergency_Playback_Switch] = "Emergency_Playback_Switch",
[Telephony_Playback_Switch] = "Telephony_Playback_Switch",
// Do not remove EndHalCrlTag
[EndHalCrlTag] = NULL
};
PUBLIC halCtlsTagT halGetTagByLabel (const char *label) {
static int length= sizeof(halCtlsLabels) / sizeof(char*);
for (int idx=1; idx < length; idx++) {
if (halCtlsLabels[idx] && !strcasecmp (halCtlsLabels[idx], label)) return (halCtlsTagT)idx;
}
return (halCtlsTagT)-1;
}
|
import { TowerMap } from '../../Specs/TowerMap';
import { RaceTowers } from '../RaceTowers';
import { FelGuard } from './FelGuard';
import { Mannoroth } from './Mannoroth';
import { SummoningShrine } from './SummoningShrine';
import { KilJaeden } from './KilJaeden';
import { DemonizedDreadlord } from './DemonizedDreadlord';
export class DemonTowers extends RaceTowers {
public AddTowersToList(list: TowerMap<number, object>): void {
// Demon
list.add(FourCC('h03W'), FelGuard);
list.add(FourCC('o00L'), Mannoroth);
list.add(FourCC('n00U'), SummoningShrine);
list.add(FourCC('eC93'), KilJaeden);
list.add(FourCC('h00F'), DemonizedDreadlord);
}
}
|
---
title: 消息代码 | Microsoft Docs
description: 了解消息视图的每个消息行上显示的消息代码的含义。
ms.custom: SEO-VS-2020
ms.date: 11/04/2016
ms.topic: conceptual
helpviewer_keywords:
- message codes
ms.assetid: 9f91f4e2-c1f1-4349-9f11-2fbbf59654be
author: mikejo5000
ms.author: mikejo
manager: jillfra
ms.workload:
- multiple
ms.openlocfilehash: e4b836a5d4c1faad6b4c0375e2ec51d759816889
ms.sourcegitcommit: 620d30c60da8f9805fce524fe4951cf40f28297d
ms.translationtype: HT
ms.contentlocale: zh-CN
ms.lasthandoff: 01/05/2021
ms.locfileid: "97903605"
---
# <a name="message-codes"></a>消息代码
[消息视图](../debugger/messages-view.md)中显示的每行消息均包含“P”、“S”、“s”或“R”代码。 这些代码具有以下含义:
|代码|含义|
|----------|-------------|
|P|该消息已通过 PostMessage 函数发布到队列中。 没有关于该消息的最终处置的可用信息。|
|S|已通过 SendMessage 函数发送该消息。 这意味着,在接收方处理并返回该消息之前,发送方不会重新获得控制权。 因此,接收方可以将返回值传递回发送方。|
|s|已发送该消息,但安全性阻止了对返回值的访问。|
|R|每个“S”行都有对应的“R”(返回)行,后者列出了消息返回值。 有时,消息调用是嵌套的,这意味着一个消息处理程序会发送另一条消息。|
|
CREATE PROCEDURE [dbo].[aspnet_Users_CreateUser]
@ApplicationId uniqueidentifier,
@UserName nvarchar(256),
@IsUserAnonymous bit,
@LastActivityDate DATETIME,
@UserId uniqueidentifier OUTPUT
AS
BEGIN
IF( @UserId IS NULL )
SELECT @UserId = NEWID()
ELSE
BEGIN
IF( EXISTS( SELECT UserId FROM dbo.aspnet_Users
WHERE @UserId = UserId ) )
RETURN -1
END
INSERT dbo.aspnet_Users (ApplicationId, UserId, UserName, LoweredUserName, IsAnonymous, LastActivityDate)
VALUES (@ApplicationId, @UserId, @UserName, LOWER(@UserName), @IsUserAnonymous, @LastActivityDate)
RETURN 0
END
|
export * from "./deviceInputSystem";
export * from "./InputDevices/deviceEnums";
export * from "./InputDevices/deviceTypes";
export * from "./Helpers/eventFactory";
export * from "./Implementations/nativeDeviceInputSystem";
export * from "./Implementations/webDeviceInputSystem";
import "./InputDevices/deviceSourceManager";
export * from "./InputDevices/deviceSourceManager";
|
## [编写一个类,实现简单的栈,栈中有以下操作:](stack.cc)
> 元素入栈 void push(int);
> 元素出栈 void pop();
> 读出栈顶元素 int top();
> 判断栈空 bool emty();
> 判断栈满 bool full();
如果栈溢出,程序终止。栈的数据成员由存放
10个整型数据的数组构成。先后做如下操作:
> 创建栈
> 将10入栈
> 将12入栈
> 将14入栈
> 读出并输出栈顶元素
> 出栈
> 读出并输出栈顶元素
## 编写一个类,实现简单的队列。队列中有以下操作:
> 元素入队 void push(int);
> 元素出队 void pop();
> 读取队头元素 int front();
> 读取队尾元素 int back();
> 判断队列是否为空 bool emty();
> 判断队列是否已满 bool full();
##### [链栈](listQueue.cc)
##### [数组实现栈](arrayQueue.cc)
## 在封装Linux下互斥锁和条件变量,并自行编写测试程序
[MutexCond](mutexcond/)
|
# Rare Disease analysis in Mondo
To answer the question of 'How many rare diseases are there?' we analyzed terms in Mondo to get a total count of Rare Diseases as defined in Mondo Disease Ontology (Mondo).
## Methods
This analysis was performed on the [Mondo 2019-09-30 release](http://purl.obolibrary.org/obo/mondo/releases/2019-09-30/mondo.json).
**1. Get all 'Disease' terms from Mondo**
First we get all the terms in Mondo that are a descendants of `MONDO:0000001 'Disease'`.
There are `21633` Mondo disease terms.
**2. Filter terms that are descendants of 'disease susceptibility'**
We then filter out terms that are descendants of `MONDO:0042489 'disease susceptibility'`, to avoid counting ambiguous terms that are related to disease susceptibility and not the actual disease itself.
This gives us a list of `21563` Mondo rare disease terms.
**3. Identify terms that are 'rare'**
Any disease term in Mondo is considered rare if the term, or its ancestor, has modifier `MONDO:0021136 'Rare'` in the ontology.
There are `12914` Mondo rare disease terms.
**4. Consider terms in 'gard_rare' subset**
There are `3176` Mondo disease terms that are in `gard_rare` subset which contains Mondo terms that are yet to be treated as 'rare'.
We add these terms to our set of Mondo rare disease terms.
This increases the Mondo rare disease term count to `13866`.
But for this analysis, we are interested in terms that are both rare and are leaf nodes in the ontology.
After considering only leaf nodes, we get `10394` as the final count of Mondo rare disease terms.
## Results
[all-mondo-disease-terms.tsv](artifacts/all-mondo-disease-terms.tsv): As part of our analysis, we generated a TSV containing 21633 Mondo disease terms, each with annotations that signifies whether the term is a rare disease term and whether that term is a leaf node in the ontology.
|
using System;
using System.Linq;
using Raven.Client.Embedded;
using Raven.Tests.Common;
using Xunit;
namespace Raven.Tests.Issues.Ravendb718
{
public class DateTimeOffset_QueryDynamicTests : RavenTest
{
[Fact]
public void DateTimeOffset_FromNow_OnDynamicIndex_Queries_WithCorrectOffset()
{
DoTest(DateTimeOffset.Now);
}
[Fact]
public void DateTimeOffset_FromUtcNow_OnDynamicIndex_Queries_WithCorrectOffset()
{
DoTest(DateTimeOffset.UtcNow);
}
[Fact]
public void DateTimeOffset_FromNew_OnDynamicIndex_Queries_WithCorrectOffset()
{
DoTest(new DateTimeOffset(2012, 1, 1, 0, 0, 0, TimeSpan.FromHours(-10.5)));
}
private void DoTest(DateTimeOffset dto)
{
using (var documentStore = NewDocumentStore())
{
using (var session = documentStore.OpenSession())
{
session.Store(new Foo { Id = "foos/1", DateTimeOffset = dto });
session.SaveChanges();
}
using (var session = documentStore.OpenSession())
{
var foo = session.Query<Foo>()
.Customize(x => x.WaitForNonStaleResults())
.First(x => x.DateTimeOffset == dto);
Assert.Equal(dto, foo.DateTimeOffset);
}
}
}
public class Foo
{
public string Id { get; set; }
public DateTimeOffset DateTimeOffset { get; set; }
}
}
}
|
package com.genaku.maskededittextsample
import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import com.genaku.maskededittext.MaskedEditText
import com.genaku.maskededittext.MaskedFormatter
import com.genaku.maskededittext.MaskedWatcher
class MainActivity : AppCompatActivity() {
/**
* Use specific values for create your own mask (see example below or in xml):
* ANYTHING_KEY = '*'
* DIGIT_KEY = '#'
* UPPERCASE_KEY = 'U';
* LOWERCASE_KEY = 'L';
* ALPHA_NUMERIC_KEY = 'A';
* LITERAL_KEY = '\'';
* CHARACTER_KEY = '?';
* HEX_KEY = 'H';
*/
/**
* For getting unmasked text for MaskedEditText mEdtMaskedCustom just use mEdtMaskedCustom.getUnMaskedString().
* For getting unmasked text for default EditText just use formatter.formatString(text).getUnMaskedString().
*/
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private lateinit var mEdtMaskedCustom: MaskedEditText
private lateinit var mEdtMasked: EditText
private lateinit var mImageView: ImageView
private lateinit var mTvPhone: TextInputEditText
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass
// ===========================================================
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViews()
setMask("+7(###) ###-##-##")
}
// ===========================================================
// Listeners, methods for/from Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private fun findViews() {
mEdtMaskedCustom = findViewById(R.id.edt_masked_custom)
mEdtMasked = findViewById(R.id.edt_masked)
mImageView = findViewById(R.id.imageView)
mTvPhone = findViewById(R.id.tvPhone)
mImageView.setOnClickListener {
mTvPhone.text?.clear()
}
}
/**
* You cas use MaskedEditText declared in xml with attribute named mask
* or
* set mask in code for default EdiText
*
* @param mask your mask
*/
private fun setMask(mask: String) {
val formatter = MaskedFormatter(mask)
mTvPhone.addTextChangedListener(InputTypeSwitcher(mTvPhone, mImageView, ::noMask))
mTvPhone.addTextChangedListener(MaskedWatcher(formatter, mTvPhone, ::noMask))
val s = formatter.formatString(mEdtMasked.text.toString()).unMaskedString
}
private class InputTypeSwitcher(
private val editText: EditText,
private val imageView: ImageView,
private val noMask: (text: String) -> Boolean
) : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val value = s.toString()
if (s.isNullOrEmpty()) {
switchImageView(View.GONE)
} else {
switchImageView(View.VISIBLE)
}
if (noMask(value)) {
switchInputType(InputType.TYPE_NULL)
} else {
switchInputType(InputType.TYPE_CLASS_PHONE)
}
}
private fun switchInputType(type: Int) {
if (editText.inputType != type)
editText.inputType = type
}
private fun switchImageView(visibility: Int) {
if (imageView.visibility != visibility)
imageView.visibility = visibility
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
private fun noMask(value: String): Boolean = value.isEmpty() || value[0] !in "+(0123456789"
fun getUnMaskedTextForEdtCustom() {
mEdtMaskedCustom.unMaskedText
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
|
using Letter.IO;
namespace Letter.Tcp
{
public interface ITcpFilter : IFilter<ITcpSession>
{
}
}
|
<?php
/**
* Created by PhpStorm.
* User: xmy 280564871@qq.com
* Date: 2017/4/1
* Time: 15:41
*/
namespace Admin\Model;
use Think\Model;
class TabModel extends Model {
public function __construct($name = '', $tablePrefix = '', $connection = '') {
/* 设置默认的表前缀 */
$this->tablePrefix ='tab_';
/* 执行构造方法 */
parent::__construct($name, $tablePrefix, $connection);
}
}
|
import test from 'ava';
import match from '../index.js';
import {spy} from 'sinon';
test('Must match and return object\'s key', t => {
const expected = [1];
const actual = match('value', {
a: 'test',
value: expected
});
t.is(actual, expected, '');
});
test('Must return default value if nothing matched', t => {
const expected = {a: 1};
const actual = match('nothing', {
value: 1
}, expected);
t.is(actual, expected);
});
test('Must call matched value if it is a function', t => {
const fn = spy();
match('test', {test: fn});
t.is(fn.calledOnce, true);
});
test('Must call default value if nothing matched and it is a function', t => {
const fn = spy();
match('nothing', {}, fn);
t.is(fn.calledOnce, true);
});
test('Must return undefined if default matched with no value', t => {
const expected = undefined;
const actual = match('wat', {test: 1});
t.is(actual, expected);
});
|
<?php
namespace Larabros\Elogram\Exceptions;
use Exception as BaseException;
/**
* Base exception class for this package.
*
* @package Elogram
* @author Hassan Khan <contact@hassankhan.me>
* @link https://github.com/larabros/elogram
* @license MIT
*/
class Exception extends BaseException
{
}
|
{-# LANGUAGE OverloadedStrings #-}
module PngLoader where
import System.IO
import System.Environment
import qualified Data.ByteString as B
import qualified Data.Word as W
import qualified Data.ByteString.Char8 as C
import qualified Codec.Compression.Zlib as Zlib
import qualified Data.ByteString.Lazy as LB
import qualified Data.List as L
import Text.Printf
import Data.List.Split
--Debugging stuff
import System.Directory
import Data.Char
type RGBPixel = [W.Word8]
test_file = "C:/Users/andrew/haskell/Image/sample.png"
png_file = B.readFile test_file
png_header_str = "\137PNG\r\n\SUB\n"
png_header_bytestring = C.pack png_header_str
test_bpp = 3
data Chunk =
Misc_Chunk {dataLength :: Int,
headerStr :: [Char],
chunkData :: [W.Word8],
crc :: [W.Word8]
} |
IHDR_Chunk {dataLength :: Int,
headerStr :: [Char],
chunkData :: [W.Word8],
crc :: [W.Word8],
width :: Int,
height :: Int,
bpp :: Int
} |
IDAT_Chunk {dataLength :: Int,
headerStr :: [Char],
chunkData :: [W.Word8],
crc :: [W.Word8],
width :: Int,
height :: Int,
bpp :: Int
} deriving (Show)
data FilterFlag = NoneF | SubF | UpF | AvgF | PaethF deriving (Show)
data PngImg = PngImg {ihdr :: Chunk,
idat :: Chunk,
misc_chunks :: [Chunk]
}
data Image = Image {imWidth :: Int, imHeight :: Int, imData :: [RGBPixel]}
loadPng :: B.ByteString -> [[RGBPixel]]
loadPng img_bytestring = decodeIDATs (height ihdr) . filter isIDAT $ chunks
where
chunks = extractChunks . B.drop 8 $ img_bytestring
ihdr = getIHDR chunks
isIDAT :: Chunk -> Bool
isIDAT chunk = headerStr chunk == "IDAT"
getIHDR :: [Chunk] -> Chunk
getIHDR (chunk:chunks) = if (headerStr chunk == "IHDR")
then chunk
else getIHDR chunks
extractChunks :: B.ByteString -> [Chunk]
extractChunks bs = extractChunksHelper bs []
where
extractChunksHelper bytestring chunk_list
| B.null bytestring = reverse chunk_list
| otherwise = extractChunksHelper newByteString (chunk:chunk_list)
where
header_str = C.unpack . B.take 4 . B.drop 4 $ bytestring
data_len = bytes_to_number . B.unpack . B.take 4 $ bytestring
chunk_len = 12 + data_len
newByteString = B.drop chunk_len bytestring
chunk_data = B.unpack . B.take data_len . B.drop 8 $ bytestring
crc_data = B.unpack . B.take 4 . B.drop (8+data_len) $ bytestring
chunk = case header_str of
"IHDR" -> (IHDR_Chunk data_len header_str chunk_data crc_data
cwidth cheight test_bpp)
where cwidth = bytes_to_number . take 4 $ chunk_data
cheight = bytes_to_number . take 4 . drop 4 $ chunk_data
"IDAT" -> (IDAT_Chunk data_len header_str chunk_data crc_data
cwidth cheight test_bpp)
where cwidth = width . head . reverse $ chunk_list
cheight = height . head . reverse $ chunk_list
_ -> Misc_Chunk data_len header_str chunk_data crc_data
decodeIDATs :: Int -> [Chunk] -> [[RGBPixel]]
decodeIDATs h idats =
let
unzipped_word8 = LB.unpack . Zlib.decompress . LB.pack
. concat . map chunkData $ idats
line_width = (length unzipped_word8) `div` h
getFlag (x:xs) = (wordToFlag x, xs)
in
map (chunksOf test_bpp) . unfilterLines
. map getFlag . chunksOf line_width $ unzipped_word8
unfilterLines :: [(FilterFlag, [W.Word8])] -> [[W.Word8]]
unfilterLines flaglines = unfilter flaglines []
where
unfilter [] filtered = filtered
unfilter ((NoneF,line):lines) filtered = unfilter lines (line:filtered)
unfilter ((SubF,line):lines) filtered = unfilter lines (newline:filtered)
where
newline = zipWith (+) line (0:0:0:newline)
unfilter ((UpF,line):lines) a@(prevLine:filtered) = unfilter lines (newline:a)
where
newline = zipWith (+) line prevLine
unfilter ((UpF,line):lines) [] = unfilter lines [line]
flipHorizontal :: [[RGBPixel]] -> [[RGBPixel]]
flipHorizontal = map reverse
flipVertical :: [[RGBPixel]] -> [[RGBPixel]]
flipVertical = reverse
--simpleFilter
saveAsPPM img_word8 outPath =
writeFile outPath $ (printf "P3\n%d %d\n255\n" w h) ++ flat_img
where
flat_img = L.intercalate "\n" . map show . concat . concat . reverse $ img_word8
h = length img_word8
w = length . head $ img_word8
-- Helper function
bytes_to_number :: [W.Word8] -> Int
bytes_to_number =
foldl (\n (i,a) -> n + (fromIntegral a)*256^i) 0 . zip [0,1..] . reverse
testMain :: IO ()
testMain = do
argv <- getArgs
img_bs <- B.readFile $ head argv
let flipped = flipVertical . loadPng $ img_bs
saveAsPPM flipped (argv !! 1)
wordToFlag :: W.Word8 -> FilterFlag
wordToFlag word = case word of
0 -> NoneF
1 -> SubF
2 -> UpF
3 -> AvgF
4 -> PaethF
otherwise -> error "Invalid filter flag"
|
$(function(){
// 입력창에 아무 입력도 없을 경우 'Add comment'를 기본으로 세팅
var input_area_default = $('#input_area').html();
if(input_area_default == ''){
var default_text = 'Add comment'
$('#input_area').html(default_text)
}
});
// 입력을 시작하면 기본 세팅인 'Add comment'를 제거
$(document).on("focus","#input_area",function() {
var input_area_default = $('#input_area').html()
if(input_area_default == 'Add comment'){
$('#input_area').html('')
}
});
// 이모지 버튼에 마우스 올리면 표정 바뀜
$(document).on("mouseenter",".emoji_pickup",function() {
$('#emoji_pickup_before').css("display","none");
$('#emoji_pickup_after').css("display","block");
}).on("mouseleave",".emoji_pickup",function() {
$('#emoji_pickup_after').css("display","none");
$('#emoji_pickup_before').css("display","block");
});
// 이모지 버튼 클릭시 이모지 목록 popup
$(document).on("click",".emoji_pickup",function(){
var view = $("#emoji_popup").is(":visible");
if(!view){
// popup div의 size를 가져와서 위치 선정에 활용
var popupdiv_width = $('#emoji_popup').width();
var popupdiv_height = $('#emoji_popup').height();
// popup div의 위치를 설정
var position = $('.emoji_pickup').position();
$('#emoji_popup').css("left", "0");
$('#emoji_popup').css("bottom", "70px");
$("#emoji_popup").css("background-color","#FFFFFF")
$('#emoji_popup').css("display","block");
}else{
$("#emoji_popup").css({"display":"none"});
}
});
// input area에서 esc 누르면 popup div가 사라짐
$(document).on("keyup","body",function() {
if (event.keyCode === 27) {
$("#emoji_popup").css({"display":"none"});
}
});
// emoji_picks
$(document).on("click",".emoji_list", function(e) {
var input_area_default = $('#input_area').html()
if(input_area_default == 'Add comment'){
$('#input_area').html('')
}
var emoji_id = $(this).attr('id');
var imgtag = '<img style="width:23px; height:23px" src="images/emoji/' + emoji_id + '.png">';
$('#input_area').append(imgtag);
});
// Enter 키를 입력할 경우 전송처리
/*
$(document).on("keyup","#input_area",function() {
var inputarea = $('#input_area');
inputarea.scrollTop(inputarea[0].scrollHeight);
if (event.keyCode === 13) {
var input_area_default = $('#input_area').html();
$('#input_area').html('');
}
}); */
|
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Builder
{
public static class RoutingAndMvc
{
public static IEndpointRouteBuilder UseCustomRoutes(this IEndpointRouteBuilder routes, bool useFolders)
{
//routes.AddCloudscribeFileManagerRoutes();
if (useFolders)
{
routes.MapControllerRoute(
name: "foldererrorhandler",
pattern: "{sitefolder}/oops/error/{statusCode?}",
defaults: new { controller = "Oops", action = "Error" },
constraints: new { name = new cloudscribe.Core.Web.Components.SiteFolderRouteConstraint() }
);
routes.MapControllerRoute(
name: "folderdefault",
pattern: "{sitefolder}/{controller}/{action}/{id?}",
defaults: new { action = "Index" },
constraints: new { name = new cloudscribe.Core.Web.Components.SiteFolderRouteConstraint() }
);
}
routes.MapControllerRoute(
name: "errorhandler",
pattern: "oops/error/{statusCode?}",
defaults: new { controller = "Oops", action = "Error" }
);
routes.MapControllerRoute(
name: "def",
pattern: "{controller}/{action}"
, defaults: new { controller = "Home", action = "Index" }
);
return routes;
}
public static IServiceCollection SetupMvc(
this IServiceCollection services,
bool sslIsAvailable
)
{
//https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.1
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
//options.KnownNetworks.Clear();
//options.KnownProxies.Clear();
});
services.Configure<MvcOptions>(options =>
{
if (sslIsAvailable)
{
options.Filters.Add(new RequireHttpsAttribute());
}
});
services.AddRouting(options =>
{
options.LowercaseUrls = true;
});
services.AddMvc()
.AddRazorOptions(options =>
{
//options.AddCloudscribeCommonEmbeddedViews();
//options.AddCloudscribeNavigationBootstrap3Views();
//options.AddCloudscribeCoreBootstrap3Views();
//options.AddCloudscribeFileManagerBootstrap3Views();
// options.AddCloudscribeLoggingBootstrap3Views();
options.ViewLocationExpanders.Add(new cloudscribe.Core.Web.Components.SiteViewLocationExpander());
});
return services;
}
}
}
|
import numpy
from chainer import link
from chainer.functions.array.concat import concat
from chainer.functions.noise.dropout import dropout
from fgnt.chainer_extensions import weight_init
from fgnt.chainer_extensions.sequence_linear \
import sequence_linear_function
from fgnt.chainer_extensions.sequence_lstm import sequence_lstm_function
from fgnt.chainer_extensions.sequenze_batch_normalization import \
sequence_batch_normalization_function
class SequenceLSTM(link.Link):
def __init__(self, in_size, out_size, bias=0, nobias=False,
W_x=None, W_h=None, initial_bias=None, reverse=False,
normalized=False, stateful=False):
super(SequenceLSTM, self).__init__(W_x=(in_size, 4 * out_size),
W_h=(out_size, 4 * out_size))
if W_x is None:
W_x = weight_init.uniform((in_size, 4 * out_size), low=-0.04,
high=0.04)
if W_h is None:
W_h = weight_init.uniform((out_size, 4 * out_size), low=-0.04,
high=0.04)
self.W_x.data[...] = W_x
self.W_h.data[...] = W_h
if normalized:
self.add_param('gamma', (4 * out_size,))
self.add_param('beta', (4 * out_size,))
self.gamma.data[...] = numpy.ones((4 * out_size,),
dtype=numpy.float32)
self.beta.data[...] = numpy.zeros((4 * out_size,),
dtype=numpy.float32)
nobias = True
if nobias:
self.b = None
else:
self.add_param('b', 4 * out_size)
if initial_bias is None:
initial_bias = bias
self.b.data[...] = initial_bias
self.add_persistent('reverse', reverse)
self.add_persistent('normalized', normalized)
self.add_persistent('stateful', stateful)
self.reset_states()
def reset_states(self):
self.h_prev = None
self.c_prev = None
def __call__(self, x, **kwargs):
"""Applies the lstm layer.
Args:
x (~chainer.Variable): Time-Batch of input vectors.
Returns:
~chainer.Variable: Output of the lstm layer.
"""
dropout_rate = kwargs.get('dropout', 0.)
dropout_rate_hidden_hidden = kwargs.get('dropout_hidden_hidden', 0.)
x = dropout(x, dropout_rate)
lstm_in = sequence_linear_function(x, self.W_x, self.b)
if self.normalized:
lstm_in = sequence_batch_normalization_function(lstm_in, self.gamma,
self.beta)
if self.stateful:
c_prev = self.c_prev
h_prev = self.h_prev
else:
c_prev = None
h_prev = None
lstm_out, self.h_prev, self.c_prev = \
sequence_lstm_function(lstm_in, self.W_h, c_prev, h_prev,
self.reverse, dropout_rate_hidden_hidden)
return lstm_out
class SequenceBLSTM(link.Chain):
def __init__(self, in_size, out_size, bias=0, nobias=False,
W_x_fw=None, W_h_fw=None, W_x_bw=None, W_h_bw=None,
initial_bias=None, normalized=False, concat=False,
stateful=False):
super(SequenceBLSTM, self).__init__(
lstm_fw=SequenceLSTM(in_size, out_size, bias, nobias,
W_x_fw, W_h_fw, initial_bias,
normalized=normalized,
stateful=stateful),
lstm_bw=SequenceLSTM(in_size, out_size, bias, nobias,
W_x_bw, W_h_bw, initial_bias,
reverse=True,
normalized=normalized,
stateful=stateful)
)
self.add_persistent('concat', concat)
self.add_persistent('stateful', stateful)
def __call__(self, x, **kwargs):
lstm_fw = self.lstm_fw(x, **kwargs)
lstm_bw = self.lstm_bw(x, **kwargs)
if self.concat:
return concat([lstm_fw, lstm_bw], axis=2)
else:
return lstm_fw + lstm_bw
|
module test_julia_inferred
using Test
function f1(a::Bool)
Any[a ? 1 : 1.0]
end
function f2(a::Bool)::Vector{Any}
[a ? 1 : 1.0]
end
function f3(a::Bool)
[a ? 1 : 1.0]
end
@inferred(f1(true))
@inferred(f2(true))
@test_throws Exception @inferred(f3(true))
end # module test_julia_inferred
|
class Student:
def __init__(self, name, subjects):
self.name = name
self.subjects = subjects
def greet(self):
print("Hello, I'm {}. My favourite subjects are: ".format(self.name))
for item in self.subjects:
print("\t{}".format(item))
# objects creation:
ivan = Student("Ivan Ivanov", ["maths", "phisics"])
alex = Student("Alex Petrov", ["arts", "music"])
maria = Student("Maria Popova", ["chemistry", "biology"])
# use objects:
ivan.greet()
alex.greet()
maria.greet()
|
{**********************************************************************}
{ }
{ "The contents of this file are subject to the Mozilla Public }
{ License Version 1.1 (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.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express }
{ or implied. See the License for the specific language }
{ governing rights and limitations under the License. }
{ }
{ Copyright Creative IT. }
{ Current maintainer: Eric Grange }
{ }
{**********************************************************************}
{
This unit wraps Unified InterBase from Henri Gourvest (www.progdigy.com)
http://sourceforge.net/projects/uib/
Parameters:
- server & database name (ex: 'server:path/to.db.fdb')
- user name, optional (ex: 'SYSDBA')
- password, optional (ex: 'masterkey')
- character set, optional (ex: 'WIN1252')
- library name, optional (ex: 'fbclient.dll')
}
unit dwsUIBDatabase;
interface
uses
Classes, SysUtils,
uib, uiblib, uibmetadata,
dwsUtils, dwsExprs, dwsDatabase, dwsStack, dwsXPlatform, dwsDataContext, dwsSymbols;
type
TdwsUIBDataBase = class (TdwsDataBase, IdwsDataBase)
private
FDB : TUIBDataBase;
FTransaction : TUIBTransaction;
protected
property DB : TUIBDataBase read FDB write FDB;
property Transaction : TUIBTransaction read FTransaction write FTransaction;
public
constructor Create(const parameters : array of String);
destructor Destroy; override;
procedure BeginTransaction;
procedure Commit;
procedure Rollback;
function InTransaction : Boolean;
function CanReleaseToPool : String;
procedure Exec(const sql : String; const parameters : IScriptDynArray; context : TExprBase);
function Query(const sql : String; const parameters : IScriptDynArray; context : TExprBase) : IdwsDataSet;
function VersionInfoText : String;
end;
TdwsUIBDataSet = class (TdwsDataSet)
private
FDB : TdwsUIBDataBase;
FQuery : TUIBQuery;
protected
procedure DoPrepareFields; override;
public
constructor Create(db : TdwsUIBDataBase; const sql : String; const parameters : IScriptDynArray);
destructor Destroy; override;
function Eof : Boolean; override;
procedure Next; override;
function FieldCount : Integer; override;
end;
TdwsUIBDataField = class (TdwsDataField)
protected
function GetName : String; override;
function GetDataType : TdwsDataFieldType; override;
function GetDeclaredType : String; override;
public
constructor Create(dataSet : TdwsUIBDataSet; fieldIndex : Integer);
function IsNull : Boolean; override;
procedure AsString(var Result : String); override;
function AsInteger : Int64; override;
function AsFloat : Double; override;
function AsBoolean : Boolean; override;
function AsBlob : RawByteString; override;
end;
// IdwsBlob = interface
// ['{018C9441-3177-49E1-97EF-EA5F2584FA60}']
// end;
TdwsUIBDataBaseFactory = class (TdwsDataBaseFactory)
public
function CreateDataBase(const parameters : TStringDynArray) : IdwsDataBase; override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
procedure AssignParameters(var rq : TUIBQuery; const params : IScriptDynArray);
var
i : Integer;
p : PVarData;
v : Variant;
rqParams : TSQLParams;
begin
rqParams:=rq.Params;
for i:=0 to params.ArrayLength-1 do begin
params.EvalAsVariant(i, v);
p := PVarData(@v);
case p.VType of
varInt64 : rqParams.AsInt64[i]:=p.VInt64;
varDouble : rqParams.AsDouble[i]:=p.VDouble;
varUString : rqParams.AsString[i]:=String(p.VUString);
varBoolean : rqParams.AsBoolean[i]:=p.VBoolean;
varNull : rqParams.IsNull[i]:=True;
else
rqParams.AsVariant[i]:=PVariant(p)^;
end;
end;
end;
// ------------------
// ------------------ TdwsUIBDataBaseFactory ------------------
// ------------------
// CreateDataBase
//
function TdwsUIBDataBaseFactory.CreateDataBase(const parameters : TStringDynArray) : IdwsDataBase;
var
db : TdwsUIBDataBase;
begin
db:=TdwsUIBDataBase.Create(parameters);
Result:=db;
end;
// ------------------
// ------------------ TdwsUIBDataBase ------------------
// ------------------
// Create
//
constructor TdwsUIBDataBase.Create(const parameters : array of String);
var
nbParams : Integer;
dbName : String;
begin
if FDB=nil then begin
nbParams := Length(parameters);
if nbParams > 0 then
dbName := TdwsDataBase.ApplyPathVariables(parameters[0]);
try
FDB:=TUIBDataBase.Create{$ifndef UIB_NO_COMPONENT}(nil){$endif};
FDB.DatabaseName:=dbName;
if nbParams > 1 then
FDB.UserName := parameters[1];
if nbParams > 2 then
FDB.PassWord := parameters[2];
if nbParams > 3 then
FDB.CharacterSet := uiblib.StrToCharacterSet(ScriptStringToRawByteString(parameters[3]));
if nbParams > 4 then
FDB.LibraryName := parameters[4];
FDB.Connected:=True;
except
RefCount:=0;
raise;
end;
end;
if FTransaction=nil then begin
FTransaction:=TUIBTransaction.Create{$ifndef UIB_NO_COMPONENT}(nil){$endif};
FTransaction.DataBase:=FDB;
end;
end;
// Destroy
//
destructor TdwsUIBDataBase.Destroy;
begin
FTransaction.Free;
FDB.Free;
inherited;
end;
// BeginTransaction
//
procedure TdwsUIBDataBase.BeginTransaction;
begin
FTransaction.StartTransaction;
end;
// Commit
//
procedure TdwsUIBDataBase.Commit;
begin
FTransaction.Commit;
end;
// Rollback
//
procedure TdwsUIBDataBase.Rollback;
begin
FTransaction.RollBack;
end;
// InTransaction
//
function TdwsUIBDataBase.InTransaction : Boolean;
begin
Result:=FTransaction.InTransaction;
end;
// CanReleasetoPool
//
function TdwsUIBDataBase.CanReleasetoPool : String;
begin
// Note: UIB can't have datasets open outside transactions
if InTransaction then
Result:='in transaction'
else Result:='';
end;
// Exec
//
procedure TdwsUIBDataBase.Exec(const sql : String; const parameters : IScriptDynArray; context : TExprBase);
var
rq : TUIBQuery;
begin
rq:=TUIBQuery.Create{$ifndef UIB_NO_COMPONENT}(nil){$endif};
try
rq.Transaction:=FTransaction;
rq.SQL.Text:=sql;
AssignParameters(rq, parameters);
rq.Execute;
except
rq.Close;
raise;
end;
end;
// Query
//
function TdwsUIBDataBase.Query(const sql : String; const parameters : IScriptDynArray; context : TExprBase) : IdwsDataSet;
var
ds : TdwsUIBDataSet;
begin
ds:=TdwsUIBDataSet.Create(Self, sql, parameters);
Result:=ds;
end;
// VersionInfoText
//
function TdwsUIBDataBase.VersionInfoText : String;
begin
Result:='UIB '+DB.InfoVersion;
end;
// ------------------
// ------------------ TdwsUIBDataSet ------------------
// ------------------
// Create
//
constructor TdwsUIBDataSet.Create(db : TdwsUIBDataBase; const sql : String; const parameters : IScriptDynArray);
begin
FDB:=db;
inherited Create(db);
FQuery:=TUIBQuery.Create{$ifndef UIB_NO_COMPONENT}(nil){$endif};
try
FQuery.CachedFetch := False;
FQuery.UseCursor := False;
FQuery.FetchBlobs := True;
FQuery.Transaction := db.FTransaction;
FQuery.SQL.Text := sql;
FQuery.Prepare(True);
AssignParameters(FQuery, parameters);
FQuery.Open;
except
RefCount:=0;
raise;
end;
end;
// Destroy
//
destructor TdwsUIBDataSet.Destroy;
begin
FQuery.Free;
inherited;
end;
// Eof
//
function TdwsUIBDataSet.Eof : Boolean;
begin
Result:=FQuery.Eof;
end;
// Next
//
procedure TdwsUIBDataSet.Next;
begin
FQuery.Next;
end;
// FieldCount
//
function TdwsUIBDataSet.FieldCount : Integer;
begin
Result:=FQuery.Fields.FieldCount;
end;
// DoPrepareFields
//
procedure TdwsUIBDataSet.DoPrepareFields;
var
i, n : Integer;
begin
n:=FQuery.Fields.FieldCount;
SetLength(FFields, n);
for i:=0 to n-1 do
FFields[i]:=TdwsUIBDataField.Create(Self, i);
end;
// ------------------
// ------------------ TdwsUIBDataField ------------------
// ------------------
// Create
//
constructor TdwsUIBDataField.Create(dataSet : TdwsUIBDataSet; fieldIndex : Integer);
begin
inherited Create(dataSet, fieldIndex);
end;
// IsNull
//
function TdwsUIBDataField.IsNull : Boolean;
begin
Result:=TdwsUIBDataSet(DataSet).FQuery.Fields.IsNull[Index];
end;
// GetName
//
function TdwsUIBDataField.GetName : String;
var
fields : TSQLResult;
begin
fields := TdwsUIBDataSet(DataSet).FQuery.Fields;
Result := fields.AliasName[Index];
end;
// GetDataType
//
function TdwsUIBDataField.GetDataType : TdwsDataFieldType;
var
uibft : TUIBFieldType;
begin
uibft:=TdwsUIBDataSet(DataSet).FQuery.Fields.FieldType[Index];
case uibft of
uftNumeric, uftFloat, uftDoublePrecision : Result:=dftFloat;
uftChar, uftVarchar, uftCstring : Result:=dftString;
uftSmallint, uftInteger, uftInt64 : Result:=dftInteger;
uftTimestamp, uftDate, uftTime : Result:=dftDateTime;
uftBlob, uftBlobId : Result:=dftBlob;
{$IFDEF IB7_UP}
uftBoolean : Result:=dftBoolean;
{$ENDIF}
{$IFDEF FB25_UP}
uftNull : Result:=dftNull;
{$ENDIF}
else
Result:=dftUnknown;
end;
end;
// GetDeclaredType
//
function TdwsUIBDataField.GetDeclaredType : String;
const
cFieldTypes: array [TUIBFieldType] of string =
('', 'NUMERIC', 'CHAR', 'VARCHAR', 'CSTRING', 'SMALLINT', 'INTEGER', 'QUAD',
'FLOAT', 'DOUBLE PRECISION', 'TIMESTAMP', 'BLOB', 'BLOBID', 'DATE', 'TIME',
'BIGINT' , 'ARRAY'{$IFDEF IB7_UP}, 'BOOLEAN' {$ENDIF}
{$IFDEF FB25_UP}, 'NULL'{$ENDIF});
begin
Result:=cFieldTypes[TdwsUIBDataSet(DataSet).FQuery.Fields.FieldType[Index]];
end;
// AsString
//
procedure TdwsUIBDataField.AsString(var Result : String);
begin
Result:=TdwsUIBDataSet(DataSet).FQuery.Fields.AsString[Index];
end;
// AsInteger
//
function TdwsUIBDataField.AsInteger : Int64;
begin
Result:=TdwsUIBDataSet(DataSet).FQuery.Fields.AsInteger[Index];
end;
// AsFloat
//
function TdwsUIBDataField.AsFloat : Double;
begin
Result:=TdwsUIBDataSet(DataSet).FQuery.Fields.AsDouble[Index];
end;
// AsBoolean
//
function TdwsUIBDataField.AsBoolean : Boolean;
begin
Result:=TdwsUIBDataSet(DataSet).FQuery.Fields.AsBoolean[Index];
end;
// AsBlob
//
function TdwsUIBDataField.AsBlob : RawByteString;
begin
Result:=TdwsUIBDataSet(DataSet).FQuery.Fields.AsRawByteString[Index];
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
TdwsDatabase.RegisterDriver('UIB', TdwsUIBDataBaseFactory.Create);
end.
|
<?php
declare(strict_types=1);
namespace CurrencyConverter\Application\Exception;
class ApiDomainException extends \DomainException
{
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.spark.streaming.pubnub
import java.io.{Externalizable, ObjectInput, ObjectOutput}
import collection.JavaConverters._
import com.google.gson.JsonParser
import com.pubnub.api.PNConfiguration
import com.pubnub.api.PubNub
import com.pubnub.api.callbacks.SubscribeCallback
import com.pubnub.api.enums.PNReconnectionPolicy
import com.pubnub.api.models.consumer.PNStatus
import com.pubnub.api.models.consumer.pubsub.PNMessageResult
import com.pubnub.api.models.consumer.pubsub.PNPresenceEventResult
import org.apache.spark.internal.Logging
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.receiver.Receiver
import org.apache.spark.util.Utils
private[streaming]
class PubNubInputDStream(_ssc: StreamingContext,
val configuration: PNConfiguration,
val channels: Seq[String],
val channelGroups: Seq[String],
val timeToken: Option[Long],
val _storageLevel: StorageLevel)
extends ReceiverInputDStream[SparkPubNubMessage](_ssc) {
override def getReceiver(): Receiver[SparkPubNubMessage] = {
new PubNubReceiver(
new SparkPubNubNConfiguration(configuration), channels, channelGroups,
timeToken, _storageLevel
)
}
}
/**
* Wrapper class for PNConfiguration with only consumer-related, serializable properties.
* PubNub configuration model encapsulates various fields which are not serializable.
*/
private[pubnub]
class SparkPubNubNConfiguration(configuration: PNConfiguration) extends Serializable {
var origin: String = configuration.getOrigin
var subscribeTimeout: Integer = configuration.getSubscribeTimeout
var secure: Boolean = configuration.isSecure
var subscribeKey: String = configuration.getSubscribeKey
var publishKey: String = configuration.getPublishKey
var cipherKey: String = configuration.getCipherKey
var authKey: String = configuration.getAuthKey
var uuid: String = configuration.getUuid
var connectTimeout: Integer = configuration.getConnectTimeout
var filterExpression: String = configuration.getFilterExpression
var reconnectionPolicy: PNReconnectionPolicy = configuration.getReconnectionPolicy
var maximumReconnectionRetries: Integer = configuration.getMaximumReconnectionRetries
var maximumConnections: Integer = configuration.getMaximumConnections
def toConfiguration: PNConfiguration = {
val config = new PNConfiguration()
config.setOrigin(origin)
config.setSubscribeTimeout(subscribeTimeout)
config.setSecure(secure)
config.setSubscribeKey(subscribeKey)
config.setPublishKey(publishKey)
config.setCipherKey(cipherKey)
config.setAuthKey(authKey)
config.setUuid(uuid)
config.setConnectTimeout(connectTimeout)
config.setFilterExpression(filterExpression)
config.setReconnectionPolicy(reconnectionPolicy)
config.setMaximumReconnectionRetries(maximumReconnectionRetries)
config.setMaximumConnections(maximumConnections)
config
}
}
/**
* Wrapper class for PNMessageResult with a custom serialization process.
* PubNub message model uses GSON objects which are not serializable.
*/
class SparkPubNubMessage extends Externalizable {
var message: PNMessageResult = _
// PubNub does not support sending empty messages.
def getPayload: String = message.getMessage.toString
def getChannel: String = message.getChannel
def getPublisher: String = message.getPublisher
def getSubscription: String = message.getSubscription
// Convert to Unix timestamp.
def getTimestamp: Long = Math.ceil(message.getTimetoken / 10000).longValue()
override def writeExternal(out: ObjectOutput): Unit = Utils.tryOrIOException {
def writeVariableLength(data: Any): Unit = {
data match {
case null => out.writeInt(-1)
case d =>
val buffer = Utils.serialize(d)
out.writeInt(buffer.length)
out.write(buffer)
}
}
writeVariableLength(
if (message.getMessage != null) message.getMessage.toString else null
)
writeVariableLength(message.getChannel)
writeVariableLength(message.getPublisher)
writeVariableLength(message.getSubscription)
out.writeLong(message.getTimetoken)
}
override def readExternal(in: ObjectInput): Unit = Utils.tryOrIOException {
def readVariableLength(): Any = {
in.readInt match {
case -1 => null
case length =>
val buffer = new Array[Byte](length)
in.readFully(buffer)
Utils.deserialize(buffer)
}
}
val parser = new JsonParser
val builder = PNMessageResult.builder
readVariableLength() match {
case null =>
case data => builder.message(parser.parse(data.asInstanceOf[String]))
}
builder.channel(readVariableLength().asInstanceOf[String])
builder.publisher(readVariableLength().asInstanceOf[String])
builder.subscription(readVariableLength().asInstanceOf[String])
builder.timetoken(in.readLong())
message = builder.build()
}
}
private[pubnub]
class PubNubReceiver(configuration: SparkPubNubNConfiguration,
channels: Seq[String],
channelGroups: Seq[String],
timeToken: Option[Long],
storageLevel: StorageLevel)
extends Receiver[SparkPubNubMessage](storageLevel) with Logging {
var client: PubNub = _
override def onStart(): Unit = {
client = new PubNub(configuration.toConfiguration)
client.addListener(
new SubscribeCallback() {
def status(pubNub: PubNub, status: PNStatus): Unit = {
if (status.isError) {
log.error(s"Encountered PubNub error: $status.")
}
}
def message(pubNub: PubNub, message: PNMessageResult): Unit = {
val record = new SparkPubNubMessage
record.message = message
store(record)
}
def presence(pubNub: PubNub, presence: PNPresenceEventResult): Unit = {
}
}
)
val builder = client.subscribe()
.channels(channels.toList.asJava)
.channelGroups(channelGroups.toList.asJava)
if (timeToken.isDefined) {
builder.withTimetoken(timeToken.get)
}
builder.execute()
}
override def onStop(): Unit = {
client.unsubscribeAll()
client.destroy()
}
}
|
<?php
namespace app\admin\controller;
use think\Session;
use think\Controller;
use think\Request;
use think\Config;
use app\admin\controller\Common;
class Banner extends Common{
public function banner_list(){
$list=db('banner')->order('id desc')->paginate(4);
$page=$list->render();
$num=db('banner')->count();
$this->assign('num',$num);
$this->assign('page',$page);
$this->assign('list',$list);
return view();
}
public function banner_add(){
return view();
}
public function banner_insert(){
$list=input('post.');
$list['addtime']=time();
$list['state']=1;
$num=db('banner')->insert($list);
return $num;
}
public function banner_edit(){
$id=input('id');
$list=db('banner')->where('id',$id)->find();
$this->assign('list',$list);
return view();
}
public function banner_update(){
$list=input('post.');
$img=db('banner')->where('id',$list['id'])->find();
$picname=$img['imgname'];
if ($list['imgname']!=$picname) {
$list['imgname']=substr($list['imgname'], 9);
$num=db('banner')->where('id',$list['id'])->update($list);
if ($num>0) {
if (file_exists("uploads/{$picname}")) {
unlink("uploads/{$picname}");
}
return $num;
}
}else{
$list['imgname']=$picname;
$num=db('banner')->where('id',$list['id'])->update($list);
return $num;
}
}
public function banner_state(){
$id=input('id');
$list=db('banner')->where('id',$id)->find();
if ($list['state']=='1') {
$num=db('banner')->where('id',$id)->update(['state'=>2]);
return $num;
}else{
$num=db('banner')->where('id',$id)->update(['state'=>1]);
return $num;
}
}
public function banner_del(){
$id=input('id');
$list=db('banner')->where('id',$id)->find();
$picname=$list['imgname'];
$num=db('banner')->where('id',$id)->delete();
if (file_exists("uploads/{$picname}")) {
unlink("uploads/{$picname}");
}
return $num;
}
// 批量删除
public function deleteall(){
$getid = input('id'); //获取选择的复选框的值
// echo $getid;
if (!$getid)
$this->error('未选择记录'); //没选择就提示信息
$getids = explode(',', $getid); //选择一个以上,就用,把值连接起来(1,2,3)这样
$id = is_array($getid) ? $getids : $getid;
//如果是数组,就把用,连接起来的值覆给$id,否则就覆获取到的没有,号连接起来的值
//最后进行数据操作,
if(!is_array($id)){
$Result = db("banner")->delete($id);
}else{
foreach ($id as $v) {
$Result = db("banner")->delete($id['$v']);
}
}
$say = '删除成功';
if ($Result === false) {
$this->error('操作失败');
} else {
$this->success($say);
}
}
public function banner_uploads(){
$file =request()->file('pic');
// 移动到框架应用根目录/public/uploads/bigpic 目录下
$info = $file->move(ROOT_PATH . 'public' . DS .'uploads');
if($info){
return $info->getSaveName();
}else{
// 上传失败获取错误信息
return $file->getError();
}
}
}
|
ecall x3, x0, 5
ecall x4, x0, 5
blt x4, x3, Else
slli x4, x4, 3
beq x0, x0, Exit
Else: slli x3, x3, 3
beq x0, x0, Exit
Exit:
|
package com.salama.service.core.interfaces;
import com.salama.service.core.net.RequestWrapper;
/**
*
* @author XingGu Liu
*
*/
public interface RequestTracer {
public void init();
public void destroy();
/**
*
* @param request
*/
public void onRequest(RequestWrapper request);
}
|
import 'dart:developer';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
class LoginRestapi {
var url = 'http://jsserver.iptime.org:8080/login';
Future<int> KakaoLoginGet() async {
var response = await http.get(url);
if (response.statusCode == HttpStatus.ok) {
Map<String, dynamic> jsonresponse = convert.jsonDecode(response.body);
var userid = jsonresponse['userid'];
var useremail = jsonresponse['useremail'];
return HttpStatus.ok;
}
return HttpStatus.badRequest;
}
Future<int> KakaoLoginPost(String id, String email) async {
var request = {};
request['userid']=id;
request['useremail']=email;
var requestjson = convert.jsonEncode(request);
var response = await http.post(url, body:requestjson);
if (response.statusCode == HttpStatus.ok){
Map<String, dynamic> responsejson = convert.jsonDecode(response.body);
log('response.statusCode:${response.statusCode}');
log('response.body:${response.body}');
log('responsejson.tostring:${responsejson.toString()}');
return HttpStatus.ok;
}
return HttpStatus.badRequest;
}
Future<int> FacebookLoginPost(String id, String email) async {
var request = {};
request['userid']=id;
request['useremail']=email;
var requestjson = convert.jsonEncode(request);
var response = await http.post(url, body:requestjson);
if (response.statusCode == HttpStatus.ok){
Map<String, dynamic> responsejson = convert.jsonDecode(response.body);
log('response.statusCode:${response.statusCode}');
log('response.body:${response.body}');
log('responsejson.tostring:${responsejson.toString()}');
return HttpStatus.ok;
}
return HttpStatus.badRequest;
}
}
|
INSERT OR REPLACE INTO files (key, time_stamp, data) VALUES (?, ?, ?)
|
# All cities in a country (Morocco) organised by largest population to the smallest
| Name | CountryCode | District | Population |
| :--- | :--- | :--- | :---: |
|Casablanca|MAR|Casablanca|2940623|
|Rabat|MAR|Rabat-Salé-Zammour-Z|623457|
|Marrakech|MAR|Marrakech-Tensift-Al|621914|
|Fès|MAR|Fès-Boulemane|541162|
|Tanger|MAR|Tanger-Tétouan|521735|
|Salé|MAR|Rabat-Salé-Zammour-Z|504420|
|Meknès|MAR|Meknès-Tafilalet|460000|
|Oujda|MAR|Oriental|365382|
|Kénitra|MAR|Gharb-Chrarda-Béni H|292600|
|Tétouan|MAR|Tanger-Tétouan|277516|
|Safi|MAR|Doukkala-Abda|262300|
|Agadir|MAR|Souss Massa-Draâ|155244|
|Mohammedia|MAR|Casablanca|154706|
|Khouribga|MAR|Chaouia-Ouardigha|152090|
|Beni-Mellal|MAR|Tadla-Azilal|140212|
|Témara|MAR|Rabat-Salé-Zammour-Z|126303|
|El Jadida|MAR|Doukkala-Abda|119083|
|Nador|MAR|Oriental|112450|
|Ksar el Kebir|MAR|Tanger-Tétouan|107065|
|Settat|MAR|Chaouia-Ouardigha|96200|
|Taza|MAR|Taza-Al Hoceima-Taou|92700|
|El Araich|MAR|Tanger-Tétouan|90400|
|
/* Copyright (C) 2010 FlameScripts <http://www.flame-wow.org/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Sladran
SD%Complete: 75%
SDComment:
SDCategory: Gundrak
EndScriptData */
#include "precompiled.h"
#include "gundrak.h"
enum
{
SAY_AGGRO = -1604000,
SAY_SUMMON_SNAKE = -1604001,
SAY_SUMMON_CONSTRICTOR = -1604002,
SAY_SLAY_1 = -1604003,
SAY_SLAY_2 = -1604004,
SAY_SLAY_3 = -1604005,
SAY_DEATH = -1604006,
EMOTE_NOVA = -1604007,
// Slad'Ran spells
SPELL_POISON_NOVA = 55081,
SPELL_POISON_NOVA_H = 59842,
SPELL_POWERFUL_BITE = 48287,
SPELL_POWERFUL_BITE_H = 59840,
SPELL_VENOM_BOLT = 54970,
SPELL_VENOM_BOLT_H = 59839,
// Summon spells
SPELL_SUMMON_VIPER = 55060,
SPELL_SUMMON_CONSTRICTOR = 54969,
SPELL_GRIP_OF_SLADRAN = 55093,
SPELL_GRIP_OF_SLADRAN_H = 61474,
NPC_SLADRAN_CONSTRICTOR = 29713,
NPC_SLADRAN_VIPER = 29680,
NPC_SNAKE_WRAP = 29742,
NPC_SLADRAN_SUMMON_TARGET = 29682
};
/*######
## mob_sladran_summon_target
######*/
struct FLAMEMU_DLL_DECL mob_sladran_summon_targetAI : public ScriptedAI
{
mob_sladran_summon_targetAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
Reset();
}
ScriptedInstance* m_pInstance;
void Reset() {}
void MoveInLineOfSight(Unit* pWho) {}
void AttackStart(Unit* pWho) {}
void JustSummoned(Creature* pSummoned)
{
if (!m_pInstance)
return;
if (Creature* pSladran = ((Creature*)Unit::GetUnit(*m_creature, m_pInstance->GetData64(NPC_SLADRAN))))
{
float fPosX, fPosY, fPosZ;
pSladran->GetPosition(fPosX, fPosY, fPosZ);
pSummoned->GetMotionMaster()->MovePoint(0, fPosX, fPosY, fPosZ);
}
}
void UpdateAI(const uint32 diff) {}
};
CreatureAI* GetAI_mob_sladran_summon_target(Creature* pCreature)
{
return new mob_sladran_summon_targetAI(pCreature);
}
/*######
## boss_sladran
######*/
struct FLAMEMU_DLL_DECL boss_sladranAI : public ScriptedAI
{
boss_sladranAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty();
Reset();
}
ScriptedInstance* m_pInstance;
bool m_bIsRegularMode;
uint32 m_uiSummonTimer;
uint32 m_uiPoisonNovaTimer;
uint32 m_uiPowerfulBiteTimer;
uint32 m_uiVenomBoltTimer;
void Reset()
{
m_uiSummonTimer = m_bIsRegularMode ? 5000 : 3000;
m_uiPoisonNovaTimer = 22000;
m_uiPowerfulBiteTimer = 10000;
m_uiVenomBoltTimer = 15000;
}
void Aggro(Unit* pWho)
{
DoScriptText(SAY_AGGRO, m_creature);
if (m_pInstance)
m_pInstance->SetData(TYPE_SLADRAN, IN_PROGRESS);
}
void KilledUnit(Unit* pVictim)
{
switch(urand(0, 2))
{
case 0: DoScriptText(SAY_SLAY_1, m_creature); break;
case 1: DoScriptText(SAY_SLAY_2, m_creature); break;
case 2: DoScriptText(SAY_SLAY_3, m_creature); break;
}
}
void JustDied(Unit* pKiller)
{
DoScriptText(SAY_DEATH, m_creature);
if (m_pInstance)
m_pInstance->SetData(TYPE_SLADRAN, DONE);
}
Creature* SelectRandomCreatureOfEntryInRange(uint32 uiEntry, float fRange)
{
std::list<Creature* > lCreatureList;
GetCreatureListWithEntryInGrid(lCreatureList, m_creature, uiEntry, fRange);
if (lCreatureList.empty())
return NULL;
std::list<Creature* >::iterator iter = lCreatureList.begin();
advance(iter, urand(0, lCreatureList.size()-1));
return *iter;
}
void UpdateAI(const uint32 uiDiff)
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
if (m_uiPoisonNovaTimer < uiDiff)
{
DoScriptText(EMOTE_NOVA, m_creature);
DoCastSpellIfCan(m_creature->getVictim(),m_bIsRegularMode ? SPELL_POISON_NOVA : SPELL_POISON_NOVA_H);
m_uiPoisonNovaTimer = 22000;
}
else
m_uiPoisonNovaTimer -= uiDiff;
if (m_uiSummonTimer < uiDiff)
{
if (Creature* pSummonTarget = SelectRandomCreatureOfEntryInRange(NPC_SLADRAN_SUMMON_TARGET, 75.0f))
{
if (urand(0, 3))
{
// we don't want to get spammed
if (!urand(0, 4))
DoScriptText(SAY_SUMMON_CONSTRICTOR, m_creature);
pSummonTarget->CastSpell(pSummonTarget, SPELL_SUMMON_CONSTRICTOR, false);
}
else
{
// we don't want to get spammed
if (!urand(0, 4))
DoScriptText(SAY_SUMMON_SNAKE, m_creature);
pSummonTarget->CastSpell(pSummonTarget, SPELL_SUMMON_VIPER, false);
}
}
m_uiSummonTimer = m_bIsRegularMode ? 5000 : 3000;
}
else
m_uiSummonTimer -= uiDiff;
if (m_uiPowerfulBiteTimer < uiDiff)
{
DoCastSpellIfCan(m_creature->getVictim(), m_bIsRegularMode ? SPELL_POWERFUL_BITE : SPELL_POWERFUL_BITE_H);
m_uiPowerfulBiteTimer = 10000;
}
else
m_uiPowerfulBiteTimer -= uiDiff;
if (m_uiVenomBoltTimer < uiDiff)
{
if (Unit* pTarget = SelectUnit(SELECT_TARGET_RANDOM, 0))
DoCastSpellIfCan(pTarget, m_bIsRegularMode ? SPELL_VENOM_BOLT : SPELL_VENOM_BOLT_H);
m_uiVenomBoltTimer = 15000;
}
else
m_uiVenomBoltTimer -= uiDiff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_sladran(Creature* pCreature)
{
return new boss_sladranAI(pCreature);
}
void AddSC_boss_sladran()
{
Script* newscript;
newscript = new Script;
newscript->Name = "boss_sladran";
newscript->GetAI = &GetAI_boss_sladran;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_sladran_summon_target";
newscript->GetAI = &GetAI_mob_sladran_summon_target;
newscript->RegisterSelf();
}
|
require "optparse"
require_relative "../config/environment"
parser = OptionParser.new { |args|
args.on "-f", "--fund FUND"
args.on "-o", "--organisation ORGANISATION"
args.on "-q", "--quarter QUARTER", Integer
args.on "-y", "--year YEAR", Integer
args.on "-i", "--input FILE"
}
options = {}
parser.parse!(into: options)
fund = Activity.fund.by_roda_identifier(options.fetch(:fund))
organisation = Organisation.find_by(name: options.fetch(:organisation))
unless fund
warn "Could not find fund with RODA identifier '#{options.fetch(:fund)}'"
exit 1
end
unless organisation
warn "Could not find organisation with name '#{options.fetch(:organisation)}'"
exit 1
end
def zero_option_to_nil(options, field)
value = options.fetch(field)
value == 0 ? nil : value
end
report = Report.find_by(
fund: fund,
organisation: organisation,
financial_quarter: zero_option_to_nil(options, :quarter),
financial_year: zero_option_to_nil(options, :year),
)
unless report
warn "Could not find report with the given parameters"
exit 1
end
puts "\nRunning import with the following report:\n\n"
puts " id: #{report.id}"
puts " description: #{report.description}"
puts " fund: #{report.fund.roda_identifier}"
puts " organisation: #{report.organisation.name}"
puts " quarter: #{report.financial_quarter_and_year}"
puts " state: #{report.state}"
puts "\nIs this correct? [y/n]"
confirmation = gets
exit unless confirmation.strip == "y"
importer = ImportForecasts.new(report: report)
rows = CSV.parse(File.read(options.fetch(:input)), headers: true)
importer.import(rows)
importer.errors.each do |error|
warn "Line #{error.csv_row}, column '#{error.column}': #{error.message}"
end
if importer.errors.empty?
exit 0
else
exit 1
end
|
# Neighbor finders
export
NoNeighborFinder,
find_neighbors,
DistanceNeighborFinder,
DistanceVecNeighborFinder,
TreeNeighborFinder,
CellListMapNeighborFinder
"""
NoNeighborFinder()
Placeholder neighbor finder that returns no neighbors.
When using this neighbor finder, ensure that `nl_only` for the interactions is
set to `false`.
"""
struct NoNeighborFinder <: NeighborFinder end
"""
find_neighbors(system, neighbor_finder, current_neighbors=nothing, step_n=0; parallel=true)
Obtain a list of close atoms in a system.
Custom neighbor finders should implement this function.
"""
function find_neighbors(s::System,
nf::NoNeighborFinder,
current_neighbors=nothing,
step_n::Integer=0;
kwargs...)
return nothing
end
Base.show(io::IO, neighbor_finder::NoNeighborFinder) = print(io, typeof(neighbor_finder))
"""
DistanceNeighborFinder(; nb_matrix, matrix_14, n_steps, dist_cutoff)
Find close atoms by distance.
"""
struct DistanceNeighborFinder{D} <: NeighborFinder
nb_matrix::BitArray{2}
matrix_14::BitArray{2}
n_steps::Int
dist_cutoff::D
end
function DistanceNeighborFinder(;
nb_matrix,
matrix_14=falses(size(nb_matrix)),
n_steps=10,
dist_cutoff)
return DistanceNeighborFinder{typeof(dist_cutoff)}(nb_matrix, matrix_14, n_steps, dist_cutoff)
end
function find_neighbors(s::System,
nf::DistanceNeighborFinder,
current_neighbors=nothing,
step_n::Integer=0;
parallel::Bool=true)
!iszero(step_n % nf.n_steps) && return current_neighbors
if isnothing(current_neighbors)
neighbors = NeighborList()
else
neighbors = current_neighbors
end
empty!(neighbors)
sqdist_cutoff = nf.dist_cutoff ^ 2
if parallel && nthreads() > 1
nl_threads = [Tuple{Int, Int, Bool}[] for i in 1:nthreads()]
@threads for i in 1:length(s)
nl = nl_threads[threadid()]
ci = s.coords[i]
nbi = @view nf.nb_matrix[:, i]
w14i = @view nf.matrix_14[:, i]
for j in 1:(i - 1)
r2 = sum(abs2, vector(ci, s.coords[j], s.box_size))
if r2 <= sqdist_cutoff && nbi[j]
push!(nl, (i, j, w14i[j]))
end
end
end
for nl in nl_threads
append!(neighbors, nl)
end
else
for i in 1:length(s)
ci = s.coords[i]
nbi = @view nf.nb_matrix[:, i]
w14i = @view nf.matrix_14[:, i]
for j in 1:(i - 1)
r2 = sum(abs2, vector(ci, s.coords[j], s.box_size))
if r2 <= sqdist_cutoff && nbi[j]
push!(neighbors, (i, j, w14i[j]))
end
end
end
end
return neighbors
end
"""
DistanceVecNeighborFinder(; nb_matrix, matrix_14, n_steps, dist_cutoff)
Find close atoms by distance in a GPU and differentiable safe manner.
"""
struct DistanceVecNeighborFinder{D, B, I} <: NeighborFinder
nb_matrix::B
matrix_14::B
n_steps::Int
dist_cutoff::D
is::I
js::I
end
function DistanceVecNeighborFinder(;
nb_matrix,
matrix_14=falses(size(nb_matrix)),
n_steps=10,
dist_cutoff)
n_atoms = size(nb_matrix, 1)
if isa(nb_matrix, CuArray)
is = cu(hcat([collect(1:n_atoms) for i in 1:n_atoms]...))
js = cu(permutedims(is, (2, 1)))
m14 = cu(matrix_14)
else
is = hcat([collect(1:n_atoms) for i in 1:n_atoms]...)
js = permutedims(is, (2, 1))
m14 = matrix_14
end
return DistanceVecNeighborFinder{typeof(dist_cutoff), typeof(nb_matrix), typeof(is)}(
nb_matrix, m14, n_steps, dist_cutoff, is, js)
end
# Find the boundaries of an ordered list of integers
function findboundaries(nbs_ord, n_atoms)
inds = zeros(Int, n_atoms)
atom_i = 1
for (nb_i, nb_ai) in enumerate(nbs_ord)
while atom_i < nb_ai
inds[atom_i] = nb_i
atom_i += 1
end
end
while atom_i < (n_atoms + 1)
inds[atom_i] = length(nbs_ord) + 1
atom_i += 1
end
return inds
end
function find_neighbors(s::System,
nf::DistanceVecNeighborFinder,
current_neighbors=nothing,
step_n::Integer=0;
kwargs...)
!iszero(step_n % nf.n_steps) && return current_neighbors
n_atoms = length(s)
sqdist_cutoff = nf.dist_cutoff ^ 2
sqdists = sqdistance.(nf.is, nf.js, (s.coords,), (s.box_size,))
close = sqdists .< sqdist_cutoff
close_nb = close .* nf.nb_matrix
eligible = tril(close_nb, -1)
fa = Array(findall(!iszero, eligible))
nbsi, nbsj = getindex.(fa, 1), getindex.(fa, 2)
order_i = sortperm(nbsi)
weights_14 = @view nf.matrix_14[fa]
nbsi_ordi, nbsj_ordi = nbsi[order_i], nbsj[order_i]
sortperm_j = sortperm(nbsj_ordi)
weights_14_ordi = @view weights_14[order_i]
atom_bounds_i = findboundaries(nbsi_ordi, n_atoms)
atom_bounds_j = findboundaries(view(nbsj_ordi, sortperm_j), n_atoms)
return NeighborListVec(nbsi_ordi, nbsj_ordi, atom_bounds_i, atom_bounds_j,
sortperm_j, weights_14_ordi)
end
function allneighbors(n_atoms)
nbs_all = findall(!iszero, tril(ones(Bool, n_atoms, n_atoms), -1))
nbsi, nbsj = getindex.(nbs_all, 1), getindex.(nbs_all, 2)
order_i = sortperm(nbsi)
nbsi_ordi, nbsj_ordi = nbsi[order_i], nbsj[order_i]
sortperm_j = sortperm(nbsj_ordi)
atom_bounds_i = findboundaries(nbsi_ordi, n_atoms)
atom_bounds_j = findboundaries(view(nbsj_ordi, sortperm_j), n_atoms)
weights_14 = nothing
return NeighborListVec(nbsi_ordi, nbsj_ordi, atom_bounds_i, atom_bounds_j,
sortperm_j, weights_14)
end
"""
TreeNeighborFinder(; nb_matrix, matrix_14, n_steps, dist_cutoff)
Find close atoms by distance using a tree search.
"""
struct TreeNeighborFinder{D} <: NeighborFinder
nb_matrix::BitArray{2}
matrix_14::BitArray{2}
n_steps::Int
dist_cutoff::D
end
function TreeNeighborFinder(;
nb_matrix,
matrix_14=falses(size(nb_matrix)),
n_steps=10,
dist_cutoff)
return TreeNeighborFinder{typeof(dist_cutoff)}(nb_matrix, matrix_14, n_steps, dist_cutoff)
end
function find_neighbors(s::System,
nf::TreeNeighborFinder,
current_neighbors=nothing,
step_n::Integer=0;
parallel::Bool=true)
!iszero(step_n % nf.n_steps) && return current_neighbors
if isnothing(current_neighbors)
neighbors = NeighborList()
else
neighbors = current_neighbors
end
empty!(neighbors)
dist_unit = unit(first(first(s.coords)))
bv = ustrip.(dist_unit, s.box_size)
btree = BallTree(ustripvec.(s.coords), PeriodicEuclidean(bv))
dist_cutoff = ustrip(dist_unit, nf.dist_cutoff)
if parallel && nthreads() > 1
nl_threads = [Tuple{Int, Int, Bool}[] for i in 1:nthreads()]
@threads for i in 1:length(s)
nl = nl_threads[threadid()]
ci = ustrip.(s.coords[i])
nbi = @view nf.nb_matrix[:, i]
w14i = @view nf.matrix_14[:, i]
idxs = inrange(btree, ci, dist_cutoff, true)
for j in idxs
if nbi[j] && i > j
push!(nl, (i, j, w14i[j]))
end
end
end
for nl in nl_threads
append!(neighbors, nl)
end
else
for i in 1:length(s)
ci = ustrip.(s.coords[i])
nbi = @view nf.nb_matrix[:, i]
w14i = @view nf.matrix_14[:, i]
idxs = inrange(btree, ci, dist_cutoff, true)
for j in idxs
if nbi[j] && i > j
push!(neighbors, (i, j, w14i[j]))
end
end
end
end
return neighbors
end
# Find neighbor lists using CellListMap.jl
"""
CellListMapNeighborFinder(; nb_matrix, matrix_14, n_steps, dist_cutoff, x0, unit_cell)
Find close atoms by distance, and store auxiliary arrays for in-place threading. `x0` and `unit_cell`
are optional initial coordinates and system unit cell that improve the first approximation of the
cell list structure. The unit cell can be provided as a three-component vector of box sides on each
direction, in which case the unit cell is considered `OrthorhombicCell`, or as a unit cell matrix,
in which case the cell is considered a general `TriclinicCell` by the cell list algorithm.
### Example
```julia-repl
julia> coords
15954-element Vector{SVector{3, Quantity{Float64, 𝐋, Unitful.FreeUnits{(nm,), 𝐋, nothing}}}}:
[2.5193063341012127 nm, 3.907448346081021 nm, 4.694954671434135 nm]
[2.4173958848835233 nm, 3.916034913604175 nm, 4.699661024574953 nm]
⋮
[1.818842280373283 nm, 5.592152965227421 nm, 4.992100424805031 nm]
[1.7261366568663976 nm, 5.610326185704369 nm, 5.084523386833478 nm]
julia> box_size
3-element SVector{3, Quantity{Float64, 𝐋, Unitful.FreeUnits{(nm,), 𝐋, nothing}}} with indices SOneTo(3):
5.676 nm
5.6627 nm
6.2963 nm
julia> neighbor_finder = CellListMapNeighborFinder(
nb_matrix=s.neighbor_finder.nb_matrix, matrix_14=s.neighbor_finder.matrix_14,
n_steps=10, dist_cutoff=1.2u"nm",
x0 = coords, unit_cell = box_size
)
CellListMapNeighborFinder{Quantity{Float64, 𝐋, Unitful.FreeUnits{(nm,), 𝐋, nothing}}, 3, Float64}
Size of nb_matrix = (15954, 15954)
n_steps = 10
dist_cutoff = 1.2 nm
```
"""
mutable struct CellListMapNeighborFinder{N, T} <: NeighborFinder
nb_matrix::BitArray{2}
matrix_14::BitArray{2}
n_steps::Int
dist_cutoff::T
# Auxiliary arrays for multi-threaded in-place updating of the lists
cl::CellListMap.CellList{N, T}
aux::CellListMap.AuxThreaded{N, T}
neighbors_threaded::Vector{NeighborList}
end
# This function sets up the box structure for CellListMap. It uses the unit cell
# if it is given, or guesses a box size from the number of particles, assuming
# that the atomic density is similar to that of liquid water at ambient conditions.
function CellListMapNeighborFinder(;
nb_matrix,
matrix_14=falses(size(nb_matrix)),
n_steps=10,
x0=nothing,
unit_cell=nothing,
number_of_batches=(0, 0), # (0, 0): use default heuristic
dist_cutoff::T) where T
np = size(nb_matrix, 1)
if isnothing(unit_cell)
if unit(dist_cutoff) == NoUnits
side = max(2 * dist_cutoff, (np * 0.01) ^ (1 / 3))
else
side = max(2 * dist_cutoff, uconvert(unit(dist_cutoff), (np * 0.01u"nm^3") ^ (1 / 3)))
end
sides = SVector(side, side, side)
box = CellListMap.Box(sides, dist_cutoff)
else
box = CellListMap.Box(unit_cell, dist_cutoff)
end
if isnothing(x0)
x = [ustrip.(box.unit_cell_max) .* rand(SVector{3, T}) for _ in 1:np]
else
x = x0
end
# Construct the cell list for the first time, to allocate
cl = CellList(x, box; parallel=true, nbatches=number_of_batches)
return CellListMapNeighborFinder{3, T}(
nb_matrix, matrix_14, n_steps, dist_cutoff,
cl, CellListMap.AuxThreaded(cl),
[NeighborList(0, [(0, 0, false)]) for _ in 1:CellListMap.nbatches(cl)])
end
"""
push_pair!(neighbor::NeighborList, i, j, nb_matrix, matrix_14)
Add pair to pair list. If the buffer size is large enough, update element, otherwise
push new element to `neighbor.list`.
"""
function push_pair!(neighbors::NeighborList, i, j, nb_matrix, matrix_14)
if nb_matrix[i, j]
push!(neighbors, (Int(i), Int(j), matrix_14[i, j]))
end
return neighbors
end
# This is only called in the parallel case
function reduce_pairs(neighbors::NeighborList, neighbors_threaded::Vector{NeighborList})
neighbors.n = 0
for i in 1:length(neighbors_threaded)
append!(neighbors, neighbors_threaded[i])
end
return neighbors
end
"""
find_neighbors(s::System,
nf::CellListMapNeighborFinder,
current_neighbors=nothing,
step_n::Integer=0;
parallel::Bool=true)
Find neighbors using `CellListMap`, without in-place updating. Should be called only
the first time the cell lists are built. Modifies the mutable `nf` structure.
"""
function find_neighbors(s::System,
nf::CellListMapNeighborFinder,
current_neighbors=nothing,
step_n::Integer=0;
parallel::Bool=true)
!iszero(step_n % nf.n_steps) && return current_neighbors
if isnothing(current_neighbors)
neighbors = NeighborList()
else
neighbors = current_neighbors
end
aux = nf.aux
cl = nf.cl
neighbors.n = 0
neighbors_threaded = nf.neighbors_threaded
if parallel
for i in 1:length(neighbors_threaded)
neighbors_threaded[i].n = 0
end
else
neighbors_threaded[1].n = 0
end
box = CellListMap.Box(s.box_size, nf.dist_cutoff; lcell=1)
cl = UpdateCellList!(s.coords, box, cl, aux; parallel=parallel)
map_pairwise!(
(x, y, i, j, d2, pairs) -> push_pair!(pairs, i, j, nf.nb_matrix, nf.matrix_14),
neighbors, box, cl;
reduce=reduce_pairs,
output_threaded=neighbors_threaded,
parallel=parallel
)
nf.cl = cl
return neighbors
end
function Base.show(io::IO, neighbor_finder::NeighborFinder)
println(io, typeof(neighbor_finder))
println(io," Size of nb_matrix = " , size(neighbor_finder.nb_matrix))
println(io," n_steps = " , neighbor_finder.n_steps)
print(io," dist_cutoff = ", neighbor_finder.dist_cutoff)
end
|
# The Book of Ruby - http://www.sapphiresteel.com
puts("What shall we call this class? ")
className = gets.strip().capitalize() # make sure class name starts with capital letter
Object.const_set(className,Class.new) # create new class
puts("I'll give it a method called 'myname'" )
className = Object.const_get(className)
className::module_eval{ define_method(:myname){
puts("The name of my class is '#{self.class}'" ) }
}
x = className.new
x.myname
|
atc --model="./Wav2word.pb" \
--output_type=FP32 \
--output="./Wav2word_tensorflow_aipp" \
--framework=3 \
--soc_version=Ascend310
|
import path from 'path';
import inquirer from 'inquirer';
import disallowUndefined from 'lib/proxy/disallowUndefined';
import {PropertyNotDefinedError} from 'lib/exceptions/PropertyNotDefinedError';
import {ObjectExtras} from 'lib/helpers/ObjectExtra';
import {RandTypes} from 'lib/helpers/RandTypes';
export default async function selectorCmd(args, options, logger, generator) {
const selectorModule = require(path.join(options.root, args.path));
const generationObject = {
modulePath: args.path,
methods: [],
};
for (const methodName in selectorModule) {
if (!selectorModule.hasOwnProperty(methodName)) {
continue;
}
const selectorMethod = selectorModule[methodName];
const methodData = {
name: methodName,
};
try {
const mock = resolveSelectorMock(selectorMethod);
const preResult = selectorMethod(mock);
const randType = await chooseReturnType(methodName);
const finalResult = RandTypes[randType];
ObjectExtras.findAndReplace(mock, preResult, finalResult);
Object.assign(methodData, {
mock,
result: finalResult,
});
} catch (e) {
logger.error(`Could not generate tests for "${methodName}": ${e.toString()}`);
}
generationObject.methods.push(methodData);
}
generator.generate('selector.unit.spec.js', generationObject);
};
function chooseReturnType(selectorName) {
return inquirer.prompt([{
type: 'list',
name: 'type',
message: `Choose return type for "${selectorName}" selector`,
choices: RandTypes.LIST,
}]).then(response => response.type);
}
function resolveSelectorMock(selectorMethod, _resolvedMock = {}, _nestLevel = 0) {
const pingPongMock = new Proxy(_resolvedMock, disallowUndefined);
if (_nestLevel === 5) {
throw new Error(`Nest level exceeded`);
}
try {
selectorMethod(pingPongMock);
return _resolvedMock;
} catch (e) {
if (e instanceof PropertyNotDefinedError) {
const property = e.property;
const target = e.target;
target[property] = {};
return resolveSelectorMock(selectorMethod, _resolvedMock, _nestLevel + 1);
}
throw e;
}
}
|
<?php
namespace OK\Uml\Parser\Factory;
use OK\Uml\Entity\NodeInterface;
use OK\Uml\Entity\ArgumentNode;
/**
* @author Oleg Kochetkov <oleg.kochetkov999@yandex.ru>
*/
class ArgumentFactory implements NodeFactoryInterface
{
/**
* @param \ReflectionParameter $param
* @param array $args
*
* @return ArgumentNode
* @throws \ReflectionException
*/
public function create($param, array $args = []): NodeInterface
{
$argumentNode = new ArgumentNode();
$argumentNode->name = $param->getName();
if (!empty($args) && isset($args[$param->getPosition()])) {
$argumentNode->type = $args[$param->getPosition()][0];
} else if ($param->isDefaultValueAvailable()) {
$argumentNode->type = gettype($param->getDefaultValue());
} else if ($param->isArray()) {
$argumentNode->type = 'array';
}
return $argumentNode;
}
}
|
// Flutter imports:
import 'package:afya_moja_core/afya_moja_core.dart';
import 'package:afya_moja_core/src/app_asset_strings.dart';
import 'package:afya_moja_core/src/app_strings.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
enum GenericNoDataTypes { noData, error }
/// [GenericErrorWidget] is a generic used to purposefully communicate that
/// the value of the data received from the API was [null] or it missed
/// key properties that are of a valid response.
/// Because of it;s generic natures, this widget handles the following types
/// of error defined under [GenericNoDataTypes] enum
///
/// - AbsentData -> no data completely
/// - ErrorInData -> there was an error in the received data or the API
/// returned with an error attribute
///
/// When the errorType is of type [ErrorInData] a specific illustration will
/// be shown in place of the default one.
///
/// Always, a [recoverCallback] can be defined to offset the user a way out
class GenericErrorWidget extends StatelessWidget {
const GenericErrorWidget({
Key? key,
required this.recoverCallback,
this.messageTitle,
this.messageBody,
this.actionText = retryString,
this.align,
this.type = GenericNoDataTypes.error,
this.headerIconSvgUrl,
this.padding,
this.actionKey,
this.showPrimaryButton = true,
}) : super(key: key);
/// [actionText]
final String actionText;
/// [align] where the error widget should align
final MainAxisAlignment? align;
/// [messageTitle] to show in the body, in place of the default one
final List<TextSpan>? messageBody;
/// [messageTitle] to show on the title, in place of the default one
final String? messageTitle;
/// [recoverCallback] the function to be called to recover from the error.
/// Default to [null]
final VoidCallback? recoverCallback;
/// [type] the type of error. Defaults to [noData]
final GenericNoDataTypes type;
final String? headerIconSvgUrl;
final EdgeInsets? padding;
final Key? actionKey;
final bool showPrimaryButton;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: padding ?? const EdgeInsets.all(18.0),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: align ?? MainAxisAlignment.center,
children: <Widget>[
largeVerticalSizedBox,
if (type == GenericNoDataTypes.error)
SvgPicture.asset(
headerIconSvgUrl ?? errorPageImageSvgPath,
height: MediaQuery.of(context).size.height / 3,
),
Center(
child: Column(
children: <Widget>[
Text.rich(
TextSpan(
children: <TextSpan>[
TextSpan(
text: messageTitle ?? getErrorMessage(),
style: veryBoldSize20Text(),
),
const TextSpan(text: '\n\n'),
...messageBody ??
<TextSpan>[
TextSpan(
text: defaultUserFriendlyMessage,
style: normalSize16Text(
const Color(0xff707070),
),
)
]
],
),
textAlign: TextAlign.center,
),
mediumVerticalSizedBox,
if (showPrimaryButton)
SizedBox(
width: double.infinity,
height: 48,
child: MyAfyaHubPrimaryButton(
customRadius: 8.0,
buttonKey: actionKey,
buttonColor: Theme.of(context).primaryColor,
textColor: Colors.white,
onPressed: recoverCallback,
text: actionText,
),
),
],
),
),
],
),
),
),
),
);
}
}
|
#!/bin/bash
apt-get -y install build-essential
apt-get -y install scons
apt-get -y install automake
apt-get -y install autoconf
apt-get -y install m4
apt-get -y install perl
apt-get -y install flex
apt-get -y install bison
apt-get -y install byacc
#apt-get -y install libconfig-dev
#apt-get -y install libconfig++-dev
apt-get -y install libhdf5-dev
apt-get -y install libelf-dev
ln -s /usr/include/asm-generic /usr/include/asm
|
# 文件的读写
### <1>写数据(write)
使用write()可以完成向文件写入数据
demo: 新建一个文件 `file_write_test.py`,向其中写入如下代码:
```python
f = open('test.txt', 'w')
f.write('hello world, i am here!\n' * 5)
f.close()
```
运行之后会在`file_write_test.py`文件所在的路径中创建一个文件`test.txt`,并写入内容,运行效果显示如下:
[ 补图 ]
注意:
- 如果文件不存在,那么创建;如果存在那么就先清空,然后写入数据
### <2>读数据(read)
使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据
demo: 新建一个文件`file_read_test.py`,向其中写入如下代码:
```python
f = open('test.txt', 'r')
content = f.read(5) # 最多读取5个数据
print(content)
print("-"*30) # 分割线,用来测试
content = f.read() # 从上次读取的位置继续读取剩下的所有的数据
print(content)
f.close() # 关闭文件,这个可是个好习惯哦
```
运行现象:
```
hello
------------------------------
world, i am here!
```
注意:
- 如果用open打开文件时,如果使用的"r",那么可以省略 `open('test.txt')`
### <3>读数据(readline)
readline只用来读取一行数据。
```python
f = open('test.txt', 'r')
content = f.readline()
print("1:%s" % content)
content = f.readline()
print("2:%s" % content)
f.close()
Copy
```
### <4>读数据(readlines)
readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行为列表的一个元素。
```python
f = open('test.txt', 'r')
content = f.readlines()
print(type(content))
for temp in content:
print(temp)
f.close()
```
## 指针定位
- tell() 方法用来显示当前指针的位置
```python
f = open('test.txt')
print(f.read(10)) # read 指定读取的字节数
print(f.tell()) # tell()方法显示当前文件指针所在的文字
f.close()
```
seek(offset,whence) 方法用来重新设定指针的位置。
- offset:表示偏移量
- whence:只能传入012中的一个数字。
- 0表示从文件头开始
- 1表示从当前位置开始
- 2 表示从文件的末尾开始
```python
f = open('test.txt','rb') # 需要指定打开模式为rb,只读二进制模式
print(f.read(3))
print(f.tell())
f.seek(2,0) # 从文件的开头开始,跳过两个字节
print(f.read())
f.seek(1,1) # 从当前位置开始,跳过一个字节
print(f.read())
f.seek(-4,2) # 从文件末尾开始,往前跳过四个字节
print(f.read())
f.close()
```
|
#!/bin/bash
[ "$DEBUG" ] && set -x
set -eo pipefail
dir="$(dirname "$(readlink -f "$BASH_SOURCE")")"
image="$1"
# Use a client image with curl for testing
clientImage='buildpack-deps:jessie-curl'
# Create an instance of the container-under-test
serverImage="$("$dir/../image-name.sh" librarytest/rapidoid-hello-web "$image")"
"$dir/../docker-build.sh" "$dir" "$serverImage" <<EOD
FROM $image
RUN mkdir -p /app/static
COPY dir/index.html /app/static/
EOD
cid="$(docker run -d "$serverImage" app.services=ping)"
trap "docker rm -vf $cid > /dev/null" EXIT
_request() {
local method="$1"
shift
local url="${1#/}"
shift
docker run --rm --link "$cid":rapidoid "$clientImage" \
curl -fs -X"$method" "$@" "http://rapidoid:8888/$url"
}
# Make sure that Rapidoid is listening on port 8888
. "$dir/../../retry.sh" --tries 40 --sleep 0.25 '[ "$(_request GET / --output /dev/null || echo $?)" != 7 ]'
# Make sure that Rapidoid serves the static page index.html
[ "$(_request GET "/")" = "Hello world!" ]
[ "$(_request GET "/index.html")" = "Hello world!" ]
# Make sure that Rapidoid's built-in Ping service works correctly
[ "$(_request GET "/rapidoid/ping")" = "OK" ]
|
namespace Vorbis
{
//https://github.com/knot3/OggSharp/tree/master/OggSharp
//https://github.com/yebgi83/OggVorbisSharp
//https://github.com/shilrobot/oggvorbis
}
|
package net.corda.vega.portfolio
import net.corda.core.contracts.*
import net.corda.core.identity.Party
import net.corda.core.internal.sum
import net.corda.core.messaging.CordaRPCOps
import net.corda.core.messaging.vaultQueryBy
import net.corda.core.node.services.vault.QueryCriteria
import net.corda.vega.contracts.IRSState
import net.corda.vega.contracts.SwapData
import java.math.BigDecimal
import java.time.LocalDate
/**
* This class is just a list of trades that exist with a certain other party.
* In reality, portfolios are constructed under the tree of corporation, legal entity, division, desk, book etc etc
* but for this example we just create our portfolio of "all trades against another counterparty" (ie node)
*
* @param valuationDate can be null for transient portfolio objects
*/
data class Portfolio(private val tradeStateAndRefs: List<StateAndRef<IRSState>>, val valuationDate: LocalDate? = null) {
val trades: List<IRSState> by lazy { tradeStateAndRefs.map { it.state.data } }
val swaps: List<SwapData> by lazy { trades.map { it.swap } }
val refs: List<StateRef> by lazy { tradeStateAndRefs.map { it.ref } }
fun getNotionalForParty(party: Party): BigDecimal = trades.map { it.swap.getLegForParty(party).notional }.sum()
fun update(curTrades: List<StateAndRef<IRSState>>): Portfolio {
return copy(tradeStateAndRefs = curTrades)
}
}
fun List<StateAndRef<IRSState>>.toPortfolio(): Portfolio {
return Portfolio(this)
}
inline fun <reified T : ContractState> List<StateRef>.toStateAndRef(rpc: CordaRPCOps): List<StateAndRef<T>> {
return rpc.vaultQueryBy<T>(QueryCriteria.VaultQueryCriteria(stateRefs = this)).states
}
|
require_relative "plugin/splatoon2/version"
require_relative "plugin/splatoon2/macro/fast_return"
require_relative "plugin/splatoon2/macro/jump_to_right_key"
require_relative "plugin/splatoon2/macro/jump_to_up_key"
require_relative "plugin/splatoon2/macro/jump_to_left_key"
require_relative "plugin/splatoon2/mode/guruguru"
module ProconBypassMan
module Plugin
end
end
|
pub const REGEX_RFC3339: &str =
r"^([0-9]{4}-[0-9]{2}-[0-9]{2}[Tt][0-9]{2}:[0-9]{2}:[0-9]{2}[Zz+-:0-9]{1,6}$)";
pub const REGEX_RFC3339_NANO: &str =
r"^([0-9]{4}-[0-9]{2}-[0-9]{2}[Tt][0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{7,9}[Zz+-:0-9]{1,6}$)";
pub const REGEX_RFC1123: &str =
r"^([A-Za-z]{3}, [0-9]{2} [A-Za-z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} [A-Za-z]{3,4}$)";
pub const REGEX_RFC1123Z: &str =
r"^([A-Za-z]{3}, [0-9]{2} [A-Za-z]{3} [0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2} [-+]{1}[0-9]{4}$)";
pub const REGEX_RFC822Z: &str =
r"^([0-9]{2} [A-Za-z]{3} [0-9]{2} [0-9]{2}:[0-9]{2} [-+]{1}[0-9]{4}$)";
pub const REGEX_RFC822: &str = r"^([0-9]{2} [A-Za-z]{3} [0-9]{2} [0-9]{2}:[0-9]{2} [A-Za-z]{3,4}$)";
pub const REGEX_RFC850: &str =
r"^([A-Za-z]{6,9}, [0-9]{2}-[A-Za-z]{3}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} [A-Z]{3,4}$)";
pub const REGEX_RUBY_FORMAT: &str =
r"^([A-Za-z]{3} [A-Za-z]{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} [+-][0-9]{4} [0-9]{4}$)";
pub const REGEX_UNIX_FORMAT: &str =
r"^([A-Za-z]{3} [A-Za-z]{3} [0-9_ ]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2} [A-Za-z]{3,4} [0-9]{4}$)";
pub const REGEX_ANSI_C_FORMAT: &str =
r"^([A-Za-z]{3} [A-Za-z]{3} [0-9_ ]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{4}$)";
pub const RFC1123: &str = "%a, %d %b %Y %H:%M:%S %Z";
pub const RFC1123Z: &str = "%a, %d %b %Y %H:%M:%S %z";
pub const RFC822: &str = "%d %b %y %H:%M %Z";
pub const RFC822Z: &str = "%d %b %y %H:%M %z";
pub const RFC3339_NANO: &str = "%Y-%m-%dT%H:%M:%S%.9f%:z";
pub const ANSI_C: &str = "%a %b %_d %H:%M:%S %Y";
pub const UNIX_FORMAT: &str = "%a %b %_d %H:%M:%S %Z %Y";
pub const RUBY_FORMAT: &str = "%a %b %_d %H:%M:%S %z %Y";
pub const RFC850: &str = "%A, %d-%b-%y %H:%M:%S %Z";
|
package typingsSlinky.materialUi.global.MaterialUI
import typingsSlinky.materialUi.MaterialUI.Tabs.TabProps
import typingsSlinky.materialUi.MaterialUI.Tabs.TabsProps
import typingsSlinky.react.mod.Component
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object Tabs {
@JSGlobal("__MaterialUI.Tabs.Tab")
@js.native
class Tab ()
extends Component[TabProps, js.Object, js.Any]
@JSGlobal("__MaterialUI.Tabs.Tabs")
@js.native
class Tabs ()
extends Component[TabsProps, js.Object, js.Any]
}
|
<div class="footer">
<p>Copyright © 2016-2017 <a href="http://jitamin.com">Jitamin</a> Version <?= APP_VERSION ?> All rights reserved.
<span class="pull-right">Jitamin on <a href="https://github.com/jitamin/jitamin" title="Jitamin is developed on Github"><i class="fa fa-github"></i> Github</a></span>
</p>
</div>
|
---
layout: post
title: 中文
tags: site
comment: true
image:
published: true
---
|
mod matrix;
mod tuple;
pub use matrix::Matrix;
pub use tuple::Tuple;
pub const EPSILON: f64 = 1e-4;
#[cfg(test)]
mod matrix_test;
#[cfg(test)]
mod tuple_test;
|
#!/bin/sh
emit "export INIT_PROCESS=rhel-sysv"
export INIT_PROCESS=rhel-sysv
emit_alias_sudo "service"
emit_alias_sudo "chkconfig"
emit_stdin << 'SERVICE_SCRIPT'
SERVICE_BIN=$(which service 2>/dev/null)
if [ $? -ne 0 ]; then
die "no 'service' executable"
fi
function service { # name action
if [ "$2" = "enable" ]; then
chkconfig --add $1
elif [ "$2" = "disable" ]; then
chkconfig --del $1
else
${SERVICE_BIN} "$@"
fi
}
SERVICE_SCRIPT
|
package me.tylerbwong.rebelbase.data.models
import com.google.gson.annotations.SerializedName
/**
* @author Tyler Wong
*/
data class PlanetResponse(@SerializedName(COUNT) var count: Int,
@SerializedName(NEXT) var next: String,
@SerializedName(RESULTS) var results: MutableList<Planet>) {
companion object {
const val COUNT = "count"
const val NEXT = "next"
const val RESULTS = "results"
}
}
|
<?php echo Message::render() ?>
<div class=forum-title>
<?php echo html::anchor( 'forum/post/'.$post->id, $post->title ); ?>
</div>
<div class=forum-content>
<?php echo $post->content ?>
</div>
<div>
<?php echo __('Created by:') ?>
<b><?php echo html::anchor('profile/view/'.$post->user->id, $post->user->username ) ?></b>
<?php echo Time::Ago($post->created) ?>
<?php if ($user->id == $post->user->id): ?>
<?php echo html::anchor( 'forum/post/'.$post->id.'/edit', 'Edit' ) ?>
<?php echo html::anchor( 'forum/post/'.$post->id.'/delete', 'Delete' ) ?>
<?php endif ?>
</div>
|
package main
import (
"errors"
"fmt"
"io"
"net"
"os"
"github.com/code-tool/docker-fpm-wrapper/pkg/util"
)
type DataListener struct {
socketPath string
listener net.Listener
rPool *util.ReaderPool
writer io.Writer
errorChan chan error
}
func NewDataListener(socketPath string, rPool *util.ReaderPool, writer io.Writer, errorChan chan error) *DataListener {
return &DataListener{socketPath: socketPath, rPool: rPool, writer: writer, errorChan: errorChan}
}
func (l *DataListener) handleConnection(conn net.Conn) {
reader := l.rPool.Get(conn)
for {
line, err := util.ReadLine(reader)
if line != nil && len(line) > 0 {
l.writer.Write(line)
}
if err != nil {
if err != io.EOF {
l.errorChan <- err
}
break
}
}
l.rPool.Put(reader)
conn.Close()
}
func (l *DataListener) initSocket() error {
var err error
var c net.Conn
if _, err = os.Stat(l.socketPath); !os.IsNotExist(err) {
// socket exists
c, err = net.Dial("unix", l.socketPath)
if err == nil {
c.Close()
// socket exists and listening
return errors.New(fmt.Sprintf("Socket %s already exists and listening", l.socketPath))
}
err = os.Remove(l.socketPath)
if err != nil {
return err
}
}
l.listener, err = net.Listen("unix", l.socketPath)
if err != nil {
return err
}
return os.Chmod(l.socketPath, 0777)
}
func (l *DataListener) acceptConnections() {
for {
conn, err := l.listener.Accept()
if err != nil {
l.errorChan <- err
return
}
go l.handleConnection(conn)
}
}
func (l *DataListener) Start() error {
err := l.initSocket()
if err == nil {
go l.acceptConnections()
}
return err
}
func (l *DataListener) Stop() {
l.listener.Close()
}
|
/* eslint-disable unicorn/filename-case */
export default {
depend: ["Plain", "ExplicitName", "PromisePlugin"],
create: (Plain, ExplicitName, PromisePlugin) => {
return {
lorem: Plain.get("lorem"),
foo: ExplicitName.echo("bar"),
ping: PromisePlugin.ping,
}
},
}
|
# do_not_heart_me
Цифровой Прорыв 2020 Сердце
|
CREATE TABLE IF NOT EXISTS sb.migrations (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4 (),
version INTEGER NOT NULL,
files TEXT NOT NULL,
executed timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO sb.migrations(version, files)
VALUES(2, '0002_add_migrations_table.sql');
|
use crate::common::{
configuration::genesis_model::Fund,
jcli_wrapper,
jormungandr::{starter::Starter, ConfigurationBuilder},
};
use chain_addr::Discrimination;
#[test]
pub fn test_correct_utxos_are_read_from_node() {
let sender_private_key = jcli_wrapper::assert_key_generate_default();
println!("Sender private key generated: {}", &sender_private_key);
let reciever_private_key = jcli_wrapper::assert_key_generate_default();
println!("Reciever private key generated: {}", &reciever_private_key);
let sender_public_key = jcli_wrapper::assert_key_to_public_default(&sender_private_key);
println!("Sender public key generated: {}", &sender_public_key);
let reciever_public_key = jcli_wrapper::assert_key_to_public_default(&reciever_private_key);
println!("Reciever public key generated: {}", &reciever_public_key);
let sender_address =
jcli_wrapper::assert_address_single(&sender_public_key, Discrimination::Test);
println!("Sender address generated: {}", &sender_address);
let reciever_address =
jcli_wrapper::assert_address_single(&reciever_public_key, Discrimination::Test);
println!("Reciever address generated: {}", &reciever_address);
let mut funds = vec![
Fund {
address: reciever_address.clone(),
value: 100.into(),
},
Fund {
address: sender_address.clone(),
value: 100.into(),
},
];
let config = ConfigurationBuilder::new()
.with_funds(funds.clone())
.build();
let jormungandr = Starter::new().config(config).start().unwrap();
let mut content = jcli_wrapper::assert_rest_utxo_get(&jormungandr.rest_address());
funds.sort_by_key(|fund| fund.address.clone());
content.sort_by_key(|utxo| utxo.address().to_string());
assert_eq!(content.len(), funds.len());
assert_eq!(funds[0].address, content[0].address().to_string());
assert_eq!(
funds[0].value.to_string(),
content[0].associated_fund().to_string()
);
assert_eq!(funds[1].address, content[1].address().to_string());
assert_eq!(
funds[1].value.to_string(),
content[1].associated_fund().to_string()
);
}
|
require_relative '../src/ntp_dos'
require 'optparse'
puts 'NTP Amp DOS attack'
puts 'by DaRkReD'
puts 'usage ntpdos.py <target ip> <ntpserver list> <number of threads> ex: sudo ntp_dos_proxy.rb 1.2.3.4 file.txt 10'
|
// cannot exist within mapStateSlice due to import cycles with
// layerDataSelector(used to be mapStateSlice) -> nso/impact -> layer-data -> mapStateSlice
// x -> y .. x is used by y
import { Map as MapBoxMap } from 'mapbox-gl';
import type { RootState } from '../store';
import type { LayerDataTypes } from '../layers/layer-data';
import type { MapState } from '.';
import type { LayerKey } from '../../config/types';
export const layersSelector = (state: RootState): MapState['layers'] =>
state.mapState.layers;
export const dateRangeSelector = (state: RootState): MapState['dateRange'] =>
state.mapState.dateRange;
export const mapSelector = (state: RootState): MapBoxMap | undefined =>
state.mapState.mapboxMap();
export const layerDataSelector = (id: LayerKey, date?: number) => (
state: RootState,
): LayerDataTypes | undefined =>
state.mapState.layersData.find(
({ layer, date: dataDate }) =>
layer.id === id && (!date || date === dataDate),
);
export const isLoading = (state: RootState): boolean =>
state.mapState.loading > 0;
|
import tz.co.asoft.Phone
import kotlin.test.*
class PhoneTest {
@Test
fun shouldBeNormalized() {
val phone1 = Phone("0752748674")
assertEquals("255752748674", phone1.value)
val phone2 = Phone("255752748674")
assertEquals("255752748674", phone2.value)
val phone3 = Phone("254752748674")
assertEquals("254752748674", phone3.value)
val phone4 = Phone("+255752748674")
assertEquals("255752748674", phone4.value)
val phone5 = Phone("+256752748674")
assertEquals("256752748674", phone5.value)
val adminPhone = Phone(255000000000)
assertEquals(255000000000, adminPhone.value.toLong())
}
@Test
fun shouldBeInvalid() {
assertFails { Phone("255") }
assertFails { Phone("0000000000") }
}
@Test
fun should_throw_error() {
assertFails { Phone(2) }
assertFails { Phone(0) }
}
}
|
# 88. Merge Sorted Array
标签(空格分隔): leetcode easy array
---
给两个排好序的正数数组,*nums1*和*nums2*,合并它们。
**注意:**
1. 直接修改*nums1*,你可以假定nums1的长度>=两个数组长度之和。
2. m是*nums1*的有效元素个数,n是*nums2*的有效元素个数。
## 思路
1. 题目没有给定升序还是降序,此处默认升序。
2. 我们从m+n-1开始,比较两个数组的最末位,谁大就覆盖,且索引-1.
3. 我们以nums2的索引来判断,这是有一定的技巧性的。如果这个索引<0,我们就停止比较,因为所有nums2都插入了且前面也正好是nums1的数。而当nums1的索引<0时,只要覆盖就行了。
## 代码
```js
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function(nums1, m, nums2, n) {
var i = m - 1,
j = n - 1,
k = m + n -1;
while(j>=0) {
if(i<0 || nums1[i] < nums2[j]) {
nums1[k--] = nums2[j--];
} else {
nums1[k--] = nums1[i--];
}
}
};
```
## 有点耍赖的代码
```js
/**
* @param {number[]} nums1
* @param {number} m
* @param {number[]} nums2
* @param {number} n
* @return {void} Do not return anything, modify nums1 in-place instead.
*/
var merge = function(nums1, m, nums2, n) {
nums1.splice(m);
nums2.splice(n);
// 因为题目规定只能修改nums1,所以用这种技巧塞入,用concat会返回新的数组
Array.prototype.push.apply(nums1, nums2);
nums1.sort((a,b) => a - b);
};
```
|
package tests
import (
"testing"
"github.com/gruntwork-io/terratest/modules/terraform"
)
func TestSerial(t *testing.T) {
// setup
options := &terraform.Options{
TerraformDir: ".",
}
terraform.InitAndApply(t, options)
defer terraform.Destroy(t, options)
t.Run("terraform_init_should_succeed", func(t *testing.T) {
terraformTestOptions := &terraform.Options{
TerraformDir: "./test-01",
}
defer terraform.Destroy(t, terraformTestOptions)
terraform.Init(t, terraformTestOptions)
if _, err := terraform.ApplyE(t, terraformTestOptions); err != nil {
t.Fatalf("Should be no errors in trivial TF.")
}
})
t.Run("create_rg_should_fail", func(t *testing.T) {
terraformTestOptions := &terraform.Options{
TerraformDir: "./test-02",
}
defer terraform.Destroy(t, terraformTestOptions)
terraform.Init(t, terraformTestOptions)
if _, err := terraform.ApplyE(t, terraformTestOptions); err == nil {
t.Fatalf("Should not be possible to create rg of same name.")
}
})
t.Run("create_storage_should_succeed", func(t *testing.T) {
terraformTestOptions := &terraform.Options{
TerraformDir: "./test-03",
}
defer terraform.Destroy(t, terraformTestOptions)
terraform.Init(t, terraformTestOptions)
if _, err := terraform.ApplyE(t, terraformTestOptions); err != nil {
t.Fatalf("Should be possible to create storage.")
}
})
t.Run("create_virtual_network_should_succeed", func(t *testing.T) {
terraformTestOptions := &terraform.Options{
TerraformDir: "./test-04",
}
defer terraform.Destroy(t, terraformTestOptions)
terraform.Init(t, terraformTestOptions)
if _, err := terraform.ApplyE(t, terraformTestOptions); err != nil {
t.Fatalf("Should be possible to create virtual network.")
}
})
t.Run("create_public_ip_should_succeed", func(t *testing.T) {
terraformTestOptions := &terraform.Options{
TerraformDir: "./test-05",
}
defer terraform.Destroy(t, terraformTestOptions)
terraform.Init(t, terraformTestOptions)
if _, err := terraform.ApplyE(t, terraformTestOptions); err != nil {
t.Fatalf("Should be possible to create public ip.")
}
})
}
|
---
layout: page
title: About me
permalink: /about/
banner_image: sample-banner-image-2.jpg
banner_image_alt: About me
---
一名爱折腾,爱自学的程序猿.
* 2012 年毕业于武汉理工大学, 本科.
* 2012 年入职东软集团 (大连) 有限公司.
东软是我人生中最重要的一个转折点, 是一个把大学理论知识变成实践经验的工厂.
2012/07 -- 2012/12 一大批校招的毕业生在东软接受了半年的 C/C++ 语言培训
培训期间主要完成以下项目:
<table>
<tr>
<td>作品</td>
<td>语言</td>
</tr>
<tr>
<td>车牌识别系统</td>
<td> C++ , MFC ,SQL</td>
</tr>
<tr>
<td>媒体播放器</td>
<td>C++ , MFC</td>
</tr>
</table>
* 2012/12 -- 2014/01 进入嵌入式事业部,开始了与 C 语言没啥关系的 Android 系统适配工作.
从没有 JAVA 基础到写出自己第一款发布到应用商城的应用[贴吧一键签到][360link], 一步走过来受益匪浅,目前就360手机市场下载量已经达到了49万.
* 2014/02 从东软离职
* 2014/03 -- 2016/04 3月北京华为面试通过,5月正式入职,从事安全领域开发,工作环境很融洽,有一个很好的领导,一个很好的导师,身边有一群很好很照顾我的同事.
* 2016/04 -- 至今 入职阿里, 回归`android`大本营
### Contact me
Say `Hello` at dyy726@qq.com
---
<!-- {% include social.html %} -->
[360link]: http://zhushou.360.cn/detail/index/soft_id/895366
[jekyll]: http://jekyllrb.com
|
function write_doc(docformat::Pandoc2HTML, doc, rendered, out_path)
_, weave_source = splitdir(abspath(doc.source))
weave_version, weave_date = weave_info()
# Header is inserted from displayed plots
header_script = doc.header_script
self_contained = (header_script ≠ "") ? [] : "--self-contained"
if haskey(doc.header, "bibliography")
filt = "--filter"
citeproc = "pandoc-citeproc"
else
filt = []
citeproc = []
end
out_path = get_out_path(doc, out_path, "html")
cd_back = let d = pwd(); () -> cd(d); end
cd(dirname(out_path))
try
out = basename(out_path)
highlight_stylesheet = get_highlight_stylesheet(MIME("text/html"), docformat.highlight_theme)
cmd = `pandoc -f markdown+raw_html -s --mathjax=""
$filt $citeproc $(docformat.pandoc_options)
--template $(docformat.template_path)
-H $(docformat.stylesheet_path)
$(self_contained)
-V highlight_stylesheet=$(highlight_stylesheet)
-V weave_version=$(weave_version)
-V weave_date=$(weave_date)
-V weave_source=$(weave_source)
-V headerscript=$(header_script)
-o $(out)`
proc = open(cmd, "r+")
println(proc.in, rendered)
close(proc.in)
proc_output = read(proc.out, String)
catch
rethrow() # TODO: just show error content instead of rethrow the err
finally
cd_back()
end
return out_path
end
function write_doc(docformat::Pandoc2PDF, doc, rendered, out_path)
if haskey(doc.header, "bibliography")
filt = "--filter"
citeproc = "pandoc-citeproc"
else
filt = []
citeproc = []
end
out_path = get_out_path(doc, out_path, "pdf")
cd_back = let d = pwd(); () -> cd(d); end
cd(dirname(out_path))
try
out = basename(out_path)
cmd = `pandoc -f markdown+raw_tex -s --pdf-engine=xelatex --highlight-style=tango
$filt $citeproc $(docformat.pandoc_options)
--include-in-header=$(docformat.header_template)
-V fontsize=12pt -o $(out)`
proc = open(cmd, "r+")
println(proc.in, rendered)
close(proc.in)
proc_output = read(proc.out, String)
catch
rethrow()
finally
cd_back()
end
return out_path
end
|
require File.expand_path('../../../spec_helper', __FILE__)
describe "Process.setpriority" do
platform_is_not :windows do
it "takes three arguments" do
lambda { Process.setpriority }.should raise_error(ArgumentError)
lambda {
Process.setpriority(Process::PRIO_PROCESS)
}.should raise_error(ArgumentError)
lambda {
Process.setpriority(Process::PRIO_PROCESS, 0)
}.should raise_error(ArgumentError)
end
end
# Needs a valid version written for Linux
platform_is :os => :darwin do
it "sets the scheduling priority for a specified process" do
p = Process.getpriority(Process::PRIO_PROCESS, 0)
Process.setpriority(Process::PRIO_PROCESS, 0, p + 1).should == 0
Process.getpriority(Process::PRIO_PROCESS, 0).should == (p + 1)
if Process.uid == 0
Process.setpriority(Process::PRIO_PROCESS, 0, p).should == 0
else
lambda {
Process.setpriority(Process::PRIO_PROCESS, 0, p)
}.should raise_error(Errno::EACCES)
end
end
end
# Darwin and FreeBSD don't seem to handle these at all, getting all out of
# whack with either permission errors or just the wrong value
platform_is_not :os => [:darwin, :freebsd, :windows] do
it "sets the scheduling priority for a specified process group" do
pr = Process.getpriority(Process::PRIO_PGRP, 0)
Process.setpriority(Process::PRIO_PGRP, 0, pr + 1).should == 0
Process.getpriority(Process::PRIO_PGRP, 0).should == (pr + 1)
if Process.uid == 0
Process.setpriority(Process::PRIO_PGRP, 0, pr).should == 0
else
# EACCESS is not always raised. It's a stupid OS behavior.
ok = false
begin
Process.setpriority(Process::PRIO_PGRP, 0, pr)
ok = true
rescue Errno::EACCES
ok = true
rescue Object
ok = false
end
ok.should == true
end
end
end
platform_is_not :os => :windows do
as_superuser do
it "sets the scheduling priority for a specified user" do
p = Process.getpriority(Process::PRIO_USER, 0)
Process.setpriority(Process::PRIO_USER, 0, p + 1).should == 0
Process.getpriority(Process::PRIO_USER, 0).should == (p + 1)
Process.setpriority(Process::PRIO_USER, 0, p).should == 0
end
end
end
end
|
-- ------------------------------------------------------------
-- Resolve state-as-country
-- ------------------------------------------------------------
-- --------------------------------------
-- Resolves political divisions which are treated as countries in
-- the reference databases (GADM, Geonames) but are actually
-- subnational units (states, provinces, territories, etc.)
-- If parent country is correct, populates the
-- country fields with name and id of state-as-country
-- Assumes country has already been resolve, therefore must
-- be performed after all other country checks have been
-- completed
-- --------------------------------------
-- standard name
UPDATE user_data a
SET
country_id=b.country_id,
country=b.country,
match_method_country='exact standard name, state-as-country',
state_province=NULL -- Clear just in case
FROM country b JOIN country c
ON b.alt_country_id=c.country_id
WHERE job=:'job'
AND a.state_province_id IS NULL
AND a.country_id=c.country_id
AND LOWER(unaccent(a.state_province_verbatim))=LOWER(b.country)
;
--iso or fips codes
UPDATE user_data a
SET
country_id=b.country_id,
country=b.country,
match_method_country='ISO/FIPS/HASC code, state-as-country',
state_province=NULL -- Clear just in case
FROM country b JOIN country c
ON b.alt_country_id=c.country_id
WHERE job=:'job'
AND a.state_province_id IS NULL
AND a.country_id=c.country_id
AND a.state_province_verbatim IN (b.iso, b.iso_alpha3, b.fips)
;
-- alternate name
UPDATE user_data a
SET
country_id=b.country_id,
country=b.country,
match_method_country='exact alternate name, state-as-country',
state_province=NULL -- Clear just in case
FROM country b JOIN country c
ON b.alt_country_id=c.country_id
JOIN country_name d
ON b.country_id=d.country_id
WHERE job=:'job'
AND a.state_province_id IS NULL
AND a.country_id=c.country_id
AND (
LOWER(a.state_province_verbatim)=LOWER(d.country_name)
OR -- In case non-Latin languages corrupted by LOWER():
a.state_province_verbatim=d.country_name
)
;
|
# ClimbingRobot
CAD and code for my wheeled-legged-climbing robot: https://youtu.be/anp15oVASc4
|
/* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
import {RenderCache} from './drawable';
import {Point} from './internal_types';
import {
CirclePaintOption,
LinePaintOption,
ObjectRenderer,
TrianglePaintOption,
} from './renderer/renderer_types';
export class PaintBrush {
constructor(
private readonly renderCache: RenderCache,
private readonly renderer: ObjectRenderer
) {}
setLine(cacheId: string, polyline: Float32Array, paintOpt: LinePaintOption) {
const newCacheValue = this.renderer.createOrUpdateLineObject(
this.renderCache.getFromPreviousFrame(cacheId),
polyline,
paintOpt
);
if (newCacheValue) {
this.renderCache.setToCurrentFrame(cacheId, newCacheValue);
}
}
setTriangle(cacheId: string, loc: Point, paintOpt: TrianglePaintOption) {
const newCacheValue = this.renderer.createOrUpdateTriangleObject(
this.renderCache.getFromPreviousFrame(cacheId),
loc,
paintOpt
);
if (newCacheValue) {
this.renderCache.setToCurrentFrame(cacheId, newCacheValue);
}
}
setCircle(cacheId: string, loc: Point, paintOpt: CirclePaintOption) {
const newCacheValue = this.renderer.createOrUpdateCircleObject(
this.renderCache.getFromPreviousFrame(cacheId),
loc,
paintOpt
);
if (newCacheValue) {
this.renderCache.setToCurrentFrame(cacheId, newCacheValue);
}
}
}
|
namespace Nest.Searchify.Abstractions
{
public interface IPagingParameters
{
int Start();
int Size { get; set; }
int? Page { get; set; }
bool HasSort();
}
}
|
<p align="center">
<img src="https://raw.githubusercontent.com/gnlow/id/master/Dalkak/dalkak_logo.svg?sanitize=true" width="100"></img>
</p>
<h1 align="center">
Dalkak
<a href="https://bundlephobia.com/result?p=dalkak">
<img src="https://badgen.net/bundlephobia/minzip/dalkak"></img>
</a>
</h1>
Library for Block based EPL(ex: Scratch, Entry)
|
import 'dart:convert';
import 'dart:math';
import 'package:fluent_reader_lite/models/service.dart';
import 'package:fluent_reader_lite/utils/global.dart';
import 'package:fluent_reader_lite/utils/store.dart';
import 'package:fluent_reader_lite/utils/utils.dart';
import 'package:html/parser.dart';
import 'package:tuple/tuple.dart';
import 'package:http/http.dart' as http;
import '../item.dart';
import '../source.dart';
class FeedbinServiceHandler extends ServiceHandler {
String endpoint;
String username;
String password;
int fetchLimit;
int _lastId;
Tuple2<Set<String>, Set<String>> _lastSynced;
FeedbinServiceHandler() {
endpoint = Store.sp.getString(StoreKeys.ENDPOINT);
username = Store.sp.getString(StoreKeys.USERNAME);
password = Store.sp.getString(StoreKeys.PASSWORD);
fetchLimit = Store.sp.getInt(StoreKeys.FETCH_LIMIT);
_lastId = Store.sp.getInt(StoreKeys.LAST_ID) ?? 0;
}
FeedbinServiceHandler.fromValues(
this.endpoint,
this.username,
this.password,
this.fetchLimit
) {
_lastId = Store.sp.getInt(StoreKeys.LAST_ID) ?? 0;
}
void persist() {
Store.sp.setInt(StoreKeys.SYNC_SERVICE, SyncService.Feedbin.index);
Store.sp.setString(StoreKeys.ENDPOINT, endpoint);
Store.sp.setString(StoreKeys.USERNAME, username);
Store.sp.setString(StoreKeys.PASSWORD, password);
Store.sp.setInt(StoreKeys.FETCH_LIMIT, fetchLimit);
Store.sp.setInt(StoreKeys.LAST_ID, _lastId);
Global.service = this;
}
@override
void remove() {
super.remove();
Store.sp.remove(StoreKeys.ENDPOINT);
Store.sp.remove(StoreKeys.USERNAME);
Store.sp.remove(StoreKeys.PASSWORD);
Store.sp.remove(StoreKeys.FETCH_LIMIT);
Store.sp.remove(StoreKeys.LAST_ID);
Global.service = null;
}
String _getApiKey() {
final credentials = "$username:$password";
final bytes = utf8.encode(credentials);
return base64.encode(bytes);
}
Future<http.Response> _fetchAPI(String params) async {
return await http.get(
endpoint + params,
headers: {
"Authorization": "Basic ${_getApiKey()}",
}
);
}
Future<void> _markItems(String type, String method, List<String> refs) async {
final auth = "Basic ${_getApiKey()}";
final promises = List<Future>.empty(growable: true);
final client = http.Client();
try {
while (refs.length > 0) {
final batch = List<int>.empty(growable: true);
while (batch.length < 1000 && refs.length > 0) {
batch.add(int.parse(refs.removeLast()));
}
final bodyObject = {
"${type}_entries": batch,
};
final request = http.Request(
method,
Uri.parse(endpoint + type + "_entries.json"),
);
request.headers["Authorization"] = auth;
request.headers["Content-Type"] = "application/json; charset=utf-8";
request.body = jsonEncode(bodyObject);
promises.add(client.send(request));
}
await Future.wait(promises);
} finally {
client.close();
}
}
int get lastId => _lastId;
set lastId(int value) {
_lastId = value;
Store.sp.setInt(StoreKeys.LAST_ID, value);
}
@override
Future<bool> validate() async {
try {
final response = await _fetchAPI("authentication.json");
return response.statusCode == 200;
} catch(exp) {
print(exp);
return false;
}
}
@override
Future<Tuple2<List<RSSSource>, Map<String, List<String>>>> getSources() async {
final response = await _fetchAPI("subscriptions.json");
assert(response.statusCode == 200);
final subscriptions = jsonDecode(response.body);
final groupsMap = Map<String, List<String>>();
final tagsResponse = await _fetchAPI("taggings.json");
assert(tagsResponse.statusCode == 200);
final tags = jsonDecode(tagsResponse.body);
for (var tag in tags) {
final name = tag["name"].trim();
groupsMap.putIfAbsent(name, () => []);
groupsMap[name].add(tag["feed_id"].toString());
}
final sources = subscriptions.map<RSSSource>((s) {
return RSSSource(s["feed_id"].toString(), s["feed_url"], s["title"]);
}).toList();
return Tuple2(sources, groupsMap);
}
@override
Future<List<RSSItem>> fetchItems() async {
var page = 1;
var minId = Utils.syncMaxId;
var items = [];
List lastFetched;
do {
try {
final response = await _fetchAPI("entries.json?mode=extended&per_page=125&page=$page");
assert(response.statusCode == 200);
lastFetched = jsonDecode(response.body);
items.addAll(lastFetched.where((i) => i["id"] > lastId && i["id"] < minId));
minId = lastFetched.fold(minId, (m, n) => min(m, n["id"]));
page += 1;
} catch(exp) {
break;
}
} while (
minId > lastId &&
lastFetched != null && lastFetched.length >= 125 &&
items.length < fetchLimit
);
lastId = items.fold(lastId, (m, n) => max(m, n["id"]));
final parsedItems = List<RSSItem>.empty(growable: true);
final unread = _lastSynced.item1;
final starred = _lastSynced.item2;
for (var i in items) {
if (i["content"] == null) continue;
final dom = parse(i["content"]);
final iid = i["id"].toString();
final item = RSSItem(
id: iid,
source: i["feed_id"].toString(),
title: i["title"],
link: i["url"],
date: DateTime.parse(i["published"]),
content: i["content"],
snippet: dom.documentElement.text.trim(),
creator: i["author"],
hasRead: !unread.contains(iid),
starred: starred.contains(iid),
);
if (i["images"] != null && i["images"]["original_url"] != null) {
item.thumb = i["images"]["original_url"];
} else {
var img = dom.querySelector("img");
if (img != null && img.attributes["src"] != null) {
var thumb = img.attributes["src"];
if (thumb.startsWith("http")) {
item.thumb = thumb;
}
}
}
parsedItems.add(item);
}
_lastSynced = null;
return parsedItems;
}
@override
Future<Tuple2<Set<String>, Set<String>>> syncItems() async {
final responses = await Future.wait([
_fetchAPI("unread_entries.json"),
_fetchAPI("starred_entries.json"),
]);
assert(responses[0].statusCode == 200);
assert(responses[1].statusCode == 200);
final unread = jsonDecode(responses[0].body);
final starred = jsonDecode(responses[1].body);
_lastSynced = Tuple2(
Set.from(unread.map((i) => i.toString())),
Set.from(starred.map((i) => i.toString())),
);
return _lastSynced;
}
@override
Future<void> markAllRead(Set<String> sids, DateTime date, bool before) async {
List<String> predicates = ["hasRead = 0"];
if (sids.length > 0) {
predicates.add("source IN (${List.filled(sids.length, "?").join(" , ")})");
}
if (date != null) {
predicates.add("date ${before ? "<=" : ">="} ${date.millisecondsSinceEpoch}");
}
final rows = await Global.db.query(
"items",
columns: ["iid"],
where: predicates.join(" AND "),
whereArgs: sids.toList(),
);
final iids = rows.map((r) => r["iid"]);
await _markItems("unread", "DELETE", List.from(iids));
}
@override
Future<void> markRead(RSSItem item) async{
await _markItems("unread", "DELETE", [item.id]);
}
@override
Future<void> markUnread(RSSItem item) async {
await _markItems("unread", "POST", [item.id]);
}
@override
Future<void> star(RSSItem item) async {
await _markItems("starred", "POST", [item.id]);
}
@override
Future<void> unstar(RSSItem item) async {
await _markItems("starred", "DELETE", [item.id]);
}
}
|
package business
import (
"errors"
"time"
"github.com/opiumated/yellowpages/locations"
"github.com/opiumated/yellowpages/mongo"
"gopkg.in/mgo.v2/bson"
)
type Business struct {
ID bson.ObjectId `json:"id"`
Name string `json:"name"`
Address string `json:"address"`
Location locations.Location `json:"location"`
OwnersName string `json:"owner"`
OwnersPhone string `json:"owner_phone"`
BusinessEmail string `json:"email"`
Type string `json:"business_type"`
IsVerified bool `json:"is_verified"`
Website string `json:"website"`
BusinessCategory string `json:"category"`
Description string `json:"description"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func New(business Business) error {
session := mongo.Get().Session.Copy()
defer session.Close()
if business.AlreadyExist(business.Name) {
return errors.New("Business with that name already exists")
}
collection := session.DB(mongo.DATABASE).C(mongo.BUSINESS)
return collection.Insert(business)
}
func (b Business) AlreadyExist(businessName string) bool {
session := mongo.Get().Session.Copy()
defer session.Close()
var biz Business
collection := session.DB(mongo.DATABASE).C(mongo.BUSINESS)
if err := collection.Find(bson.M{"name": businessName}).One(&biz); err != nil {
return false
}
return true
}
func SearchBusiness(query interface{}) ([]Business, error) {
session := mongo.Get().Session.Copy()
defer session.Close()
var results []Business
collection := session.DB(mongo.DATABASE).C(mongo.BUSINESS_TYPE)
if err := collection.Find(query).Sort().Limit(20).All(&results); err != nil {
return results, err
}
return results, nil
}
|
<?php
/**
* @file gebruiker_aanpassen.php
* @author Dieter Verboven
* View waarin de admin een gebruiker kan aanpassen
* - toont een $persoon-object in een formulier
* - systeem toont een foutmelding als de invoercontrole niet correct is.
*/
?>
<script>
$(document).ready(function () {
$(".btnToevoegen").hide();
$("#success").hide();
$('#type').change(function() {
var e = document.getElementById("type");
var type = e.options[e.selectedIndex].text;
if (type === "trainer")
{
$('.text').html("Automatisch paswoord: trainer123")
$(".password").show();
}
else if (type === "zwemmer")
{
$('.text').html("Automatisch paswoord: zwemmer123")
$(".password").show();
}
});
});
</script>
<div class="col-md-10 content">
<h1 class="">Gebruiker toevoegen</h1>
<hr>
<?php
foreach ($types as $type) {
$typeOpties[$type->id] = $type->typePersoon;
}
$attributes = array('name' => 'gebruikerAanpassenFormulier', 'data-toggle' => 'validator', 'role' => 'form');
echo form_open('trainer/gebruiker/voegToe', $attributes);
echo form_labelpro('Type gebruiker:', 'type');
echo form_dropdown('type', $typeOpties,'', 'id="type"');
echo '</br>';
?>
<div class="form-group">
<?php
echo form_labelpro('Voornaam', 'voornaam');
echo form_input(array('name' => 'voornaam',
'id' => 'voornaam',
'class' => 'form-control',
'required' => 'required'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Familienaam', 'familienaam');
echo form_input(array('name' => 'familienaam',
'id' => 'familienaam',
'class' => 'form-control',
'required' => 'required'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Geboortedatum', 'geboortedatum');
echo form_input(array('name' => 'geboortedatum',
'id' => 'geboortedatum',
'class' => 'form-control',
'type' => 'date'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Straat', 'straat');
echo form_input(array('name' => 'straat',
'id' => 'straat',
'class' => 'form-control'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Huisnummer', 'nummer');
echo form_input(array('name' => 'nummer',
'id' => 'nummer',
'type' => 'number',
'class' => 'form-control'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Postcode', 'postcode');
echo form_input(array('name' => 'postcode',
'id' => 'postcode',
'type' => 'number',
'class' => 'form-control'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Woonplaats', 'woonplaats');
echo form_input(array('name' => 'woonplaats',
'id' => 'woonplaats',
'class' => 'form-control'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('E-mailadres', 'mailadres');
echo form_input(array('name' => 'mailadres',
'id' => 'mailadres',
'type' => 'email',
'class' => 'form-control',
'data-error' => 'Dit is geen email.',
'required' => 'required'));
echo '<div class="help-block with-errors"></div>';
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Gsmnummer', 'gsmnummer');
echo form_input(array('name' => 'gsmnummer',
'id' => 'gsmnummer',
'class' => 'form-control'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Biografie', 'gebruikersnaam');
echo form_textarea(array('name' => 'biografie',
'id' => 'biografie',
'class' => 'form-control'));
?>
</div>
<div class="form-group">
<?php
echo form_labelpro('Gebruikersnaam', 'gebruikersnaam');
echo form_input(array('name' => 'gebruikersnaam',
'id' => 'gebruikersnaam',
'class' => 'form-control',
'required' => 'required'));
?>
</div>
</br>
<div class="password">
<p class="text">Automatisch paswoord: trainer123</p>
</div>
<?php
echo '<div>';
echo '</br>';
echo form_submit('knop', 'Voeg toe', 'class="btn btn-primary"');
echo form_close();
echo anchor('trainer/gebruiker/beheren', form_button('back', 'Annuleren', 'class="btn btn-warning"'));
echo '</div></br>';
?>
</div>
|
# God Wars 2 Library
This is just my attempt at cataloging as much info about God Wars 2 as I can find
or write. Feel free to fork and contribute!
|
//! ` `
// @<Check variable-size...@>=
#[allow(unused_macros)]
pub(crate) macro Check_variable_size_avail_list {
($globals:expr) => {{
/// current locations of interest in `mem`
let (mut p, mut q) : (pointer, pointer);
/// is something amiss?
let mut clobbered: boolean;
// p:=rover; q:=null; clobbered:=false;
p = $globals.rover;
q = null;
clobbered = false;
crate::region_forward_label!(
|'done2|
{
// repeat if (p>=lo_mem_max)or(p<mem_min) then clobbered:=true
loop {
if p >= $globals.lo_mem_max || p < mem_min as pointer {
clobbered = true;
}
// else if (rlink(p)>=lo_mem_max)or(rlink(p)<mem_min) then clobbered:=true
else if rlink!($globals, p) >= $globals.lo_mem_max ||
rlink!($globals, p) < mem_min as pointer {
clobbered = true;
}
// else if not(is_empty(p))or(node_size(p)<2)or@|
// (p+node_size(p)>lo_mem_max)or@| (llink(rlink(p))<>p) then clobbered:=true;
else if !is_empty!($globals, p) || node_size!($globals, p) < 2 ||
p + node_size!($globals, p) > $globals.lo_mem_max ||
llink!($globals, rlink!($globals, p)) != p {
clobbered = true;
}
// if clobbered then
if clobbered {
// begin print_nl("Double-AVAIL list clobbered at ");
print_nl($globals, crate::strpool_str!("Double-AVAIL list clobbered at "));
// print_int(q); goto done2;
print_int($globals, q as _);
crate::goto_forward_label!('done2);
// end;
}
// for q:=p to p+node_size(p)-1 do {mark all locations free}
/// mark all locations free
for q in p..= p + node_size!($globals, p) - 1 {
// begin if free[q] then
if $globals.free[q] {
// begin print_nl("Doubly free location at ");
print_nl($globals, crate::strpool_str!("Doubly free location at "));
// @.Doubly free location...@>
// print_int(q); goto done2;
print_int($globals, q as _);
crate::goto_forward_label!('done2);
// end;
}
// free[q]:=true;
$globals.free[q] = true;
// end;
}
// q:=p; p:=rlink(p);
q = p;
p = rlink!($globals, p);
// until p=rover;
if (p == $globals.rover) {
break;
}
}
}
// done2:
'done2 <-
);
use crate::section_0062::print_nl;
use crate::section_0065::print_int;
use crate::section_0115::null;
use crate::section_0124::empty_flag;
}}
}
|
using System.Text;
namespace BasicHttpServer.HTTP
{
public class ResponseCookie : Cookie
{
public ResponseCookie(string name, string value)
: base(name, value)
{
Path = "/";
}
public int MaxAge { get; set; }
public bool HttpOnly { get; set; }
public string Path { get; set; }
public override string ToString()
{
var responseCookieBuilder = new StringBuilder();
responseCookieBuilder.Append($"{Name}={Value}; Path={Path};");
if (MaxAge != 0)
{
responseCookieBuilder.Append($" Max-Age={MaxAge};");
}
if (HttpOnly)
{
responseCookieBuilder.Append(" HttpOnly;");
}
return responseCookieBuilder.ToString();
}
}
}
|
---
layout: post
title: "Rails 日志切割"
date: 2013-09-15 23:48
comments: true
categories: [Rails, Linux, Logorotate]
---
编辑日志切割配置 `/etc/logrotate.conf`, 新增 Rails 日志配置项
{% highlight ruby %}
{{YOUR_APP_CURRENT_PATH}}/log/*.log {
daily
dateext
missingok
rotate 65535
delaycompress
notifempty
copytruncate
}
{% endhighlight %}
|
package com.example.weather
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.weather.ui.theme.BuildingComposeTheme
import com.google.accompanist.glide.rememberGlidePainter
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("Main", "onCreate")
setContent {
BuildingComposeTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
Content()
}
}
}
}
}
@Composable
fun Content() {
val viewModel: WeatherViewModel = viewModel()
val weather = viewModel.weather
Scaffold(topBar = {
TopAppBar() {
Text(
if (weather is Weather.OnSuccess) weather.locationName else "Weather",
modifier = Modifier.padding(start = 8.dp),
style = MaterialTheme.typography.h5
)
}
}) {
Row(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
when (weather) {
is Weather.OnSuccess -> {
Column() {
Text(
"${weather.locationName} weather",
style = MaterialTheme.typography.body1
)
Text(weather.status, style = MaterialTheme.typography.body2)
Text(weather.description, style = MaterialTheme.typography.caption)
}
Box(modifier = Modifier.padding(end = 8.dp).height(48.dp)) {
Image(
painter = rememberGlidePainter(
request = "https://openweathermap.org/img/wn/${weather.icon}@2x.png"
), contentDescription = null
)
}
}
Weather.OnLoading -> Text(text = "Loading")
is Weather.OnError -> Text(text = weather.e)
}
}
}
}
@Preview
@Composable
fun ContentPreview() {
Content()
}
|
module HLearn.DataStructures.MonoidTree
( MonoidTree
, getval
, takeMT
, dropMT
)
where
import HLearn.Algebra
-------------------------------------------------------------------------------
-- data types
data MonoidTree m
= Node { val :: m, numdp' :: Int, left :: MonoidTree m, right :: MonoidTree m }
| Leaf
instance Show m => Show (MonoidTree m) where
show Leaf = "Leaf"
show m = "Sum { val="++show (val m)++", numdp="++show (numdp m)++", ... }"
-------------------------------------------------------------------------------
-- algebra
instance Monoid m => Monoid (MonoidTree m) where
mempty = Leaf
mappend Leaf Leaf = Leaf
mappend Leaf m = m
mappend m Leaf = m
mappend m1 m2 = Node
{ val = val m1 <> val m2
, numdp' = numdp' m1 + numdp' m2
, left = m1
, right = m2
}
-------------------------------------------------------------------------------
-- training
instance HasRing (MonoidTree m) where
type Ring (MonoidTree m) = Int
instance NumDP (MonoidTree m) where
numdp Leaf = 0
numdp m = numdp' m
instance Monoid m => HomTrainer (MonoidTree m) where
type Datapoint (MonoidTree m) = m
train1dp m = Node m 1 Leaf Leaf
-------------------------------------------------------------------------------
-- operations
getval :: Monoid m => MonoidTree m -> m
getval Leaf = mempty
getval m = val m
takeMT :: Monoid m => Int -> MonoidTree m -> MonoidTree m
takeMT 0 _ = Leaf
takeMT _ Leaf = Leaf
takeMT i m = if i >= numdp m
then m
else takeMT i (left m) <> takeMT (i - (numdp $ left m)) (right m)
dropMT :: Monoid m => Int -> MonoidTree m -> MonoidTree m
dropMT 0 m = m
dropMT _ Leaf = Leaf
dropMT i m = if i >= numdp m
then Leaf
else dropMT i (left m) <> dropMT (i - (numdp $ left m)) (right m)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.