text
stringlengths 27
775k
|
---|
<h4>Wybierz wzór</h4>
<div class="business-cards">
<div class="row bc-patterns">
<input type='radio' name='bc' value='bc1' id="bc1"
ng-click="SelectDesign('bc1.png')"
style="background: url('../web/static/img/bc1.png') no-repeat; background-size: 60%;"/>
<label for="bc1" style="background: url('../web/static/img/bc1.png')"></label>
<input type='radio' name='bc' value='bc2' id="bc2"
ng-click="SelectDesign('bc2.png')"
style="background: url('../web/static/img/bc2.png') no-repeat"/>
<label for="bc2" style="background: url('../web/static/img/bc2.png')"></label>
<input type='radio' name='bc' value='bc1' id="bc3"
ng-click="SelectDesign('bc3.png')"
style="background: url('../web/static/img/bc3.png') no-repeat"/>
<label for="bc3" style="background: url('../web/static/img/bc3.png')"></label>
</div>
</div>
<style>
</style>
|
# はじめに
指定フォルダ配下にある全部のエクセルファイルから特定の文字列を検索してくれるエクセルVBA。
# 使い方
1. セルB1に検索パスを入れる。<br />セルC1の参照から選んでもOK
1. セルB2に検索したい文字列を入れる。基本は部分一致。<br />セルC2を正規表現にすれば正規表現での検索も(たぶん)可能。
1. 検索開始ボタンを押せばフォルダ配下のエクセルファイルから文字列を検索。<br />かなり遅いので気長に。
# 最後に
標準であってもいい機能だと思うんだ。
|
use crate::frame_c::config::FrameConfig;
use crate::frame_c::parser::*;
use crate::frame_c::scanner::*;
use crate::frame_c::symbol_table::*;
use crate::frame_c::utils::{frame_exitcode, RunError};
use crate::frame_c::visitors::cpp_visitor::CppVisitor;
use crate::frame_c::visitors::cs_visitor::CsVisitor;
use crate::frame_c::visitors::cs_visitor_for_bob::CsVisitorForBob;
use crate::frame_c::visitors::gdscript_3_2_visitor::GdScript32Visitor;
use crate::frame_c::visitors::java_8_visitor::Java8Visitor;
use crate::frame_c::visitors::javascript_visitor::JavaScriptVisitor;
use crate::frame_c::visitors::plantuml_visitor::PlantUmlVisitor;
use crate::frame_c::visitors::python_visitor::PythonVisitor;
use crate::frame_c::visitors::rust_visitor::RustVisitor;
use crate::frame_c::visitors::smcat_visitor::SmcatVisitor;
use exitcode::USAGE;
use std::fs;
use std::path::{Path, PathBuf};
/* --------------------------------------------------------------------- */
static IS_DEBUG: bool = false;
static FRAMEC_VERSION: &str = "emitted from framec_v0.7.3";
/* --------------------------------------------------------------------- */
pub struct Exe {}
impl Exe {
/* --------------------------------------------------------------------- */
pub fn new() -> Exe {
Exe {}
}
pub fn debug_print(msg: &str) {
if !IS_DEBUG {
return;
}
println!("{}", msg);
}
/* --------------------------------------------------------------------- */
pub fn run_file(
&self,
config_path: &Option<PathBuf>,
input_path: &Path,
output_format: String,
) -> Result<String, RunError> {
match fs::read_to_string(input_path) {
Ok(content) => {
Exe::debug_print(&(&content).to_string());
self.run(config_path, content, output_format)
}
Err(err) => {
let error_msg = format!("Error reading input file: {}", err);
let run_error = RunError::new(exitcode::NOINPUT, &*error_msg);
Err(run_error)
}
}
}
pub fn run(
&self,
config_path: &Option<PathBuf>,
content: String,
mut output_format: String,
) -> Result<String, RunError> {
// NOTE!!! There is a bug w/ the CLion debugger when a variable (maybe just String type)
// isn't initialized under some circumstances. Basically the debugger
// stops debugging or doesn't step and it looks like it hangs. To avoid
// this you have to initialize the variable, but the compiler then complains
// about the unused assignment. This can be squelched with `#[allow(unused_assignments)]`
// but I've reported it to JetBrains and want it fixed. So when you are
// debugging here, just uncomment the next line and then comment it back
// when checking in.
// let mut output= String::new();
let output;
let scanner = Scanner::new(content);
let (has_errors, errors, tokens) = scanner.scan_tokens();
if has_errors {
let run_error = RunError::new(frame_exitcode::PARSE_ERR, &*errors);
return Err(run_error);
}
for token in &tokens {
Exe::debug_print(&format!("{:?}", token));
}
let mut arcanum = Arcanum::new();
let mut comments = Vec::new();
// NOTE: This block is to remove references to symbol_table and comments
{
let mut syntactic_parser = Parser::new(&tokens, &mut comments, true, arcanum);
syntactic_parser.parse();
if syntactic_parser.had_error() {
let mut errors = "Terminating with errors.\n".to_string();
errors.push_str(&syntactic_parser.get_errors());
let run_error = RunError::new(frame_exitcode::PARSE_ERR, &errors);
return Err(run_error);
}
arcanum = syntactic_parser.get_arcanum();
}
let mut comments2 = comments.clone();
let mut semantic_parser = Parser::new(&tokens, &mut comments2, false, arcanum);
let system_node = semantic_parser.parse();
if semantic_parser.had_error() {
let mut errors = "Terminating with errors.\n".to_string();
errors.push_str(&semantic_parser.get_errors());
let run_error = RunError::new(frame_exitcode::PARSE_ERR, &errors);
return Err(run_error);
}
let generate_enter_args = semantic_parser.generate_enter_args;
let generate_exit_args = semantic_parser.generate_exit_args;
let generate_state_context = semantic_parser.generate_state_context;
let generate_state_stack = semantic_parser.generate_state_stack;
let generate_change_state = semantic_parser.generate_change_state;
let generate_transition_state = semantic_parser.generate_transition_state;
// check for local config.yaml if no path specified
let mut local_config_path = config_path;
let config_yaml = PathBuf::from("config.yaml");
let some_config_yaml = Some(config_yaml.clone());
if local_config_path.is_none() && config_yaml.exists() {
local_config_path = &some_config_yaml;
}
// load configuration
let config = match FrameConfig::load(local_config_path, &system_node) {
Ok(cfg) => cfg,
Err(err) => {
let run_error = RunError::new(frame_exitcode::CONFIG_ERR, &err.to_string());
return Err(run_error);
}
};
match &system_node.attributes_opt {
Some(attributes) => {
if let Some(language) = attributes.get("language") {
output_format = language.value.clone();
}
}
None => {}
}
if output_format == "javascript" {
let mut visitor = JavaScriptVisitor::new(
semantic_parser.get_arcanum(),
generate_exit_args,
generate_enter_args || generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "cpp" {
let mut visitor = CppVisitor::new(
semantic_parser.get_arcanum(),
config,
generate_exit_args,
generate_enter_args || generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "c_sharp_bob" {
let mut visitor = CsVisitorForBob::new(
semantic_parser.get_arcanum(),
generate_exit_args,
generate_enter_args || generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "c_sharp" {
let mut visitor = CsVisitor::new(
semantic_parser.get_arcanum(),
generate_exit_args,
generate_enter_args || generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "gdscript" {
let mut visitor = GdScript32Visitor::new(
semantic_parser.get_arcanum(),
generate_exit_args,
generate_enter_args || generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "java_8" {
let mut visitor = Java8Visitor::new(
semantic_parser.get_arcanum(),
generate_exit_args,
generate_enter_args || generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "python_3" {
let mut visitor = PythonVisitor::new(
semantic_parser.get_arcanum(),
generate_exit_args,
generate_enter_args || generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "plantuml" {
let (arcanum, system_hierarchy) = semantic_parser.get_all();
let mut visitor = PlantUmlVisitor::new(
arcanum,
system_hierarchy,
generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
FRAMEC_VERSION,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "rust" {
let mut visitor = RustVisitor::new(
FRAMEC_VERSION,
config,
semantic_parser.get_arcanum(),
generate_enter_args,
generate_exit_args,
generate_state_context,
generate_state_stack,
generate_change_state,
generate_transition_state,
comments,
);
visitor.run(&system_node);
output = visitor.get_code();
} else if output_format == "smcat" {
let mut visitor = SmcatVisitor::new(
FRAMEC_VERSION,
config,
semantic_parser.get_system_hierarchy(),
);
visitor.run(&system_node);
output = visitor.get_code();
// } else if output_format == "xstate" {
// let mut visitor = XStateVisitor::new(semantic_parser.get_arcanum()
// , generate_exit_args
// , generate_state_context
// , generate_state_stack
// , generate_change_state
// , generate_transition_state
// , FRAMEC_VERSION
// , comments);
// visitor.run(&system_node);
// return visitor.get_code();
} else {
let error_msg = &format!("Error - unrecognized output format {}.", output_format);
let run_error = RunError::new(USAGE, error_msg);
return Err(run_error);
}
Ok(output)
// let mut graphviz_visitor = GraphVizVisitor::new(semantic_parser.get_arcanum(), comments);
// graphviz_visitor.run(&system_node);
// println!("{}", graphviz_visitor.code);
}
}
impl Default for Exe {
fn default() -> Self {
Exe::new()
}
}
|
<div class="dropdown-menu">
@foreach($items->where('parent_id', $item->id) as $item)
<a class="dropdown-item" href="{{ $item->url }}" target="{{ $item->target }}">
<span style="color:{{ $item->color }}">
@if($item->icon_class)
<i class="nav-icon {{ $item->icon_class }}"></i>
@endif
{{ $item->title }}
</span>
</a>
@if($item->divider)
<div class="dropdown-divider"></div>
@endif
@endforeach
</div>
|
## zen6 4k ##
ELO: 1151
Opponent | Rank | ELO | Black | White | Total | Win rate
---------|-----:|----:|-------|-------|-------|-------:
[LZ LM 30BOZ02 0.1k](LZ%20LM%2030BOZ02%200.1k.md) | 2D | 2102 | 0 / 1 | - | 0 / 1 | 0.0%
[zen7 1k](zen7%201k.md) | 1k | 1668 | - | 0 / 1 | 0 / 1 | 0.0%
[pachi nodcnn 3k](pachi%20nodcnn%203k.md) | 2k | 1535 | 1 / 2 | 0 / 1 | 1 / 3 | 33.3%
[LZ 041](LZ%20041.md) | 2k | 1534 | 2 / 2 | - | 2 / 2 | 100.0%
[zen6 1k](zen6%201k.md) | 2k | 1487 | 0 / 1 | 0 / 2 | 0 / 3 | 0.0%
[LZ 038](LZ%20038.md) | 2k | 1436 | 0 / 1 | 1 / 1 | 1 / 2 | 50.0%
[fuego 1.1 5M](fuego%201.1%205M.md) | 2k | 1435 | 0 / 2 | 0 / 2 | 0 / 4 | 0.0%
[LZ 039](LZ%20039.md) | 2k | 1433 | 0 / 2 | 1 / 2 | 1 / 4 | 25.0%
[RN4.32 0.3k](RN4.32%200.3k.md) | 2k | 1430 | 2 / 3 | 0 / 2 | 2 / 5 | 40.0%
[zen7 3k](zen7%203k.md) | 3k | 1392 | 0 / 2 | 1 / 3 | 1 / 5 | 20.0%
[pachi 12.20 nodcnn 1k](pachi%2012.20%20nodcnn%201k.md) | 3k | 1390 | 0 / 1 | 0 / 3 | 0 / 4 | 0.0%
[pachi nodcnn 1k](pachi%20nodcnn%201k.md) | 3k | 1356 | 0 / 1 | 0 / 3 | 0 / 4 | 0.0%
[zen6 2k](zen6%202k.md) | 3k | 1348 | 0 / 3 | 0 / 10 | 0 / 13 | 0.0%
[zen7 4k](zen7%204k.md) | 3k | 1313 | 0 / 1 | 1 / 14 | 1 / 15 | 6.7%
[zen7 5k](zen7%205k.md) | 3k | 1284 | 5 / 13 | 0 / 8 | 5 / 21 | 23.8%
[zen6 3k](zen6%203k.md) | 3k | 1267 | 0 / 1 | 7 / 22 | 7 / 23 | 30.4%
[LZ 036](LZ%20036.md) | 3k | 1247 | 0 / 3 | 5 / 22 | 5 / 25 | 20.0%
[gnugo 3.8 lv1](gnugo%203.8%20lv1.md) | 3k | 1210 | 13 / 23 | 2 / 3 | 15 / 26 | 57.7%
[gnugo 3.8 lvX](gnugo%203.8%20lvX.md) | 4k | 1187 | 4 / 8 | 6 / 14 | 10 / 22 | 45.5%
[fuego 1.1 1M](fuego%201.1%201M.md) | 4k | 1172 | 5 / 19 | 8 / 13 | 13 / 32 | 40.6%
[LZ 033](LZ%20033.md) | 4k | 1138 | 14 / 21 | 1 / 2 | 15 / 23 | 65.2%
[zen6 5k](zen6%205k.md) | 4k | 1133 | 10 / 19 | 2 / 2 | 12 / 21 | 57.1%
[zen7 6k](zen7%206k.md) | 4k | 1041 | 8 / 12 | 7 / 13 | 15 / 25 | 60.0%
[zen6 6k](zen6%206k.md) | 4k | 1035 | 6 / 10 | 12 / 16 | 18 / 26 | 69.2%
[zen6 7k](zen6%207k.md) | 4k | 1022 | 19 / 20 | 3 / 3 | 22 / 23 | 95.7%
[RN4.32 0.2k](RN4.32%200.2k.md) | 5k | 999 | 5 / 8 | 3 / 3 | 8 / 11 | 72.7%
[LZ 031](LZ%20031.md) | 5k | 972 | 5 / 5 | 4 / 7 | 9 / 12 | 75.0%
[zen7 7k](zen7%207k.md) | 5k | 935 | 3 / 4 | 1 / 4 | 4 / 8 | 50.0%
[zen6 8k](zen6%208k.md) | 5k | 899 | 7 / 7 | 3 / 3 | 10 / 10 | 100.0%
[DariushGTP3.1.5.7 lv7](DariushGTP3.1.5.7%20lv7.md) | 5k | 827 | 2 / 2 | 5 / 5 | 7 / 7 | 100.0%
[LZ 026](LZ%20026.md) | 6k | 786 | 4 / 4 | 5 / 5 | 9 / 9 | 100.0%
[zen6 9k](zen6%209k.md) | 6k | 779 | 3 / 4 | - | 3 / 4 | 75.0%
[zen7 8k](zen7%208k.md) | 6k | 771 | 2 / 2 | 2 / 2 | 4 / 4 | 100.0%
[MoGo release3 1k](MoGo%20release3%201k.md) | 6k | 726 | 2 / 3 | 7 / 10 | 9 / 13 | 69.2%
[LZ 021](LZ%20021.md) | 6k | 651 | 2 / 2 | 1 / 1 | 3 / 3 | 100.0%
[aya 6.34](aya%206.34.md) | 7k | 554 | 3 / 3 | - | 3 / 3 | 100.0%
Total | | | 127 / 241 | 88 / 176 | 215 / 417 |
Win rate| | | 52.7% | 50.0% | 51.6% |
|
import Errors from "../errors";
import { Logger } from "../../../domain/utilities";
import { MultiMessages } from "../helpers";
// **==========================================================================
// ** Server Error Handler
// **==========================================================================
// eslint-disable-next-line no-unused-vars
export default (err, req, res, _) => {
const handledError = Errors.errorHandler(err);
const message =
typeof handledError.message === "string"
? req.t(handledError.message)
: MultiMessages(handledError.message, req);
if (
handledError.statusCode === 500 ||
process.env.NODE_ENV === "Development"
) {
Logger.error(
`${handledError.statusCode} - ${
handledError.statusCode === 500 ? handledError.error : message
} - ${req.method} ${req.originalUrl} - ${req.ip}`
);
}
return res.status(handledError.statusCode).send({
error: message,
});
};
|
use std::fmt;
use std::rc::Rc;
use ::bits::{DNameBuf, DNameSlice, RecordData};
use ::iana::{Class, Rtype};
use ::rdata::MasterRecordData;
use super::{ScanError, ScanResult, Scanner, SyntaxError};
#[derive(Clone, Debug)]
pub struct MasterRecord {
pub owner: Rc<DNameBuf>,
pub class: Class,
pub ttl: u32,
pub rdata: MasterRecordData,
}
impl MasterRecord {
pub fn new(owner: Rc<DNameBuf>, class: Class, ttl: u32,
rdata: MasterRecordData) -> Self {
MasterRecord { owner: owner, class: class,
ttl: ttl, rdata: rdata }
}
}
impl MasterRecord {
pub fn scan<S: Scanner>(stream: &mut S,
last_owner: Option<Rc<DNameBuf>>,
last_class: Option<Class>,
origin: &Option<Rc<DNameBuf>>,
default_ttl: Option<u32>) -> ScanResult<Self> {
let owner = try!(MasterRecord::scan_owner(stream, last_owner,
origin));
let (ttl, class) = try!(MasterRecord::scan_ttl_class(stream,
default_ttl,
last_class));
let rtype = try!(Rtype::scan(stream));
let rdata = try!(MasterRecordData::scan(rtype, stream,
map_origin(origin)));
try!(stream.scan_newline());
Ok(MasterRecord::new(owner, class, ttl, rdata))
}
/// Scans the owner.
///
/// Returns new owner and origin.
fn scan_owner<S: Scanner>(stream: &mut S,
last_owner: Option<Rc<DNameBuf>>,
origin: &Option<Rc<DNameBuf>>)
-> ScanResult<Rc<DNameBuf>> {
let pos = stream.pos();
if let Ok(()) = stream.scan_space() {
if let Some(owner) = last_owner { Ok(owner) }
else { Err(ScanError::Syntax(SyntaxError::NoLastOwner, pos)) }
}
else if let Ok(()) = stream.skip_literal(b"@") {
if let Some(ref origin) = *origin { Ok(origin.clone()) }
else { Err(ScanError::Syntax(SyntaxError::NoOrigin, pos)) }
}
else {
Ok(Rc::new(try!(stream.scan_dname(map_origin(origin)))))
}
}
fn scan_ttl_class<S: Scanner>(stream: &mut S, default_ttl: Option<u32>,
last_class: Option<Class>)
-> ScanResult<(u32, Class)> {
let pos = stream.pos();
let (ttl, class) = match stream.scan_u32() {
Ok(ttl) => {
match Class::scan(stream) {
Ok(class) => {
(Some(ttl), Some(class))
}
Err(_) => (Some(ttl), None)
}
}
Err(_) => {
match Class::scan(stream) {
Ok(class) => {
match stream.scan_u32() {
Ok(ttl) => {
(Some(ttl), Some(class))
}
Err(_) => (None, Some(class))
}
}
Err(_) => (None, None)
}
}
};
let ttl = match ttl.or(default_ttl) {
Some(ttl) => ttl,
None => {
return Err(ScanError::Syntax(SyntaxError::NoDefaultTtl, pos))
}
};
let class = match class.or(last_class) {
Some(class) => class,
None => {
return Err(ScanError::Syntax(SyntaxError::NoLastClass, pos))
}
};
Ok((ttl, class))
}
}
impl fmt::Display for MasterRecord {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {} {} {}",
self.owner, self.ttl, self.class,
self.rdata.rtype(), self.rdata)
}
}
pub fn map_origin(origin: &Option<Rc<DNameBuf>>) -> Option<&DNameSlice> {
match *origin {
Some(ref rc) => Some(rc),
None => None
}
}
|
import { Payment } from "./payment";
export interface Penguin {
id: string;
price: Payment;
timestamp: string;
fromAddress: string;
toAddresss: string;
url: string;
}
|
<?php
/*
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.
*/
require_once("../settings.inc");
require_once("../utils.inc");
// $gParamLabel is a hack to allow for require(copy.php)
$gLabel = ( isset($gParamLabel) ? $gParamLabel : $argv[1] );
if ( !$gLabel ) {
lprint("You must specify a label.");
exit();
}
// find min & max pageid of the specified run
$crawl = getCrawl($gLabel);
$minid = $crawl['minPageid'];
$maxid = $crawl['maxPageid'];
lprint("Run \"$gLabel\": min pageid = $minid, max pageid = $maxid");
// copy the rows to production
$pageidCond = "pageid >= $minid and pageid <= $maxid";
if ( $gbDev && ( $gPagesTableDesktop != $gPagesTableDev ) ) {
$count = doSimpleQuery("select count(*) from $gPagesTableDesktop where $pageidCond;");
if ( $count ) {
lprint("Rows already copied.");
}
else {
//lprint("Copy 'requests' rows to production...");
//doSimpleCommand("insert into $gRequestsTableDesktop select * from $gRequestsTableDev where $pageidCond;");
lprint("Copy 'pages' rows to production...");
doSimpleCommand("insert into $gPagesTableDesktop select * from $gPagesTableDev where $pageidCond;");
lprint("...DONE.");
}
}
// orphaned records
lprint("Checking for orphaned records...");
$numOrphans = doSimpleQuery("select count(*) from $gRequestsTable where $pageidCond and pageid not in (select pageid from $gPagesTable where $pageidCond);");
if ( $numOrphans ) {
lprint("There are $numOrphans orphaned records in the \"$gRequestsTable\" table.");
$cmd = "delete from $gRequestsTable where $pageidCond and pageid not in (select pageid from $gPagesTable where $pageidCond);";
if ( $numOrphans < 5000 ) {
lprint("Deleting orphans now...");
doSimpleCommand($cmd);
}
else {
lprint("You should delete them, recalculate the stats, and regenerate the mysql dump files.\n $cmd");
}
}
else {
lprint("No orphaned records.");
}
// Compute stats
require_once("../stats.inc");
require_once("../dbapi.inc");
$device = curDevice();
if ( getStats($gLabel, "All", $device) ) {
lprint("Stats already computed.");
}
else {
lprint("Computing stats for $gLabel $device...");
replaceStats($gLabel, null, $device, null, $crawl['crawlid']);
if ( $gbDev && ( $gStatsTableDesktop != $gStatsTableDev ) ) {
lprint("Copy stats to production...");
$cmd = "replace into $gStatsTableDesktop select * from $gStatsTableDev where label='$gLabel' and device='$device';";
doSimpleCommand($cmd);
}
lprint("...stats computed and copied.");
}
// mysqldump files
if ( $gbDev || $gbMobile || $gbChrome || $gbAndroid || $gbIe || $gbIphone ) {
dumpCrawl($gLabel);
dumpOther();
}
cprint(date("G:i") . ": DONE finalizing latest run.");
?>
|
import AbstractFibreListener = require('plugins/common/views/AbstractFibreListener');
import Backbone = require('backbone');
import AlertNotificationView = require('weaver/views/AlertNotificationView');
import ViewFibreOptions = require('plugins/interfaces/ViewFibreOptions');
import FibreBuilder = require('../layout/FibreBuilder');
class FibreView extends AbstractFibreListener {
static factory(options: ViewFibreOptions<FibreBuilder>): FibreView {
return new FibreView(options);
}
thread: Thread;
alertNotificationView: AlertNotificationView;
constructor(options?: ViewFibreOptions<FibreBuilder>) {
super(options);
this.thread = options.thread;
this.alertNotificationView = new AlertNotificationView({
// TODO: Fix this once tsdgen annotations have been updated.
model: this.model ? (<any>this.model).alert : undefined
});
this.alertNotificationView.$el.addClass('mas-fiberOverview--alert')
.appendTo(this.$el);
// TODO: Fix this once tsdgen annotations have been updated
this.$('.mas-fiberOverview--label').append((<any>this.model).getTranslated('name'));
}
protected _updateElementDetails(selected: boolean): void {
// TODO: FIXME
if (selected) {
this.dispatchCustomEvent('element:show-details', {
args: true,
model: this.model,
thread: this.thread,
});
} else {
this.dispatchCustomEvent('element:show-details', {
args: false,
});
}
}
protected _updateChangedAttributesFullList(attributes: Array<string>): void {
// Does nothing
}
}
export = FibreView;
|
package sq
import "testing"
func TestAppendAndReplace(t *testing.T) {
tests := []struct {
input string
exp1 string // mysql
exp2 string // postgres
}{
{
`sample`,
`sample`,
`sample`,
},
{
`foo = ? AND bar = ?`,
`foo = ? AND bar = ?`,
`foo = $1 AND bar = $2`,
},
{
`"foo" = ? AND "bar" = ?`,
"`foo` = ? AND `bar` = ?",
`"foo" = $1 AND "bar" = $2`,
},
{
`INSERT INTO "user"("id", "name") VALUES (?,?)`,
"INSERT INTO `user`(`id`, `name`) VALUES (?,?)",
`INSERT INTO "user"("id", "name") VALUES ($1,$2)`,
},
{
`$.deleted_at IS NULL`,
`schema.deleted_at IS NULL`,
`schema.deleted_at IS NULL`,
},
{
`INSERT INTO $."user"("id", "name") VALUES (?,?)`,
"INSERT INTO schema.`user`(`id`, `name`) VALUES (?,?)",
`INSERT INTO schema."user"("id", "name") VALUES ($1,$2)`,
},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
{
var b []byte
output := appendAndReplace(b, nil, '`', '?', tt.input, "schema")
if string(output) != tt.exp1 {
t.Errorf("\nExpect: %s\nOutput: %s\n", tt.exp1, output)
}
}
{
var b []byte
var c int64
output := appendAndReplace(b, &c, '"', '$', tt.input, "schema")
if string(output) != tt.exp2 {
t.Errorf("\nExpect: %s\nOutput: %s\n", tt.exp2, output)
}
}
})
}
}
|
# 今後やること
- Effectクラスをつくる
- すげー適当なカードを実装する
## 2020/5/28 やること
- ダイスの面を買いたい
- ダイス屋さんをつくる
- [x] ダイスの面を自由に変えるコマンドを追加する
- [x] 自分のダイスを見る
- [x] まずダイスを保持し\ているのか?
- [x] まずプレイヤーを保持しているのか?
- -> [x] 今自分が何を操作してるのか確認
|
package xvals
import (
"log"
"os"
"gopkg.in/yaml.v3"
)
type ProfileFile struct {
CurrentProfile string `yaml:"current_profile"`
Profiles map[string]map[string]string `yaml:"profiles"`
}
// profileProvider is an xvals provider holding several profiles of values
type profileProvider struct {
mapProvider
filename string
}
// WithProfile adds a file that has a one or several profiles, which of one
// is the current profile. Each profile is a mapProvider
func WithProfile(profileFilePath string) XvalProvider {
p := &profileProvider{filename: profileFilePath}
p.Reload()
ctxt = append(ctxt, p)
return p
}
// Reload the profile file
func (c *profileProvider) Reload() {
data, err := os.ReadFile(c.filename)
if err != nil {
log.Printf("failed to load file %s %v", c.filename, err)
}
content := &ProfileFile{}
err = yaml.Unmarshal(data, content)
if err != nil {
log.Printf("failed to parse file %s %v", c.filename, err)
}
cp, ok := content.Profiles[content.CurrentProfile]
if ok {
c.mapProvider = mapProvider{vals: cp}
return
}
log.Printf("current profile %s is not available in profile file %s", content.CurrentProfile, c.filename)
}
|
using Microsoft.AspNetCore.Identity;
using System;
using System.ComponentModel.DataAnnotations;
namespace ThingLing.Shared.Models.UserAccount
{
public class ApplicationUser : IdentityUser
{
[Display(Name = "Date created")]
public DateTimeOffset DateCreated { get; set; }
}
}
|
<?php
namespace App\Renderers;
use App\Game;
class BlinkstickRenderer implements Renderer
{
private $itemPositions = [];
public function __construct()
{
$this->resetLeds();
}
public function render($state)
{
//$this->renderWithPulses($state);
//$this->renderWithSetLed($state);
$this->renderWithSetAll($state);
}
private function renderWithPulses($state)
{
foreach ($state['items'] as $item) {
$position = (int) floor($item->position);
if (array_key_exists($item->id, $this->itemPositions) && $this->itemPositions[$item->id] === $position) {
continue;
}
$this->pulseLed($position, 200, $item->color);
$this->itemPositions[$item->id] = $position;
}
}
private function renderWithSetLed($state)
{
foreach ($state['items'] as $item) {
$position = (int) floor($item->position);
if (array_key_exists($item->id, $this->itemPositions) && $this->itemPositions[$item->id] === $position) {
continue;
}
$this->setLed($position, $item->color);
if (array_key_exists($item->id, $this->itemPositions)) {
$this->setLed($this->itemPositions[$item->id], 'black');
}
$this->itemPositions[$item->id] = $position;
}
}
private function renderWithSetAll($state)
{
$data = [];
for ($i =0; $i < Game::BOARD_LENGTH; $i++) {
$color = [0, 0, 0];
foreach ($state['items'] as $item) {
if ((int) floor($item->position) === $i) {
$color = $item->colorRGB;
}
}
$data = array_merge($data, $color);
}
$this->setAllLeds($data);
}
/**
* Uses a nodejs script to interact with the blinkstick
*
* @param int $position
* @param int $duration
* @param string $color
* @return void
*/
private function pulseLed(int $position, int $duration, string $color)
{
//$command = resource_path('js/pulseLed.js') . " --index=$position --duration=$duration --color=$color";
$command = "blinkstick --pulse --index=$position --duration=$duration '$color'";
$logFile = storage_path('logs/blink.txt');
exec($command . " > $logFile &");
echo $command . "\n";
}
private function setLed(int $position, string $color)
{
$command = resource_path('js/setLed.js') . " --index=$position --color=$color";
$logFile = storage_path('logs/blink.txt');
echo $command . "\n";
exec($command . " > $logFile &");
}
private function setAllLeds(array $data)
{
$command = resource_path("js/setAllLeds.js --data='" . json_encode($data) . "'");
$logFile = storage_path('logs/blink.txt');
echo $command . "\n";
exec($command . " > $logFile &");
}
/**
* Resets the leds back to black
*/
private function resetLeds()
{
$data = array_fill(0, Game::BOARD_LENGTH * 3, 0);
$this->setAllLeds($data);
}
}
|
import styled from 'styled-components';
export const HeaderWrapper = styled.header`
width: 100%;
max-width: 1200px;
top: 0;
position: fixed;
box-shadow: 0 4px 10px var(--color-header-shadow);
background: var(--color-header);
margin: 0 auto;
`;
export const HeaderNav = styled.nav`
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.8rem 2rem;
`;
export const HeaderName = styled.h1`
font-size: 1.5rem;
color: var(--color-header-title);
`;
export const HeaderImageWrapper = styled.div`
overflow: hidden;
border-radius: 50%;
max-width: 4rem;
max-height: 4rem;
background-position: center;
background-size: cover;
`;
export const HeaderImage = styled.img`
width: 100%;
`;
|
using NAudio.CoreAudioApi;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace AudioRecorder
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly List<MMDevice> _mmDevices;
private IWaveIn capture;
private WaveFileWriter writer;
private bool _isRecording = false;
public MainWindow()
{
InitializeComponent();
this._mmDevices = GetMMDevices().ToList();
DeviceSelectCombobox.ItemsSource = _mmDevices.ToDictionary(d => d.ID, d => d.FriendlyName);
DeviceSelectCombobox.DisplayMemberPath = "Value";
DeviceSelectCombobox.SelectedValuePath = "Key";
}
private async void StartStopRecordingButton_Click(object sender, RoutedEventArgs e)
{
_isRecording = !_isRecording;
if (_isRecording)
{
StartStopRecordingButton.Content = "Stop";
StartRecording();
}
else
{
StartStopRecordingButton.Content = "Start";
StopRecording();
}
}
private void StartRecording()
{
var selectedDevice = this._mmDevices.Single(d => d.ID == (string)DeviceSelectCombobox.SelectedValue);
capture = new WasapiLoopbackCapture(selectedDevice);
capture.RecordingStopped += (s, a) =>
{
writer.Dispose();
writer = null;
capture.Dispose();
capture = null;
};
capture.DataAvailable += (s, waveInEventArgs) =>
{
if (writer == null)
{
writer = new WaveFileWriter("test.wav", capture.WaveFormat);
}
writer.Write(waveInEventArgs.Buffer, 0, waveInEventArgs.BytesRecorded);
};
capture.StartRecording();
}
private void StopRecording()
{
capture?.StopRecording();
}
private IEnumerable<MMDevice> GetMMDevices()
{
var enumerator = new MMDeviceEnumerator();
foreach (var mmDevice in enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))
{
yield return mmDevice;
}
}
}
}
|
# Snowman Library
This package contains shared code from app and wrapper.
## Development
If you change any code in this package, please run `npm run build` and make sure to commit `./src` as well as `./lib`!
|
require 'test_helper'
class ScheduledMessagesControllerTest < ActionController::TestCase
test "current message should redirect" do
m = scheduled_messages(:message_2)
m.scheduled_at = Time.now - 10.minutes
m.save!
post :show, params: {id: m.id}
assert_redirected_to %r(qualtrics.com)
refute assigns(:expired_string)
end
test "older than 30 minutes message should show expired message" do
m = scheduled_messages(:message_1)
m.scheduled_at = Time.now - 40.minutes
m.save!
post :show, params: {id: scheduled_messages(:message_1).id}
assert_response :success
assert_select 'h3', /expired \d+ minutes ago/
end
test "survey can extend default message expiration length" do
s = surveys(:link)
s.message_expiration_minutes = 60
s.save!
m = scheduled_messages(:message_1)
m.scheduled_at = Time.now - 40.minutes
m.save!
post :show, params: {id: m.id}
assert_redirected_to %r(qualtrics.com)
refute assigns(:expired_string)
end
test "custom expiry should show expired message" do
m = scheduled_messages(:message_1)
m.scheduled_at = Time.now - 10.minutes
m.expires_at = Time.now - 5.minutes
m.save!
post :show, params: {id: scheduled_messages(:message_1).id}
assert_response :success
assert_select 'h3', /expired \d+ minutes ago/
end
test "custom expiry that's longer should redirect" do
m = scheduled_messages(:message_1)
m.scheduled_at = Time.now - 160.minutes
m.expires_at = Time.now + 15.minutes
m.save!
post :show, params: {id: scheduled_messages(:message_1).id}
assert_redirected_to %r(qualtrics.com)
refute assigns(:expired_string)
end
test "not found message should show expired with a 404" do
post :show, params: {id: 99999}
assert_response :not_found
assert_select 'h3', /expired/
end
test "generic completion page" do
get :complete
assert_response :success
assert_select 'h3', /complete/
end
end
|
"""
Extension Class
"""
from threading import Timer
from ulauncher.api.client.Extension import Extension
from ulauncher.api.shared.event import KeywordQueryEvent, ItemEnterEvent
from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem
from ulauncher.api.shared.item.ExtensionSmallResultItem import ExtensionSmallResultItem
from ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction
from ulauncher.api.shared.action.CopyToClipboardAction import CopyToClipboardAction
from ulauncher.api.shared.action.HideWindowAction import HideWindowAction
from ulauncher.api.shared.action.ExtensionCustomAction import ExtensionCustomAction
from brotab.client import BrotabClient
from brotab.listeners import KeywordQueryEventListener, ItemEnterEventListener
from brotab.actions import RESULT_ITEM_ENTER, REFRESH_TABS
from gi.repository import Notify
DISPLAY_MAX_RESULTS = 20
INDEX_REFRESH_TIME_SECONDS = 60
class BrotabExtension(Extension):
""" Main Extension Class """
def __init__(self):
""" Initializes the extension """
super(BrotabExtension, self).__init__()
self.logger.info("Initializing Brotab Extension")
Notify.init(__name__)
self.brotab_client = BrotabClient()
if not self.brotab_client.is_installed():
raise EnvironmentError("Brotab is not installed on your system. \
Please see https://github.com/balta2ar/brotab for instructions.")
self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())
self.subscribe(ItemEnterEvent, ItemEnterEventListener())
self.index_tabs()
def index_tabs(self):
""" Index brotab tabs """
self.brotab_client.index()
# Timer(INDEX_REFRESH_TIME_SECONDS, self.index_tabs).start()
def show_commands(self, arg):
""" Show Extension commands """
return RenderResultListAction([
ExtensionResultItem(icon='images/icon.png',
name='Refresh Tabs',
highlightable=False,
on_enter=ExtensionCustomAction({
"action": REFRESH_TABS,
}, keep_app_open=True))
])
def show_no_results_message(self):
""" Shows empty list results """
return RenderResultListAction([
ExtensionResultItem(icon='images/icon.png',
name='No tabs found matching your criteria',
highlightable=False,
on_enter=HideWindowAction())
])
def notify(self, text):
""" Shows Notification """
Notify.Notification.new("Brotab", text).show()
def search_tabs(self, event):
""" Search tabs """
items = []
self.brotab_client.index()
tabs = self.brotab_client.search_tabs(event.get_argument())
for tab in tabs[:DISPLAY_MAX_RESULTS]:
data = {"action": RESULT_ITEM_ENTER, 'tab': tab['prefix']}
items.append(
ExtensionSmallResultItem(icon='images/%s' % tab["icon"],
name=tab["name"],
description=tab['url'],
on_enter=ExtensionCustomAction(data),
on_alt_enter=CopyToClipboardAction(tab["url"])))
if not items:
return self.show_no_results_message()
return RenderResultListAction(items)
|
import { ApiModelProperty } from '@nestjs/swagger';
import { DecisionDto } from './decision/decision.docs';
export class CaseDto {
@ApiModelProperty({ required: false, description: 'case number' })
id: number;
@ApiModelProperty({ required: false, description: 'case number' })
caseNumber: string;
@ApiModelProperty({ required: false, description: 'subject' })
subject: string;
@ApiModelProperty({ required: false, description: 'file location' })
fileLocation: string;
@ApiModelProperty({ required: false, description: 'claimed amount' })
claimedAmount: number;
@ApiModelProperty({ required: false, description: 'submit date' })
submitDate: Date;
@ApiModelProperty({ required: false, description: 'registration date' })
registrationDate: Date;
@ApiModelProperty({ required: false, description: 'first session date' })
firstSessionDate: Date;
@ApiModelProperty({ required: false, description: 'case status' })
caseStatus: string;
@ApiModelProperty({ required: false, description: 'next session date' })
nextSessionDate: Date;
@ApiModelProperty({ required: false, description: 'hall' })
hall: string;
@ApiModelProperty({ required: false, description: 'secretary name' })
secretaryName: string;
// @ApiModelProperty({ required: false, description: 'last decision' })
// lastDecisions: DecisionDto;
@ApiModelProperty({ required: false, description: 'latest session date' })
latestSessionDate: Date;
@ApiModelProperty({ required: false, description: 'root case number' })
rootCaseNumber: string;
@ApiModelProperty({ required: false, description: 'date of assignation' })
dateOfAssignation: Date;
@ApiModelProperty({ required: false, description: 'meeting date' })
meetingDate: Date;
@ApiModelProperty({ required: false, description: 'due date' })
dueDate: Date;
@ApiModelProperty({ required: false, description: 'managed by' })
managedBy: string;
@ApiModelProperty({ required: false, description: 'payment amount' })
paymentAmount: number;
@ApiModelProperty({ required: false, description: 'payment status' })
paymentStatus: string; // mozda enum
@ApiModelProperty({ required: false, description: 'parties addresses' })
partiesAddresses: string[];
@ApiModelProperty({ required: false, description: 'parties names' })
partiesNames: string[];
@ApiModelProperty({ required: false, description: 'notes' })
notes: string[];
@ApiModelProperty({ required: false, description: 'attachements' })
attachments: FileDto[];
@ApiModelProperty({ required: false, description: 'petitionsAttachements' })
petitionsAttachments: FileDto[];
@ApiModelProperty({ required: false, description: 'exhibits' })
exhibits: ExhibitDto[];
@ApiModelProperty({ required: false, description: 'notices' })
notices: NoticeDto[];
@ApiModelProperty({ required: false, description: 'decisions' })
decisions: DecisionDto[];
@ApiModelProperty({ required: false, description: 'petitions' })
petitions: PetitionDto[];
@ApiModelProperty({ required: false, description: 'verdicts' })
verdicts: VerdictDto[];
@ApiModelProperty({ required: false, description: 'depositVouchers' })
depositVouchers: DepositVoucherDto[];
@ApiModelProperty({ required: false, description: 'claims' })
claims: ClaimDto[];
}
export class CreateCaseDto {
@ApiModelProperty({ required: false, description: 'case number' })
caseNumber: string;
@ApiModelProperty({ required: false, description: 'subject' })
subject: string;
@ApiModelProperty({ required: false, description: 'file location' })
fileLocation: string;
@ApiModelProperty({ required: false, description: 'claimed amount' })
claimedAmount: number;
@ApiModelProperty({ required: false, description: 'submit date' })
submitDate: Date;
@ApiModelProperty({ required: false, description: 'registration date' })
registrationDate: Date;
@ApiModelProperty({ required: false, description: 'first session date' })
firstSessionDate: Date;
@ApiModelProperty({ required: false, description: 'case status' })
caseStatus: string;
@ApiModelProperty({ required: false, description: 'next session date' })
nextSessionDate: Date;
@ApiModelProperty({ required: false, description: 'hall' })
hall: string;
@ApiModelProperty({ required: false, description: 'secretary name' })
secretaryName: string;
@ApiModelProperty({ required: false, description: 'latest session date' })
latestSessionDate: Date;
@ApiModelProperty({ required: false, description: 'root case number' })
rootCaseNumber: string;
@ApiModelProperty({ required: false, description: 'date of assignation' })
dateOfAssignation: Date;
@ApiModelProperty({ required: false, description: 'meeting date' })
meetingDate: Date;
@ApiModelProperty({ required: false, description: 'due date' })
dueDate: Date;
@ApiModelProperty({ required: false, description: 'managed by' })
managedBy: string;
@ApiModelProperty({ required: false, description: 'payment amount' })
paymentAmount: number;
@ApiModelProperty({ required: false, description: 'payment status' })
paymentStatus: string; // mozda enum
@ApiModelProperty({ required: false, description: 'parties addresses' })
partiesAddresses: string[];
@ApiModelProperty({ required: false, description: 'parties names' })
partiesNames: string[];
@ApiModelProperty({ required: false, description: 'notes' })
notes: string[];
}
export class FileDto {
@ApiModelProperty({ required: false, description: 'url' })
url: string;
@ApiModelProperty({ required: false, description: 'author' })
author: string;
@ApiModelProperty({ required: false, description: 'case id' })
caseId: string;
}
export class ClaimDto {
@ApiModelProperty({ required: false, description: 'initial amount' })
initialClaimAmount: Number;
@ApiModelProperty({ required: false, description: 'current claim amount' })
currentClaimAmount: Number;
@ApiModelProperty({ required: false, description: 'balance claim amount' })
balanceClaimAmount: Number;
@ApiModelProperty({ required: false, description: 'claim details' })
claimDetails: string;
@ApiModelProperty({ required: false, description: 'case id' })
caseId: string;
}
export class DepositVoucherDto {
@ApiModelProperty({ required: false, description: 'year' })
year: Number;
@ApiModelProperty({ required: false, description: 'type' })
type: string;
@ApiModelProperty({ required: false, description: 'amount' })
amount: Number;
@ApiModelProperty({ required: false, description: 'case id' })
caseId: string;
}
export class ExhibitDto {
@ApiModelProperty({ required: false, description: 'description' })
description: string;
@ApiModelProperty({ required: false, description: 'case id' })
caseId: string;
}
export class NoticeDto {
@ApiModelProperty({ required: false, description: 'notice number' })
noticeNumber: string;
@ApiModelProperty({ required: false, description: 'type' })
type: string;
@ApiModelProperty({ required: false, description: 'registration date' })
registrationDate: Date;
@ApiModelProperty({ required: false, description: 'links' })
links: string[];
@ApiModelProperty({ required: false, description: 'parties' })
parties: string[];
@ApiModelProperty({ required: false, description: 'case id' })
caseId: string;
}
export class PetitionDto {
@ApiModelProperty({ required: false, description: 'petition date' })
petitionDate: Date;
@ApiModelProperty({ required: false, description: 'subject' })
subject: string;
@ApiModelProperty({ required: false, description: 'links' })
links: string[];
@ApiModelProperty({ required: false, description: 'applicant' })
applicant: string;
@ApiModelProperty({ required: false, description: 'position number' })
positionNumber: number;
@ApiModelProperty({ required: false, description: 'decision number' })
decisionNumber: number;
@ApiModelProperty({ required: false, description: 'decision abstract' })
decisionAbstract: string;
@ApiModelProperty({ required: false, description: 'session date' })
sessionDate: Date;
@ApiModelProperty({ required: false, description: 'case id' })
caseId: string;
}
export class VerdictDto {
@ApiModelProperty({ required: false, description: '' })
verdict: string;
@ApiModelProperty({ required: false, description: 'case id' })
caseId: string;
}
|
package ratelimit
import (
"testing"
"time"
)
func TestMonitor_RecommendedWaitForBackgroundOp(t *testing.T) {
m := &Monitor{
known: true,
limit: 5000,
remaining: 1500,
reset: time.Now().Add(30 * time.Minute),
}
durationsApproxEqual := func(a, b time.Duration) bool {
d := a - b
if d < 0 {
d = -1 * d
}
return d < 2*time.Second
}
// The conservative handling of rate limiting means that the 1500 remaining
// will be treated as roughly 1050. For cost smaller than 1050, we should
// expect a time of (reset + 3 minutes) * cost / 1050. For cost greater than
// 1050, we should expect exactly reset + 3 minutes, because we won't wait
// past the reset, as there'd be no point.
tests := map[int]time.Duration{
1: 0,
10: 19 * time.Second,
100: 188 * time.Second,
500: 15*time.Minute + 43*time.Second,
3500: 33 * time.Minute,
}
for cost, want := range tests {
if got := m.RecommendedWaitForBackgroundOp(cost); !durationsApproxEqual(got, want) {
t.Errorf("for %d, got %s, want %s", cost, got, want)
}
}
// Verify that we use the full limit, not the remaining limit, if the reset
// time has passed. This should scale times based on 3,850 items in 63 minutes.
m.reset = time.Now().Add(-1 * time.Second)
tests = map[int]time.Duration{
1: 0, // Things you could do >=500 times should just run
10: 200 * time.Millisecond, // Things you could do 250-500 times in the limit should get 200ms
385: 378 * time.Second, // 1/10 of 63 minutes
9001: 3780 * time.Second, // The full reset period
}
for cost, want := range tests {
if got := m.RecommendedWaitForBackgroundOp(cost); !durationsApproxEqual(got, want) {
t.Errorf("with reset: for %d, got %s, want %s", cost, got, want)
}
}
}
|
#include "stringutil.h"
uint32_t indentCount(const QString& data, const QChar indentKey) {
uint32_t count = 0;
if (0 >= data.count()) {
return 0;
}
QString unIndentKeyData = data;
unIndentKeyData = unIndentKeyData.replace(indentKey, "");
if (0 >= unIndentKeyData.count()) {
return 0;
}
while (indentKey == data[count]) {
++count;
}
return count;
}
QString extractIndent(const QString& data, const QChar indentKey) {
QString indent;
return indent.fill(indentKey, indentCount(data, indentKey));
}
|
/*
* @Author: qiuz
* @Github: <https://github.com/qiuziz>
* @Date: 2020-12-09 14:14:02
* @Last Modified by: qiuz
*/
/**
* 等额本息计算方式
* 每月还款额=贷款本金×[月利率×(1+月利率)^还款月数]÷[(1+月利率)^还款月数-1]
* 总支付利息:总利息=还款月数×每月月供额-贷款本金
* 每月应还利息=贷款本金×月利率×〔(1+月利率)^还款月数-(1+月利率)^(还款月序号-1)〕÷〔(1+月利率)^还款月数-1〕
* 每月应还本金=贷款本金×月利率×(1+月利率)^(还款月序号-1)÷〔(1+月利率)^还款月数-1〕
* 总利息=还款月数×每月月供额-贷款本金
*
* 等额本金计算方式编辑
* 每月月供额=(贷款本金÷还款月数)+(贷款本金-已归还本金累计额)×月利率
* 每月应还本金=贷款本金÷还款月数
* 每月应还利息=剩余本金×月利率=(贷款本金-已归还本金累计额)×月利率。
* 每月月供递减额=每月应还本金×月利率=贷款本金÷还款月数×月利率
* 总利息=还款月数×(总贷款额×月利率-月利率×(总贷款额÷还款月数)*(还款月数-1)÷2+总贷款额÷还款月数)
*/
interface ParamsProps {
totalPrice: number;
commerceLoanYear: number;
commerceLoanRate: number;
commerceTotalPirce: number;
accumulatFundYear: number;
accumulatFundRate: number;
accumulatTotalPirce: number;
}
export const equalInterestCalc = ({
commerceLoanYear,
commerceLoanRate,
commerceTotalPirce,
accumulatFundYear,
accumulatFundRate,
accumulatTotalPirce
}: ParamsProps) =>
new Promise(resolve => {
const commerceMonth = commerceLoanYear * 12;
const commercePayMonty: number = getInterestEveryMonth(
commerceTotalPirce,
commerceLoanRate / 12,
commerceMonth
);
const accumlatMonth = accumulatFundYear * 12;
const accumlatPayMonty: number = getInterestEveryMonth(
accumulatTotalPirce,
accumulatFundRate / 12,
accumlatMonth
);
const interestTotal = getInterestTotal(
commercePayMonty * commerceMonth + accumlatPayMonty * accumlatMonth,
commerceTotalPirce + accumulatTotalPirce
);
const principalCommList = getPrincipalListByMonth(
commerceTotalPirce,
commerceLoanRate / 12,
commerceMonth
);
const principalAccuList = getPrincipalListByMonth(
accumulatTotalPirce,
accumulatFundRate / 12,
accumlatMonth
);
const principalList = mergeList(
principalCommList,
principalAccuList,
commerceMonth,
accumlatMonth
);
const principalTotal = getPrincipalTotal(
principalList,
commerceTotalPirce + accumulatTotalPirce
);
const equalInterestPayMonth = parseInt(
((commercePayMonty + accumlatPayMonty) * 10000).toFixed(0),
10
);
resolve({
equalInterest: {
payMonth: equalInterestPayMonth,
totalInterest: interestTotal.toFixed(1),
monthDecline: 0
},
equalPrincipal: {
payMonth: principalList[0],
totalInterest: principalTotal.toFixed(1),
monthDecline: principalList[0] - principalList[1]
},
equalInterestMonthList: new Array(
Math.max(commerceMonth, accumlatMonth)
).fill(equalInterestPayMonth),
equalPrincipalMonthList: principalList
});
});
/**
* 获取(等额本息)每月还款额
*
* @param loanTotalPrice 贷款总额
* @param monthLoanRate 每月利息
* @param monthNum 贷款期限(月份)
* @return
*/
const getInterestEveryMonth = (
loanTotalPrice: number,
monthLoanRate: number,
monthNum: number
): number => {
if (Math.pow(1 + monthLoanRate, monthNum) - 1 == 0) {
return 0;
}
return (
(loanTotalPrice * monthLoanRate * Math.pow(1 + monthLoanRate, monthNum)) /
(Math.pow(1 + monthLoanRate, monthNum) - 1)
);
};
/**
* 获取(等额本息)利息总额
*
* @param repaymentTotal 还款总额
* @param loanTotalPrice 贷款总额
* @return
*/
const getInterestTotal = (
repaymentTotal: number,
loanTotalPrice: number
): number => {
return repaymentTotal - loanTotalPrice;
};
const getPrincipalTotal = (list: number[], loanTotalPrice: number): number => {
return list.reduce((p, c) => p + c) / 10000 - loanTotalPrice;
};
const getPrincipalListByMonth = (
loanTotalPrice: number,
monthLoanRate: number,
monthNum: number
): number[] => {
const accumulatList: number[] = [];
let finshRepayTotal = 0;
for (let i = 0; i < monthNum; i++) {
const repayMonth =
loanTotalPrice / monthNum +
(loanTotalPrice - finshRepayTotal) * monthLoanRate;
finshRepayTotal = finshRepayTotal + loanTotalPrice / monthNum;
accumulatList.push(parseInt((repayMonth * 10000).toFixed(0), 10));
}
return accumulatList;
};
/**
* 在组合贷款下拼接(等额本金)和(等额本金)分月还款额
*
* @param commList 商业贷款分月还款数额列表
* @param accuList 公积金贷款分月还款数额列表
* @param commMonthNum 商业贷款期限(月份)
* @param accuMonthNum 公积金贷款期限(月份)
* @return
*/
const mergeList = (
commList: number[],
accuList: number[],
commMonthNum: number,
accuMonthNum: number
): number[] => {
const size = Math.min(commMonthNum, accuMonthNum);
const list: number[] = [];
for (let i = 0; i < size; i++) {
list.push((commList[i] || 0) + (accuList[i] || 0));
}
return list;
};
|
class <%= identity_model_class %> < ActiveRecord::Base
include TokenVerification
PASSWORD_RESET_KEY = :password_reset
EMAIL_CONFIRMATION_KEY = :email_confirmation
has_secure_password
belongs_to :<%= domain_model %>, inverse_of: :<%= identity_model %>
validates_presence_of :email
validates_uniqueness_of :email
validates_format_of :email, with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/, allow_blank: true
validates_presence_of :password, if: :password_required?
validates_confirmation_of :password, if: :password_required?
validates_length_of :password, within: 8..128, allow_blank: true
before_save { |ident| ident.email.downcase! }
def update_email(new_email)
self.email = new_email
if email_changed?
self.confirmed_at = nil
save && send_confirmation_email
else
save
end
end
def confirm!
self.confirmed_at = Time.current
save(validate: false)
end
def confirmed?
confirmed_at.present?
end
def send_confirmation_email
<%= identity_mailer_class %>.confirm_email(self).deliver
end
def email_confirmation_token
expires_at = 7.days.from_now
expiration_token(expires_at, EMAIL_CONFIRMATION_KEY)
end
def password_reset_token
expires_at = 1.day.from_now
expiration_token(expires_at, PASSWORD_RESET_KEY)
end
private
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
end
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Livraria.GUI.ViewModel
{
public partial class ucUnidadeFederativa : ucUserControlBase
{
#region ucUnidadeFederativa: Construtores
public ucUnidadeFederativa()
{
InitializeComponent();
Atualizar();
}
#endregion
#region ucUnidadeFederativa: Overrides
public override Size DefinirTamanhoDoForm()
{
return new Size(420, 200);
}
public override Size DefinirTamanhoDoContainer()
{
return base.DefinirTamanhoDoContainer();
}
public override object ObterVariacao()
{
string nome = ttb_Nome.Text;
string sigla = ttb_Sigla.Text;
Modelo.UnidadeFederativa unidadeFederativa = new Modelo.UnidadeFederativa()
{
Nome = nome,
Sigla = sigla
};
return unidadeFederativa;
}
#endregion
}
}
|
require 'active_support/concern'
require 'meta_search/method'
require 'meta_search/builder'
module MetaSearch
module Searches
module ActiveRecord
def self.included(base)
base.extend ClassMethods
base.class_eval do
class_attribute :_metasearch_include_attributes, :_metasearch_exclude_attributes
class_attribute :_metasearch_include_associations, :_metasearch_exclude_associations
class_attribute :_metasearch_methods
self._metasearch_include_attributes =
self._metasearch_exclude_attributes =
self._metasearch_exclude_associations =
self._metasearch_include_associations = {}
self._metasearch_methods = {}
end
end
module ClassMethods
# Prepares the search to run against your model. Returns an instance of
# MetaSearch::Builder, which behaves pretty much like an ActiveRecord::Relation,
# in that it doesn't actually query the database until you do something that
# requires it to do so.
#
# Options:
#
# * +params+ - a hash of valid searches with keys that are valid according to
# the docs in MetaSearch::Where.
# * +opts+ - A hash of additional information that will be passed through to
# the search's Builder object. +search_key+, if present, will override the
# default param name, 'search', in any sort_links generated by this Builder.
# All other keys are passed untouched to the builder, and available from the
# Builder's +options+ reader for use in :if blocks supplied to attr_searchable
# and friends.
def metasearch(params = nil, opts = nil)
builder = Searches.for(self).new(self, opts || {})
builder.build(params || {})
end
alias_method :search, :metasearch unless respond_to?(:search)
def _metasearch_method_authorized?(name, metasearch_object)
name = name.to_s
meth = self._metasearch_methods[name]
meth && (meth[:if] ? meth[:if].call(metasearch_object) : true)
end
def _metasearch_attribute_authorized?(name, metasearch_object)
name = name.to_s
if self._metasearch_include_attributes.empty?
!_metasearch_excludes_attribute?(name, metasearch_object)
else
_metasearch_includes_attribute?(name, metasearch_object)
end
end
def _metasearch_association_authorized?(name, metasearch_object)
name = name.to_s
if self._metasearch_include_associations.empty?
!_metasearch_excludes_association?(name, metasearch_object)
else
_metasearch_includes_association?(name, metasearch_object)
end
end
private
# Excludes model attributes from searchability. This means that searches can't be created against
# these columns, whether the search is based on this model, or the model's attributes are being
# searched by association from another model. If a Comment <tt>belongs_to :article</tt> but declares
# <tt>attr_unsearchable :user_id</tt> then <tt>Comment.search</tt> won't accept parameters
# like <tt>:user_id_equals</tt>, nor will an Article.search accept the parameter
# <tt>:comments_user_id_equals</tt>.
def attr_unsearchable(*args)
if table_exists?
opts = args.extract_options!
args.flatten.each do |attr|
attr = attr.to_s
raise(ArgumentError, "No persisted attribute (column) named #{attr} in #{self}") unless self.columns_hash.has_key?(attr)
self._metasearch_exclude_attributes = self._metasearch_exclude_attributes.merge(
attr => {
:if => opts[:if]
}
)
end
end
end
# Like <tt>attr_unsearchable</tt>, but operates as a whitelist rather than blacklist. If both
# <tt>attr_searchable</tt> and <tt>attr_unsearchable</tt> are present, the latter
# is ignored.
def attr_searchable(*args)
if table_exists?
opts = args.extract_options!
args.flatten.each do |attr|
attr = attr.to_s
raise(ArgumentError, "No persisted attribute (column) named #{attr} in #{self}") unless self.columns_hash.has_key?(attr)
self._metasearch_include_attributes = self._metasearch_include_attributes.merge(
attr => {
:if => opts[:if]
}
)
end
end
end
# Excludes model associations from searchability. This mean that searches can't be created against
# these associations. An article that <tt>has_many :comments</tt> but excludes comments from
# searching by declaring <tt>assoc_unsearchable :comments</tt> won't make any of the
# <tt>comments_*</tt> methods available.
def assoc_unsearchable(*args)
opts = args.extract_options!
args.flatten.each do |assoc|
assoc = assoc.to_s
raise(ArgumentError, "No such association #{assoc} in #{self}") unless self.reflect_on_all_associations.map {|a| a.name.to_s}.include?(assoc)
self._metasearch_exclude_associations = self._metasearch_exclude_associations.merge(
assoc => {
:if => opts[:if]
}
)
end
end
# As with <tt>attr_searchable</tt> this is the whitelist version of
# <tt>assoc_unsearchable</tt>
def assoc_searchable(*args)
opts = args.extract_options!
args.flatten.each do |assoc|
assoc = assoc.to_s
raise(ArgumentError, "No such association #{assoc} in #{self}") unless self.reflect_on_all_associations.map {|a| a.name.to_s}.include?(assoc)
self._metasearch_include_associations = self._metasearch_include_associations.merge(
assoc => {
:if => opts[:if]
}
)
end
end
def search_methods(*args)
opts = args.extract_options!
authorizer = opts.delete(:if)
args.flatten.map(&:to_s).each do |arg|
self._metasearch_methods = self._metasearch_methods.merge(
arg => {
:method => MetaSearch::Method.new(arg, opts),
:if => authorizer
}
)
end
end
alias_method :search_method, :search_methods
def _metasearch_includes_attribute?(name, metasearch_object)
attr = self._metasearch_include_attributes[name]
attr && (attr[:if] ? attr[:if].call(metasearch_object) : true)
end
def _metasearch_excludes_attribute?(name, metasearch_object)
attr = self._metasearch_exclude_attributes[name]
attr && (attr[:if] ? attr[:if].call(metasearch_object) : true)
end
def _metasearch_includes_association?(name, metasearch_object)
assoc = self._metasearch_include_associations[name]
assoc && (assoc[:if] ? assoc[:if].call(metasearch_object) : true)
end
def _metasearch_excludes_association?(name, metasearch_object)
assoc = self._metasearch_exclude_associations[name]
assoc && (assoc[:if] ? assoc[:if].call(metasearch_object) : true)
end
end
end
def self.for(klass)
DISPATCH[klass.name]
end
private
DISPATCH = Hash.new do |hash, klass_name|
class_name = klass_name.gsub('::', '_')
hash[klass_name] = module_eval <<-RUBY_EVAL
class #{class_name} < MetaSearch::Builder
def self.klass
::#{klass_name}
end
end
#{class_name}
RUBY_EVAL
end
end
end
|
import data from "@site/policies.v2.json";
import CodeBlock from "@theme/CodeBlock";
import React from "react";
const PolicyConfig = ({ id }: { id: string }) => {
const policy = data.policies.find((p) => p.id === id);
if (!policy) {
throw new Error(`Could not find policy '${id}'`);
}
const code = {
name: "your-policy-name",
policyType: policy.id,
handler: policy.defaultHandler,
};
return <CodeBlock language="json">{JSON.stringify(code, null, 2)}</CodeBlock>;
};
export default PolicyConfig;
|
#!/bin/bash
DATE=`date +"%Y/%m/%d %T"`
PSSTATUS=`ps -ef | grep Make_ | grep -v grep | wc -l`
if [ $PSSTATUS -ge 1 ]; then
echo "$DATE run_make_image.sh is already running. Script is stopped."
else
echo "$DATE run_make_image.sh is started."
./Make_IC0_image.sh
./Make_SID_image.sh
./Make_PRMSL_image.sh
./Make_WIND_image.sh
./Make_HTSGW_image.sh
./Make_WAVE_image.sh
./Make_TRACK_image.sh
DATE=`date +"%Y/%m/%d %T"`
echo "$DATE run_make_image.sh is finished."
fi
|
AppModules.geo = function (root) {
var minMax = root.minMax = function (value, min, max) {
return value < min ? min : value > max ? max : value;
};
var self = {
a2ll: function (arr) {
return self.p2ll(arr);
},
ll2p: function (ll) {
return root.map.project(ll, root.tile.maxZoom());
},
p2ll: function (point) {
var result = root.map.unproject(point, root.tile.maxZoom());
if (result.lng > 180) result.lng -= 360;
if (result.lng < -180) result.lng += 360;
return result;
},
pos2ll: function (oXY, mapInd, isEvent) {
if (oXY[0]) oXY = {
x: oXY[0],
y: oXY[1]
};
var map = mapInd || root.maps.getIndex();
var inch = !isEvent ? 39.3700787 : 1;
map = map ? root.maps.load(map) : false;
var result = {};
if (map) {
result.x = (oXY.x * inch - map.mRect[0]) / map.mRect[2];
result.y = (oXY.y * inch - map.mRect[1]) / map.mRect[3];
result.y = 1 - result.y;
result.x = map.cRect[0] + map.cRect[2] * result.x;
result.y = map.cRect[1] + map.cRect[3] * result.y;
result = L.point(result.x,result.y);
return self.p2ll(result);
}
return false;
}
};
return self;
};
|
export class TokenLocal {
createdAt: number;
name: string;
ownerStrategyName: string;
value: string;
}
|
<?php
require_once(APPPATH."qiniu/utils.php");
require_once(APPPATH."qiniu/conf.php");
// ----------------------------------------------------------
class Qiniu_Mac {
public $AccessKey;
public $SecretKey;
public function __construct($accessKey, $secretKey)
{
$this->AccessKey = $accessKey;
$this->SecretKey = $secretKey;
}
public function Sign($data) // => $token
{
$sign = hash_hmac('sha1', $data, $this->SecretKey, true);
return $this->AccessKey . ':' . Qiniu_Encode($sign);
}
public function SignWithData($data) // => $token
{
$data = Qiniu_Encode($data);
return $this->Sign($data) . ':' . $data;
}
public function SignRequest($req, $incbody) // => ($token, $error)
{
$url = $req->URL;
$url = parse_url($url['path']);
$data = '';
if (isset($url['path'])) {
$data = $url['path'];
}
if (isset($url['query'])) {
$data .= '?' . $url['query'];
}
$data .= "\n";
if ($incbody) {
$data .= $req->Body;
}
return $this->Sign($data);
}
public function VerifyCallback($auth, $url, $body) // ==> bool
{
$url = parse_url($url);
$data = '';
if (isset($url['path'])) {
$data = $url['path'];
}
if (isset($url['query'])) {
$data .= '?' . $url['query'];
}
$data .= "\n";
$data .= $body;
$token = 'QBox ' . $this->Sign($data);
return $auth === $token;
}
}
function Qiniu_SetKeys($accessKey, $secretKey)
{
global $QINIU_ACCESS_KEY;
global $QINIU_SECRET_KEY;
$QINIU_ACCESS_KEY = $accessKey;
$QINIU_SECRET_KEY = $secretKey;
}
function Qiniu_RequireMac($mac) // => $mac
{
if (isset($mac)) {
return $mac;
}
global $QINIU_ACCESS_KEY;
global $QINIU_SECRET_KEY;
return new Qiniu_Mac($QINIU_ACCESS_KEY, $QINIU_SECRET_KEY);
}
function Qiniu_Sign($mac, $data) // => $token
{
return Qiniu_RequireMac($mac)->Sign($data);
}
function Qiniu_SignWithData($mac, $data) // => $token
{
return Qiniu_RequireMac($mac)->SignWithData($data);
}
// ----------------------------------------------------------
|
---
title: "AWS CloudWatch"
linkTitle: "AWS CloudWatch"
date: 2022-05-25
description: >
AWS SRE - CloudWatch使用经验.
---
# AWS SRE - CloudWatch使用经验
日志、指标、告警等功能
## 一、日志查询
### A、全局日志搜索:Logs Insights
使用 CloudWatch 查询语法进行 日志组 维度的全局日志搜索。
#### 常用查询语法
```
fields @timestamp, @message
| sort @timestamp desc
| limit 20
```
#### "或"语法:|
使用 '|' 来作为 "或" 语义的分隔符,使用多个查询条件
#### "注释"
使用 '#' 在开头,作为该行查询语句的注释,可使用快捷键 "ctrl + /"
### B、日志组
#### AWS原生日志组
|
#include "builtin.hh"
#include <cassert>
#include <cstdio>
#include <unordered_map>
#include <boost/optional.hpp>
#include "echo.hh"
#include "exit.hh"
namespace exec
{
namespace builtins
{
namespace
{
enum class builtins : uint8_t
{
BUILTIN = 0,
ECHO = 1,
EXIT = 2,
};
boost::optional<builtins> builtin_from_name(const std::string& name)
{
static std::unordered_map<std::string, builtins> builtins_name{
{ "builtin", builtins::BUILTIN },
{ "echo", builtins::ECHO },
{ "exit", builtins::EXIT },
};
const auto iterator = builtins_name.find(name);
if (iterator == builtins_name.end())
return boost::optional<builtins>{};
return iterator->second;
}
} // anonymous
boost::optional<int> builtin(const std::string& name,
const std::vector<std::string>& args,
bool user_call)
{
const auto builtin_opt = builtin_from_name(name);
if (not builtin_opt)
{
if (user_call)
{
std::printf("builtin: %s is not a builtin\n", name.c_str());
return 1;
}
return {};
}
switch (*builtin_opt)
{
case builtins::BUILTIN:
return args.empty()
? 0
: builtin(args[0], { std::next(args.begin()), args.end() }, true);
case builtins::ECHO:
return echo(args);
case builtins::EXIT:
exit();
};
assert(false && "unreachable code reached");
return -1;
}
} // builtins
} // exec
|
package com.kylecorry.trail_sense.shared.grouping.filter
import com.kylecorry.trail_sense.shared.grouping.Groupable
interface IGroupFilter<T : Groupable> {
suspend fun filter(
groupId: Long? = null,
includeGroups: Boolean = false,
maxDepth: Int? = null,
predicate: (T) -> Boolean
): List<T>
}
|
#!/bin/sh
####################################################################################
# If not stated otherwise in this file or this component's Licenses.txt file the
# following copyright and licenses apply:
# Copyright 2018 RDK Management
# 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.
#######################################################################################
##To Start Openvswitch
/etc/init.d/openvswitch-switch start
## Creating Interface and Waiting for interface to be up
ifconfig brlan0 down
brctl delbr brlan0
sleep 5
##Delete existing ovs bridge
ovs-vsctl del-br brlan0
sleep 5
##Create ovs bridge
ovs-vsctl add-br brlan0
##Bridge Interface Finding
count=`ifconfig | grep brlan0 | wc -l`
echo "brlan-count=$count"
sleep 5
count=`ifconfig | grep brlan0 | wc -l`
echo "brlan-count=$count"
if [ $count != 0 ];then
echo "brlan0 interface exists"
fi
##eth3 Interface Finding
count=`ifconfig | grep eth3 | wc -l`
echo "eth3-count=$count"
sleep 5
count=`ifconfig | grep eth3 | wc -l`
if [ $count != 0 ];then
echo "eth3 interface exists"
ifconfig eth3 0 up
fi
##eth2 Interface Finding
count=`ifconfig | grep eth2 | wc -l`
echo "eth2-count=$count"
sleep 5
count=`ifconfig | grep eth2 | wc -l`
if [ $count != 0 ];then
echo "eth2 interface exists"
ifconfig eth2 0 up
fi
##eth1 Interface Finding
count=`ifconfig | grep eth1 | wc -l`
echo "eth1count=$count"
sleep 5
count=`ifconfig | grep eth1 | wc -l`
if [ $count != 0 ];then
echo "eth1 interface exists"
ifconfig eth1 0 up
fi
##wlan0 Interface Finding
wifi=`ifconfig | grep wlan0 | wc -l`
echo "wlan0count=$wifi"
sleep 5
wifi=`ifconfig | grep wlan0 | wc -l`
if [ $wifi != 0 ];then
echo "wlan0 interface exists"
ifconfig wlan0 0 up
fi
## Set ip Address for Bridge interface for dnsmasq server
if [ $count ] || [ $wifi ];then
INTERFACE=brlan0
DEFAULT_IP_ADDRESS=10.0.0.1
dnsmasq_conf_file=/etc/dnsmasq.conf
KEYWORD=dhcp-range
#############################################################
#Set ipaddress for brlan0 interface
#############################################################
if [ -f $dnsmasq_conf_file ];then
echo "getting router ip address from $dnsmasq_conf_file"
router_ip_address=`cat $dnsmasq_conf_file | grep -w $KEYWORD | cut -d ',' -f2 | cut -d '.' -f1-3`
echo "set ip address as $router_ip_address.1 for $INTERFACE"
ifconfig $INTERFACE $router_ip_address.1 netmask 255.255.255.0
else
echo "set ip address as default $DEFAULT_IP_ADDRESS for $INTERFACE"
ifconfig $INTERFACE $DEFAULT_IP_ADDRESS netmask 255.255.255.0
fi
rm -f wifi_clients.txt
##############################
#Restart dnsmasq service
##############################
killall dnsmasq
/usr/bin/dnsmasq &
################################
#Restart Hostapd
################################
systemctl restart hostapd
sleep 5
systemctl restart hostapd
fi
|
<?php
namespace Wearejust\SonataThemeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class TemplateController extends Controller
{
/**
* @return \Symfony\Component\HttpFoundation\Response
*/
public function deleteDialogAction()
{
return $this->render('@WearejustSonataTheme/Wearejust/AJAX/delete-dialog.html.twig');
}
}
|
const Disassembler = require('./lib/disassembler');
const winston = require('winston');
const http = require('http');
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'dev';
const express = require('express');
const bodyParser = require('body-parser');
// configure express
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const logger = winston.createLogger({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: `./logs/${env}.log` })
]
});
const handlePost = (req, res) => {
const disassembler = new Disassembler(logger);
const code = req.body.code;
const version = req.body.version;
const done = function(returnObj) {
res.send(returnObj);
};
disassembler.run({code, version, done});
};
app.use(express.static('public'))
app.post('/', handlePost);
app.listen(port, function () {
console.log(`Server running at http://0.0.0.0:${port}/`);
});
|
// use std::iter::Iterator;
// Symbol Tables
pub trait ST<K, V> {
/// create a symbol table
fn new() -> Self;
/// put key-value pair into the table
/// (remove key from table if value is null)
/// a[key] = val;
fn put(&mut self, key: K, val: V);
/// value paired with key
/// (null if key is absent)
/// a[key]
fn get(&self, key: &K) -> Option<&V>;
// FIXME: helper for a[key] = val
// fn get_mut(&mut self, key: &K) -> Option<&mut V>;
/// remove key (and its value) from table
fn delete(&mut self, key: &K);
/// is there a value paired with key?
fn contains(&self, key: &K) -> bool {
self.get(key).is_some()
}
/// is the table empty?
fn is_empty(&self) -> bool;
/// number of key-value pairs in the table
fn size(&self) -> usize;
// all the keys in the table
// fn keys() -> Iterator<Item=K>;
}
pub trait OrderedST<K, V>: ST<K, V> {
/// smallest key
fn min(&self) -> Option<&K>;
/// largest key
fn max(&self) -> Option<&K>;
/// largest key less than or equal to key
fn floor(&self, key: &K) -> Option<&K>;
/// smallest key greater than or equal to key
fn ceiling(&self, key: &K) -> Option<&K>;
/// number of keys less than key
fn rank(&self, key: &K) -> usize;
/// key of rank k
fn select(&self, k: usize) -> Option<&K>;
/// delete smallest key
fn delete_min(&mut self);
/// delete largest key
fn delete_max(&mut self);
/// number of keys in [lo..hi]
fn size_of_key_range(&self, lo: &K, hi: &K) -> usize {
self.rank(hi) - self.rank(lo) + 1
}
}
pub mod linked_st;
pub mod ordered_array_st;
pub mod binary_search_tree;
pub mod red_black_tree;
pub mod hash_tables;
|
package com.moon.beautygirlkotlin.common.data.entity
import android.os.Parcelable
import com.moon.beautygirlkotlin.R
import kotlinx.android.parcel.Parcelize
/**
* Created by Arthur on 2019-12-29.
*/
@Parcelize
data class Source(
val id: Int,
val title: Int,
val types: List<SourceType>?
) : Parcelable{
fun isGank() : Boolean = id == 0
fun isDouban() : Boolean = id == 1
fun isWeiyi() : Boolean = id == 2
fun isTao() : Boolean = id == 3
}
/*
*
* */
@Parcelize
data class SourceType(
val id: String,
val title: String
): Parcelable
val doubanSource = Source(1,R.string.douban_meizi, listOf(
SourceType("2", "大胸妹"),
SourceType("6", "小翘臀"),
SourceType("7", "黑丝袜"),
SourceType("3", "美图控"),
SourceType("4", "高颜值"),
SourceType("5", "大杂烩")
))
val weiyiSource = Source(2,R.string.weiyi_pic,
listOf(
SourceType("list_18_", "明星相关专辑")
)
)
val sourceList = listOf<Source>(
Source(0,R.string.gank_meizi, null),
doubanSource,
weiyiSource,
Source(3,R.string.tao_female, null)
)
|
import pytorch_lightning as pl
import numpy as np
import torch
# noinspection PyProtectedMember
from torch.utils.data import DataLoader
from spanet.options import Options
from spanet.dataset.jet_reconstruction_dataset import JetReconstructionDataset
from spanet.network.learning_rate_schedules import get_linear_schedule_with_warmup
from spanet.network.learning_rate_schedules import get_cosine_with_hard_restarts_schedule_with_warmup
class JetReconstructionBase(pl.LightningModule):
def __init__(self, options: Options):
super(JetReconstructionBase, self).__init__()
self.save_hyperparameters(options)
self.options = options
self.training_dataset, self.validation_dataset, self.testing_dataset = self.create_datasets()
self.mean = 0
self.std = 1
# Normalize datasets using training dataset statistics
if self.options.normalize_features:
self.mean, self.std = self.training_dataset.compute_statistics()
self.mean = torch.nn.Parameter(self.mean, requires_grad=False)
self.std = torch.nn.Parameter(self.std, requires_grad=False)
# Compute class weights for particles from the training dataset target distribution
self.balance_particles = False
if options.balance_particles and options.partial_events:
index_tensor, weights_tensor = self.training_dataset.compute_particle_balance()
self.particle_index_tensor = torch.nn.Parameter(index_tensor, requires_grad=False)
self.particle_weights_tensor = torch.nn.Parameter(weights_tensor, requires_grad=False)
self.balance_particles = True
# Compute class weights for jets from the training dataset target distribution
self.balance_jets = False
if options.balance_jets:
jet_weights_tensor = self.training_dataset.compute_jet_balance()
self.jet_weights_tensor = torch.nn.Parameter(jet_weights_tensor, requires_grad=False)
self.balance_jets = True
# Helper arrays for permutation groups. Used for the partial-event loss functions.
event_permutation_group = np.array(self.training_dataset.event_permutation_group)
self.event_permutation_tensor = torch.nn.Parameter(torch.from_numpy(event_permutation_group), False)
# Helper variables for keeping track of the number of batches in each epoch.
# Used for learning rate scheduling and other things.
# self.steps_per_epoch = len(self.training_dataset) // (self.options.batch_size * max(1, self.options.num_gpu))
self.steps_per_epoch = len(self.training_dataset) // self.options.batch_size
self.total_steps = self.steps_per_epoch * self.options.epochs
self.warmup_steps = int(round(self.steps_per_epoch * self.options.learning_rate_warmup_epochs))
@property
def dataset(self):
return JetReconstructionDataset
@property
def dataloader(self):
return DataLoader
@property
def dataloader_options(self):
return {
"batch_size": self.options.batch_size,
"pin_memory": self.options.num_gpu > 0,
"num_workers": self.options.num_dataloader_workers,
"prefetch_factor": 2
}
def create_datasets(self):
event_info_file = self.options.event_info_file
training_file = self.options.training_file
validation_file = self.options.validation_file
training_range = 1.0
validation_range = 1.0
# If we dont have a validation file provided, create one from the training file.
if len(validation_file) == 0:
validation_file = training_file
# Compute the training / validation ranges based on the data-split and the limiting percentage.
train_validation_split = self.options.dataset_limit * self.options.train_validation_split
training_range = (0.0, train_validation_split)
validation_range = (train_validation_split, self.options.dataset_limit)
# Construct primary training datasets
# Note that only the training dataset might be limited to full events or partial events.
training_dataset = self.dataset(data_file=training_file,
event_info=event_info_file,
limit_index=training_range,
jet_limit=self.options.limit_to_num_jets,
partial_events=self.options.partial_events,
randomization_seed=self.options.dataset_randomization,)
validation_dataset = self.dataset(data_file=validation_file,
event_info=event_info_file,
limit_index=validation_range,
jet_limit=self.options.limit_to_num_jets,
randomization_seed=self.options.dataset_randomization)
# Optionally construct the testing dataset.
# This is not used in the main training script but is still useful for testing later.
testing_dataset = None
if len(self.options.testing_file) > 0:
testing_dataset = self.dataset(data_file=self.options.testing_file,
event_info=self.options.event_info_file,
limit_index=1.0,
jet_limit=self.options.limit_to_num_jets)
return training_dataset, validation_dataset, testing_dataset
def configure_optimizers(self):
optimizer = None
if 'apex' in self.options.optimizer:
try:
# noinspection PyUnresolvedReferences
import apex.optimizers
if self.options.optimizer == 'apex_adam':
optimizer = apex.optimizers.FusedAdam
elif self.options.optimizer == 'apex_lamb':
optimizer = apex.optimizers.FusedLAMB
else:
optimizer = apex.optimizers.FusedSGD
except ImportError:
pass
else:
optimizer = getattr(torch.optim, self.options.optimizer)
if optimizer is None:
print(f"Unable to load desired optimizer: {self.options.optimizer}.")
print(f"Using pytorch AdamW as a default.")
optimizer = torch.optim.AdamW
decay_mask = ["bias", "LayerNorm.weight"]
optimizer_grouped_parameters = [
{
"params": [param for name, param in self.named_parameters()
if not any(no_decay in name for no_decay in decay_mask)],
"weight_decay": self.options.l2_penalty,
},
{
"params": [param for name, param in self.named_parameters()
if any(no_decay in name for no_decay in decay_mask)],
"weight_decay": 0.0,
},
]
optimizer = optimizer(optimizer_grouped_parameters, lr=self.options.learning_rate)
if self.options.learning_rate_cycles < 1:
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=self.warmup_steps,
num_training_steps=self.total_steps
)
else:
scheduler = get_cosine_with_hard_restarts_schedule_with_warmup(
optimizer,
num_warmup_steps=self.warmup_steps,
num_training_steps=self.total_steps,
num_cycles=self.options.learning_rate_cycles
)
scheduler = {
'scheduler': scheduler,
'interval': 'step',
'frequency': 1
}
return [optimizer], [scheduler]
def train_dataloader(self) -> DataLoader:
return self.dataloader(self.training_dataset, shuffle=True, drop_last=True, **self.dataloader_options)
def val_dataloader(self) -> DataLoader:
return self.dataloader(self.validation_dataset, drop_last=True, **self.dataloader_options)
def test_dataloader(self) -> DataLoader:
if self.testing_dataset is None:
raise ValueError("Testing dataset not provided.")
return self.dataloader(self.testing_dataset, **self.dataloader_options)
|
// Copyright (c) 2021 Mantano. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:mno_lcp/lcp.dart';
abstract class LcpClient {
bool get isAvailable;
String findOneValidPassphrase(
String jsonLicense, List<String> hashedPassphrases);
DrmContext createContext(
String jsonLicense, String hashedPassphrases, String pemCrl);
ByteData decrypt(DrmContext drmContext, ByteData encryptedData);
}
|
# pwgen
英数字からランダムな文字列を作ります。
|
/*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package attestlib
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/asn1"
"encoding/pem"
"github.com/pkg/errors"
"math/big"
)
// hashPayload returns the hash function, the hashed payload and an error.
func hashPayload(payload []byte, signingAlg SignatureAlgorithm) (crypto.Hash, []byte, error) {
switch signingAlg {
case RsaSignPkcs12048Sha256, RsaSignPkcs13072Sha256, RsaSignPkcs14096Sha256, RsaPss2048Sha256, RsaPss3072Sha256, RsaPss4096Sha256, EcdsaP256Sha256:
hashedPayload := sha256.Sum256(payload)
return crypto.SHA256, hashedPayload[:], nil
case EcdsaP384Sha384:
hashedPayload := sha512.Sum384(payload)
return crypto.SHA384, hashedPayload[:], nil
case RsaSignPkcs14096Sha512, RsaPss4096Sha512, EcdsaP521Sha512:
hashedPayload := sha512.Sum512(payload)
return crypto.SHA512, hashedPayload[:], nil
default:
return 0, nil, errors.New("invalid signature algorithm")
}
}
// This function will be used to verify PKIX and JWT signatures. PGP detached signatures are not supported by this function.
// Signature is the raw byte signature.
// PublicKey is the PEM encoded public key that will be used to verify the signature.
// Payload is the plaintext that was hashed and then signed.
func verifyDetached(signature []byte, publicKey []byte, signingAlg SignatureAlgorithm, payload []byte) error {
// Decode public key to der and parse for key type.
// This is needed to create PublicKey type needed for the verify functions.
der, rest := pem.Decode(publicKey)
if der == nil {
return errors.New("failed to decode PEM")
}
if len(rest) != 0 {
return errors.New("more than one public key given")
}
pub, err := x509.ParsePKIXPublicKey(der.Bytes)
if err != nil {
return err
}
switch signingAlg {
case RsaSignPkcs12048Sha256, RsaSignPkcs13072Sha256, RsaSignPkcs14096Sha256, RsaSignPkcs14096Sha512:
rsaKey, ok := pub.(*rsa.PublicKey)
if !ok {
return errors.New("expected rsa key")
}
hash, hashedPayload, err := hashPayload(payload, signingAlg)
if err != nil {
return err
}
err = rsa.VerifyPKCS1v15(rsaKey, hash, hashedPayload, signature)
if err != nil {
return err
}
return nil
case RsaPss2048Sha256, RsaPss3072Sha256, RsaPss4096Sha256, RsaPss4096Sha512:
rsaKey, ok := pub.(*rsa.PublicKey)
if !ok {
return errors.New("expected ecdsa key")
}
hash, hashedPayload, err := hashPayload(payload, signingAlg)
if err != nil {
return err
}
err = rsa.VerifyPSS(rsaKey, hash, hashedPayload, signature, nil)
if err != nil {
return err
}
return nil
case EcdsaP256Sha256, EcdsaP384Sha384, EcdsaP521Sha512:
ecKey, ok := pub.(*ecdsa.PublicKey)
if !ok {
return errors.New("expected ecdsa key")
}
var sigStruct struct {
R, S *big.Int
}
if _, err := asn1.Unmarshal(signature, &sigStruct); err != nil {
return err
}
// The hash function is not needed for ecdsa.Verify.
_, hashedPayload, err := hashPayload(payload, signingAlg)
if err != nil {
return err
}
if !ecdsa.Verify(ecKey, hashedPayload, sigStruct.R, sigStruct.S) {
return errors.New("failed to verify ecdsa signature")
}
return nil
default:
return errors.New("signature algorithm not supported")
}
}
|
import './posts';
import '../collections/posts/methods';
import { Meteor } from 'meteor/meteor';
import { Posts } from '../collections/posts/posts';
import { TimeLines } from '../collections/timelines/timelines';
Meteor.startup(() => {
Posts.remove({});
TimeLines.remove({});
Meteor.users.remove({});
});
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Page;
class PageController extends Controller
{
public function renderPage(Page $page)
{
$contents = collect([]);
$ordered_sections = $page->sections->sortBy('order');
foreach($ordered_sections as $section)
{
$contents[$section->name] = [
'section' => $section,
'contents' => collect([])
];
$ordered_contents = $section->contents->sortBy('order');
foreach($ordered_contents as $content)
{
$contents[$section->name]['contents']->push($content);
}
}
// dd($contents);
return view($page->template)->with([
'contents' => $contents
]);
}
}
|
{-@ LIQUID "--short-names" @-}
{-@ LIQUID "--no-termination" @-}
{-@ LIQUID "--scrape-used-imports" @-}
module DataTypes where
{-@ die :: {v:String | false} -> a @-}
die = error
{-@ data IncList a =
Emp
| (:<) { hd :: a, tl :: IncList {v:a | hd <= v}} @-}
data IncList a
= Emp
| (:<) { hd :: a
, tl :: IncList a}
infixr 9 :<
{-@ type IncListBig a x = IncList {v:a | x <= v} @-}
{-@ type IncListSmall a x = IncList {v:a | v <= x} @-}
okList = 1 :< 2 :< 3 :< Emp -- accepted by LH
insert
:: (Ord a)
=> a -> IncList a -> IncList a
insert y Emp = y :< Emp
insert y (x :< xs)
| y <= x = y :< x :< xs
| otherwise = x :< insert y xs
insertSort'
:: (Ord a)
=> [a] -> IncList a
insertSort' xs = foldr insert Emp xs
split :: [a] -> ([a], [a])
split (x:y:zs) = (x : xs, y : ys)
where
(xs, ys) = split zs
split xs = (xs, [])
quickSort
:: (Ord a)
=> [a] -> IncList a
quickSort [] = Emp
quickSort (x:xs) = append x lessers greaters
where
lessers = quickSort [y | y <- xs, y < x]
greaters = quickSort [z | z <- xs, z >= x]
{-@ append :: x:a -> IncListSmall a x
-> IncListBig a x
-> IncList a
@-}
append :: a -> IncList a -> IncList a -> IncList a
append z Emp ys = z :< ys
append z (x :< xs) ys = x :< append z xs ys
------------------
data BST a
= Leaf
| Node { root :: a
, left :: BST a
, right :: BST a}
{-@
data BST a = Leaf
| Node { root :: a
, left :: BSTL a root
, right :: BSTR a root }
@-}
{-@ type BSTL a X = BST {v:a | v < X} @-}
{-@ type BSTR a X = BST {v:a | v > X} @-}
okBST :: BST Int
okBST =
Node
6
(Node 2 (Node 1 Leaf Leaf) (Node 4 Leaf Leaf))
(Node 9 (Node 7 Leaf Leaf) Leaf)
mem
:: (Ord a)
=> a -> BST a -> Bool
mem _ Leaf = False
mem x (Node v l r)
| x == v = True
| x < v = mem x l
| otherwise = mem x r
one :: a -> BST a
one x = Node x Leaf Leaf
add :: (Ord a) => a -> BST a -> BST a
add k Leaf = one k
add k t@(Node x l r)
| k < x = Node x (add k l) r
| k < x = Node x l (add k r)
| otherwise = t
{-@ type NotLeaf a = {v:BST a | notLeaf v} @-}
{-@ measure notLeaf @-}
notLeaf :: BST a -> Bool
notLeaf Leaf = False
notLeaf (Node _ _ _) = True
-- this value is lower than the rest of the tree
data MinPair a = MP { mElt :: a, rest :: BST a }
{-@ data MinPair a = MP { mElt :: a, rest :: BSTR a mElt} @-}
{-@ delMin :: NotLeaf a -> MinPair a @-}
delMin :: (Ord a) => BST a -> MinPair a
delMin (Node k Leaf r) = MP k r
delMin (Node k l r) = MP k' (Node k l' r)
where
MP k' l' = delMin l
delMin Leaf = die "Don't say I didn't warn ya!"
del :: (Ord a) => a -> BST a -> BST a
del k' t@(Node k l r)
| k < x = Node x (del k l) r
| k < x = Node x l (del k r)
| otherwise = Leaf
del _ Leaf = Leaf
|
class Workflow
module Cwl
class StepParser
include ActiveModel::Validations
attr_reader :step_json, :title, :parser, :step_number
delegate :context, to: :parser
validates :id, :inputs, :outputs, :run, presence: true
validates :run, 'cwl/step_run': true
validates :app, 'workflow/slot/app_presence': true
validates :name, 'cwl/step_name': true
validates :outputs, 'cwl/outs': true
validate :inputs_valid?
validate :outputs_valid?
validate :docker_image_valid?, if: :requirements
def initialize(title, step_json, step_number, parser)
@title = title
@step_json = step_json
@step_number = step_number
@parser = parser
end
def name
title
end
def id
step_json["id"]
end
def app
@app ||= App.accessible_by(context).find_by_uid(id)
end
def run
step_json["run"]
end
def inputs
step_json["in"]
end
def outputs
step_json["out"]
end
def requirements
step_json["requirements"]
end
def docker_image
return unless requirements
@docker_image ||= DockerImage.new(requirements["DockerRequirement"]["dockerPull"])
end
def input_objects
@input_objects ||= inputs.map { |input, link| InputParser.new(input, link, self) }
end
def output_objects
@output_objects ||= outputs.map { |input| OutputParser.new(input, self) }
end
def prev_step
parser.find_step(step_number - 1)
end
def allowable_link_outputs
prev_step.outputs.map do |output|
[prev_step.name, output].join('/')
end
end
def docker_image_valid?
return if errors.any? || docker_image.valid?
docker_image.errors.full_messages.each do |value|
errors.add(:base, value)
end
end
def inputs_valid?
return if errors.any? || input_objects.all? { |input| input.valid? }
input_objects.each do |input|
input.errors.messages.values.flatten.each do |value|
errors.add(:base, value)
end
end
end
def outputs_valid?
return if errors.any? || output_objects.all? { |output| output.valid? }
output_objects.each do |output|
output.errors.messages.values.flatten.each do |value|
errors.add(:base, value)
end
end
end
end
end
end
|
import React from "react";
import graphql from "babel-plugin-relay/macro";
import { createFragmentContainer } from "react-relay";
class Task extends React.Component {
render() {
const {
task: { content }
} = this.props;
return <li>{content}</li>;
}
}
export default createFragmentContainer(Task, {
task: graphql`
fragment Task_task on Task {
id
content
completed
}
`
});
|
package com.github.provider.providers
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.text.TextUtils
import com.github.provider.db.DBOpenHelper
/**
* Created by swayangjit on 29/1/21.
*/
class TelemetryProvider : ContentProvider() {
private var mContext: Context? = null
private var mSqliteDatabase: SQLiteDatabase? = null
companion object {
const val AUTHORITY = "com.github.provider"
const val TELEMETRY_URI_CODE = 0
private val sUriMatcher = UriMatcher(UriMatcher.NO_MATCH)
init {
sUriMatcher.addURI(AUTHORITY, "telemetry", TELEMETRY_URI_CODE)
}
}
override fun onCreate(): Boolean {
mContext = context
mSqliteDatabase = DBOpenHelper(mContext).getWritableDatabase()
mSqliteDatabase!!.execSQL("delete from " + DBOpenHelper.TABLE_TELEMETRY)
mSqliteDatabase!!.execSQL("insert into telemetry values(3,'INTERACT', 'SAMPLE_EVENT',1,1);")
mSqliteDatabase!!.execSQL("insert into telemetry values(4,'IMPRESSION', 'SAMPLE_EVENT_1',1,2);")
return false
}
override fun query(
uri: Uri,
projection: Array<String?>?,
selection: String?,
selectionArgs: Array<String?>?,
sortOrder: String?
): Cursor? {
val table = getTableName(uri)
require(!TextUtils.isEmpty(table)) { "Unsupported URI: $uri" }
return mSqliteDatabase!!.query(
table,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
)
}
override fun getType(uri: Uri): String? {
return null
}
override fun insert(uri: Uri, contentValues: ContentValues?): Uri? {
val table = getTableName(uri)
require(!TextUtils.isEmpty(table)) { "Unsupported URI: $uri" }
mSqliteDatabase!!.insert(table, null, contentValues)
mContext!!.contentResolver.notifyChange(uri, null)
return null
}
override fun delete(uri: Uri, s: String?, strings: Array<String?>?): Int {
return 0
}
override fun update(
uri: Uri,
contentValues: ContentValues?,
s: String?,
strings: Array<String?>?
): Int {
return 0
}
private fun getTableName(uri: Uri): String? {
var tableName: String? = null
when (sUriMatcher.match(uri)) {
TELEMETRY_URI_CODE -> tableName = DBOpenHelper.TABLE_TELEMETRY
else -> {
}
}
return tableName
}
}
|
namespace Hexadecimal
{
internal class Lookup
{
/// <summary>
/// Creates a lookup array which can be used to convert
/// a byte array to a hexadecimal string.
/// </summary>
/// <param name="uppercase">
/// Whether the resulting hex should be uppercase.
/// </param>
/// <returns>The lookup array.</returns>
//private static uint[] Create(bool uppercase)
//{
// var result = new uint[256];
// for (int i = 0; i < 256; ++i)
// {
// string format = uppercase ? "X2" : "x2";
// string h = i.ToString(format);
// result[i] = (h[0]) + ((uint)h[1] << 16);
// }
// return result;
//}
public static readonly uint[] Lowercase =
{
3145776, 3211312, 3276848, 3342384, 3407920, 3473456, 3538992, 3604528,
3670064, 3735600, 6357040, 6422576, 6488112, 6553648, 6619184, 6684720,
3145777, 3211313, 3276849, 3342385, 3407921, 3473457, 3538993, 3604529,
3670065, 3735601, 6357041, 6422577, 6488113, 6553649, 6619185, 6684721,
3145778, 3211314, 3276850, 3342386, 3407922, 3473458, 3538994, 3604530,
3670066, 3735602, 6357042, 6422578, 6488114, 6553650, 6619186, 6684722,
3145779, 3211315, 3276851, 3342387, 3407923, 3473459, 3538995, 3604531,
3670067, 3735603, 6357043, 6422579, 6488115, 6553651, 6619187, 6684723,
3145780, 3211316, 3276852, 3342388, 3407924, 3473460, 3538996, 3604532,
3670068, 3735604, 6357044, 6422580, 6488116, 6553652, 6619188, 6684724,
3145781, 3211317, 3276853, 3342389, 3407925, 3473461, 3538997, 3604533,
3670069, 3735605, 6357045, 6422581, 6488117, 6553653, 6619189, 6684725,
3145782, 3211318, 3276854, 3342390, 3407926, 3473462, 3538998, 3604534,
3670070, 3735606, 6357046, 6422582, 6488118, 6553654, 6619190, 6684726,
3145783, 3211319, 3276855, 3342391, 3407927, 3473463, 3538999, 3604535,
3670071, 3735607, 6357047, 6422583, 6488119, 6553655, 6619191, 6684727,
3145784, 3211320, 3276856, 3342392, 3407928, 3473464, 3539000, 3604536,
3670072, 3735608, 6357048, 6422584, 6488120, 6553656, 6619192, 6684728,
3145785, 3211321, 3276857, 3342393, 3407929, 3473465, 3539001, 3604537,
3670073, 3735609, 6357049, 6422585, 6488121, 6553657, 6619193, 6684729,
3145825, 3211361, 3276897, 3342433, 3407969, 3473505, 3539041, 3604577,
3670113, 3735649, 6357089, 6422625, 6488161, 6553697, 6619233, 6684769,
3145826, 3211362, 3276898, 3342434, 3407970, 3473506, 3539042, 3604578,
3670114, 3735650, 6357090, 6422626, 6488162, 6553698, 6619234, 6684770,
3145827, 3211363, 3276899, 3342435, 3407971, 3473507, 3539043, 3604579,
3670115, 3735651, 6357091, 6422627, 6488163, 6553699, 6619235, 6684771,
3145828, 3211364, 3276900, 3342436, 3407972, 3473508, 3539044, 3604580,
3670116, 3735652, 6357092, 6422628, 6488164, 6553700, 6619236, 6684772,
3145829, 3211365, 3276901, 3342437, 3407973, 3473509, 3539045, 3604581,
3670117, 3735653, 6357093, 6422629, 6488165, 6553701, 6619237, 6684773,
3145830, 3211366, 3276902, 3342438, 3407974, 3473510, 3539046, 3604582,
3670118, 3735654, 6357094, 6422630, 6488166, 6553702, 6619238, 6684774
};
public static readonly uint[] Uppercase =
{
3145776, 3211312, 3276848, 3342384, 3407920, 3473456, 3538992, 3604528,
3670064, 3735600, 4259888, 4325424, 4390960, 4456496, 4522032, 4587568,
3145777, 3211313, 3276849, 3342385, 3407921, 3473457, 3538993, 3604529,
3670065, 3735601, 4259889, 4325425, 4390961, 4456497, 4522033, 4587569,
3145778, 3211314, 3276850, 3342386, 3407922, 3473458, 3538994, 3604530,
3670066, 3735602, 4259890, 4325426, 4390962, 4456498, 4522034, 4587570,
3145779, 3211315, 3276851, 3342387, 3407923, 3473459, 3538995, 3604531,
3670067, 3735603, 4259891, 4325427, 4390963, 4456499, 4522035, 4587571,
3145780, 3211316, 3276852, 3342388, 3407924, 3473460, 3538996, 3604532,
3670068, 3735604, 4259892, 4325428, 4390964, 4456500, 4522036, 4587572,
3145781, 3211317, 3276853, 3342389, 3407925, 3473461, 3538997, 3604533,
3670069, 3735605, 4259893, 4325429, 4390965, 4456501, 4522037, 4587573,
3145782, 3211318, 3276854, 3342390, 3407926, 3473462, 3538998, 3604534,
3670070, 3735606, 4259894, 4325430, 4390966, 4456502, 4522038, 4587574,
3145783, 3211319, 3276855, 3342391, 3407927, 3473463, 3538999, 3604535,
3670071, 3735607, 4259895, 4325431, 4390967, 4456503, 4522039, 4587575,
3145784, 3211320, 3276856, 3342392, 3407928, 3473464, 3539000, 3604536,
3670072, 3735608, 4259896, 4325432, 4390968, 4456504, 4522040, 4587576,
3145785, 3211321, 3276857, 3342393, 3407929, 3473465, 3539001, 3604537,
3670073, 3735609, 4259897, 4325433, 4390969, 4456505, 4522041, 4587577,
3145793, 3211329, 3276865, 3342401, 3407937, 3473473, 3539009, 3604545,
3670081, 3735617, 4259905, 4325441, 4390977, 4456513, 4522049, 4587585,
3145794, 3211330, 3276866, 3342402, 3407938, 3473474, 3539010, 3604546,
3670082, 3735618, 4259906, 4325442, 4390978, 4456514, 4522050, 4587586,
3145795, 3211331, 3276867, 3342403, 3407939, 3473475, 3539011, 3604547,
3670083, 3735619, 4259907, 4325443, 4390979, 4456515, 4522051, 4587587,
3145796, 3211332, 3276868, 3342404, 3407940, 3473476, 3539012, 3604548,
3670084, 3735620, 4259908, 4325444, 4390980, 4456516, 4522052, 4587588,
3145797, 3211333, 3276869, 3342405, 3407941, 3473477, 3539013, 3604549,
3670085, 3735621, 4259909, 4325445, 4390981, 4456517, 4522053, 4587589,
3145798, 3211334, 3276870, 3342406, 3407942, 3473478, 3539014, 3604550,
3670086, 3735622, 4259910, 4325446, 4390982, 4456518, 4522054, 4587590
};
}
}
|
require './test/test_helper'
require './lib/gameboard'
class GameBoardTest < Minitest::Test
def setup
@board = GameBoard.new
end
def test_it_is_a_gameboard
assert_instance_of GameBoard, @board
end
def test_it_has_16_valid_placement_locations
result = @board.valid_locations
assert_equal 16, result.size
end
def test_it_has_a_header_and_footer
result = @board.header_and_footer
assert_equal ['+++++++++'], result
end
def test_it_has_column_labels
result = @board.column_labels
assert_equal ['.', '1', '2', '3', '4'], result
end
def test_it_has_a_flexible_row_method
result = @board.row('A')
assert_equal ['A', ' ', ' ', ' ', ' '], result
end
def test_it_has_a_full_board
result = @board.board
board = [['+++++++++'],
['.', '1', '2', '3', '4'],
['A', ' ', ' ', ' ', ' '],
['B', ' ', ' ', ' ', ' '],
['C', ' ', ' ', ' ', ' '],
['D', ' ', ' ', ' ', ' '],
['+++++++++']]
assert_equal board, result
end
end
|
import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { User } from 'src/app/Interfaces/user.model';
import { RecipesService } from 'src/app/services/recipes.service';
import { DomSanitizer } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { AuthenticationService } from 'src/app/services/authentication.service';
@Component({
selector: 'popup-followers',
templateUrl: './followers.component.html',
styleUrls: ['./followers.component.css']
})
export class FollowersComponent implements OnInit {
@Input()
followers_users: User[];
avatars: any[] = [];
@ViewChild('closebutton') closebutton: ElementRef;
constructor(
private recipesService: RecipesService,
private domSanitizer: DomSanitizer,
public authService: AuthenticationService,
private router: Router
) {
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
}
ngOnInit() {
}
ngOnChanges(){
if(this.followers_users.length > 0){
this.get_followers_images();
}
}
get_followers_images(){
this.followers_users.forEach(user => {
this.recipesService.getRecipeAvatar(user.id).subscribe(
data => {
var urlCreator = window.URL;
this.avatars.push(this.domSanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(data)));
}
);
});
}
visitProfile(id: number){
if(this.authService.user.id === id){
this.router.navigateByUrl('/profile');
}else{
this.router.navigateByUrl('/users/'+id);
}
this.closebutton.nativeElement.click();
}
}
|
package alektas.telecomapp.domain.entities.converters
import org.junit.Test
import org.junit.Assert.*
class ValueConverterTest {
// 8-разрядный конвертер оперирует значениями от 0 до 255
private val bitDepth = 8
private val converter = ValueConverter(bitDepth)
@Test
fun convertToBitString_zeroValue_isCorrect() {
val data = doubleArrayOf(0.0)
val string = converter.convertToBitString(data)
assertEquals("00000000", string)
}
@Test
fun convertToBitString_minAndMaxValues_isCorrect() {
val data = doubleArrayOf(0.0, 1.0)
val string = converter.convertToBitString(data)
assertEquals("0000000011111111", string)
}
@Test
fun convertToBitString_severalBipolarValues_isCorrect() {
val data = doubleArrayOf(0.0, 1.0, -1.0)
val string = converter.convertToBitString(data)
assertEquals("011111111111111100000000", string)
}
@Test
fun convertToValues_zero_isCorrect() {
val actual = converter.convertToBipolarNormalizedValues("00000000")
val expected = doubleArrayOf(-1.0)
assertArrayEquals(expected, actual, 0.0)
}
@Test
fun convertToValues_minAndMaxValues_isBipolar() {
val actual = converter.convertToBipolarNormalizedValues("0000000011111111")
val expected = doubleArrayOf(-1.0, 1.0)
assertArrayEquals(expected, actual, 0.0)
}
@Test
fun convertToValues_severalValues_isBipolar() {
val actual = converter.convertToBipolarNormalizedValues("011111111111111100000000")
val expected = doubleArrayOf(0.0, 1.0, -1.0)
assertArrayEquals(expected, actual, 1 / converter.maxLevel.toDouble())
}
}
|
require 'spec_helper'
require 'htauth/algorithm'
describe HTAuth::Algorithm do
it "raises an error if it encouners an unknown algorithm" do
_ { HTAuth::Algorithm.algorithm_from_name("unknown") }.must_raise(::HTAuth::InvalidAlgorithmError)
end
end
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Network.Wai
import Network.HTTP.Types
import Network.HTTP.Client (RequestBody(RequestBodyBS))
import Network.Wai.Handler.Warp (run)
import Data.Monoid ((<>))
import Data.ByteString.Char8 hiding (putStrLn)
import qualified Data.ByteString.Lazy as LBS
import Lib (send)
app :: Application
app req respond = do
body <- strictRequestBody req
send $ "{\"text\": \"```" <>
"REMOTE: " <> RequestBodyBS remote <> "\n" <>
-- "USERAGENT: " <> RequestBodyBS userAgent <> "\n" <>
-- "PATH: " <> RequestBodyBS path <> "\n" <>
-- "QUERY: " <> RequestBodyBS query <> "\n" <>
-- "METHOD: " <> RequestBodyBS method <> "\n" <>
-- "HEAD: " <> RequestBodyBS head <> "\n" <>
"This is a clean test" <>
"```\"}"
print $ "REMOTE: " <> remote
print $ "USERAGENT: " <> userAgent
print $ "PATH: " <> path
print $ "QUERY: " <> query
print $ "METHOD: " <> method
print $ "HEAD: " <> head
print $ "BODY: " <> body
putStrLn "------------------------------------------------------------------"
respond $ responseLBS
status200
[("Content-Type", "text/plain")]
"Hello, Web!"
where remote = (pack $ show $ remoteHost req) :: ByteString
userAgent = (pack $ show $ requestHeaderUserAgent req) :: ByteString
path = rawPathInfo req :: ByteString
query = rawQueryString req :: ByteString
method = requestMethod req :: ByteString
head = (pack $ show $ requestHeaders req) :: ByteString
main :: IO ()
main = do
putStrLn $ "http://localhost:8080/"
run 8080 app
|
-- | Environments implemented as tree maps.
module MapEnv where
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Traversable as Trav
type Env = Map
-- | Query
lookup :: (Ord k) => k -> Env k v -> Maybe v
lookup = Map.lookup
lookupSafe :: (Ord k, Show k) => k -> Env k v -> v
lookupSafe k = maybe (error $ "internal error: unbound key " ++ show k) id .
MapEnv.lookup k
-- | Construction
empty :: Env k v
empty = Map.empty
singleton :: k -> v -> Env k v
singleton = Map.singleton
insert :: (Ord k) => k -> v -> Env k v -> Env k v
insert = Map.insert
update :: (Ord k) => Env k v -> k -> v -> Env k v
update rho x v = Map.insert x v rho
-- | Left-biased union
union :: (Ord k) => Env k v -> Env k v -> Env k v
union = Map.union
mapM :: (Monad m) => (v -> m w) -> Env k v -> m (Env k w)
mapM = Trav.mapM
|
package com.fasterxml.jackson.jr.ob.impl;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.jr.ob.JSON;
import com.fasterxml.jackson.jr.ob.JSONObjectException;
import com.fasterxml.jackson.jr.ob.TestBase;
import com.fasterxml.jackson.jr.ob.api.ReaderWriterProvider;
import com.fasterxml.jackson.jr.ob.api.ValueReader;
public class CustomValueReadersTest extends TestBase
{
static class CustomValue {
public int value;
// 2nd arg just to avoid discovery
public CustomValue(int v, boolean b) {
// and to ensure it goes through constructor, add 1
value = v + 1;
}
}
static class CustomValueBean {
public CustomValue custom;
protected CustomValueBean() { }
public CustomValueBean(int v) {
custom = new CustomValue(v, false);
}
}
enum ABC {
A, B, C, DEF;
}
static class CustomValueReader extends ValueReader {
private final int delta;
public CustomValueReader(int d) {
super(CustomValue.class);
delta = d;
}
@Override
public Object read(JSONReader reader, JsonParser p) throws IOException {
return new CustomValue(p.getIntValue() + delta, true);
}
// Base class impl should be fine, although we'd use this for optimal
/*
@Override
public Object readNext(JSONReader reader, JsonParser p) throws IOException {
return new CustomValue(p.nextIntValue(-1), true);
}
*/
}
static class ABCValueReader extends ValueReader {
public ABCValueReader() {
super(ABC.class);
}
@Override
public Object read(JSONReader reader, JsonParser p) throws IOException {
final String str = p.getText();
if ("n/a".equals(str)) {
return ABC.DEF;
}
return ABC.valueOf(str);
}
}
static class CapStringReader extends ValueReader {
public CapStringReader() {
super(String.class);
}
@Override
public Object read(JSONReader reader, JsonParser p) throws IOException {
return p.getText().toUpperCase();
}
}
static class OverrideStringReader extends ValueReader {
final String _value;
public OverrideStringReader(String str) {
super(String.class);
_value = str;
}
@Override
public Object read(JSONReader reader, JsonParser p) throws IOException {
p.skipChildren();
return _value;
}
}
static class CustomReaders extends ReaderWriterProvider {
final int delta;
public CustomReaders(int d) {
delta = d;
}
@Override
public ValueReader findValueReader(JSONReader readContext, Class<?> type) {
if (type.equals(CustomValue.class)) {
return new CustomValueReader(delta);
} else if (type.equals(ABC.class)) {
return new ABCValueReader();
}
return null;
}
}
static class CapStringReaderProvider extends ReaderWriterProvider {
@Override
public ValueReader findValueReader(JSONReader readContext, Class<?> type) {
if (type.equals(String.class)) {
return new CapStringReader();
}
return null;
}
}
static class OverrideStringReaderProvider extends ReaderWriterProvider {
final ValueReader vr;
public OverrideStringReaderProvider(String str) {
vr = new OverrideStringReader(str);
}
@Override
public ValueReader findValueReader(JSONReader readContext, Class<?> type) {
if (type.equals(String.class)) {
return vr;
}
return null;
}
}
static class Point {
public int _x, _y;
public Point(int x, int y) {
_x = x;
_y = y;
}
}
static class PointReader extends ValueReader {
public PointReader() { super(Point.class); }
@Override
public Object read(JSONReader reader, JsonParser p) throws IOException {
Map<String, Object> map = reader.readMap();
return new Point((Integer) map.get("x"), (Integer) map.get("y"));
}
}
static class PointReaderProvider extends ReaderWriterProvider {
@Override
public ValueReader findValueReader(JSONReader readContext, Class<?> type) {
if (type == Point.class) {
return new PointReader();
}
return null;
}
}
static class NoOpProvider extends ReaderWriterProvider {
}
/*
/**********************************************************************
/* Test methdods
/**********************************************************************
*/
public void testCustomBeanReader() throws Exception
{
// First: without handler, will fail to map
try {
JSON.std.beanFrom(CustomValue.class, "123");
fail("Should not pass");
} catch (JSONObjectException e) {
verifyException(e, ".CustomValue");
verifyException(e, "constructor to use");
}
// then with custom, should be fine
JSON json = jsonWithProvider(new CustomReaders(0));
CustomValue v = json.beanFrom(CustomValue.class, "123");
assertEquals(124, v.value);
// similarly with wrapper
CustomValueBean bean = json.beanFrom(CustomValueBean.class,
aposToQuotes("{ 'custom' : 137 }"));
assertEquals(138, bean.custom.value);
// but also ensure we can change registered handler(s)
JSON json2 = jsonWithProvider(new CustomReaders(100));
v = json2.beanFrom(CustomValue.class, "123");
assertEquals(224, v.value);
}
public void testChainedCustomBeanReaders() throws Exception
{
JSON json = jsonWithProviders(new CustomReaders(0),
new CustomReaders(100));
CustomValue v = json.beanFrom(CustomValue.class, "69");
assertEquals(70, v.value);
json = jsonWithProviders(new CustomReaders(100),
new CustomReaders(0));
v = json.beanFrom(CustomValue.class, "72");
assertEquals(173, v.value);
}
public void testCustomEnumReader() throws Exception
{
// First: without handler, will fail to map
try {
JSON.std.beanFrom(ABC.class, quote("n/a"));
fail("Should not pass");
} catch (JSONObjectException e) {
verifyException(e, "Failed to find Enum of type");
}
// then with custom, should be fine
JSON json = jsonWithProvider(new CustomReaders(0));
ABC v = json.beanFrom(ABC.class, quote("n/a"));
assertEquals(ABC.DEF, v);
// but if we remove, again error
JSON json2 = jsonWithProvider((ReaderWriterProvider) null);
try {
json2.beanFrom(ABC.class, quote("n/a"));
fail("Should not pass");
} catch (JSONObjectException e) {
verifyException(e, "Failed to find Enum of type");
}
}
// Even more fun, override default String deserializer!
public void testCustomStringReader() throws Exception
{
String allCaps = jsonWithProvider(new CapStringReaderProvider())
.beanFrom(String.class, quote("Some text"));
assertEquals("SOME TEXT", allCaps);
}
public void testChainedStringReaders() throws Exception {
String result = jsonWithProviders(new CapStringReaderProvider(),
new OverrideStringReaderProvider("foo"))
.beanFrom(String.class, quote("Some text"));
assertEquals("SOME TEXT", result);
result = jsonWithProviders(new NoOpProvider(), new OverrideStringReaderProvider("foo"))
.beanFrom(String.class, quote("Some text"));
assertEquals("foo", result);
// and ok not to have anything, too
result = jsonWithProviders(new NoOpProvider(), new NoOpProvider())
.beanFrom(String.class, quote("Some text"));
assertEquals("Some text", result);
// Plus nulls fine too
result = jsonWithProviders(null, new OverrideStringReaderProvider("foo"))
.beanFrom(String.class, quote("Some text"));
assertEquals("foo", result);
result = jsonWithProviders(new OverrideStringReaderProvider("foo"), null)
.beanFrom(String.class, quote("Some text"));
assertEquals("foo", result);
}
// But also can use methods from "JSONReader" for convenience
public void testCustomDelegatingReader() throws Exception
{
// First: without handler, will fail to map
final String doc = "{\"y\" : 3, \"x\": 2 }";
try {
JSON.std.beanFrom(Point.class, doc);
fail("Should not pass");
} catch (JSONObjectException e) {
verifyException(e, "$Point");
verifyException(e, "constructor to use");
}
// then with custom, should be fine
JSON json = jsonWithProvider(new PointReaderProvider());
Point v = json.beanFrom(Point.class, doc);
assertEquals(2, v._x);
assertEquals(3, v._y);
}
}
|
using Voltaic.Serialization;
using System.Collections.Generic;
using Voltaic;
namespace Wumpus.Entities
{
/// <summary> xxx </summary>
[IgnoreProperties("members")]
public class RpcGuild
{
/// <summary> xxx </summary>
[ModelProperty("id")]
public Snowflake Id { get; set; }
/// <summary> xxx </summary>
[ModelProperty("name")]
public Utf8String Name { get; set; }
/// <summary> xxx </summary>
[ModelProperty("icon_url")]
public Utf8String IconUrl { get; set; }
}
}
|
package main
type MimeTypes = map[string]string
var mimes = MimeTypes{
".css": "text/css; charset=utf-8",
".csv": "text/csv; charset=utf-8",
".md": "text/markdown; charset=utf-8",
".markdown": "text/markdown; charset=utf-8",
".htm": "text/html; charset=utf-8",
".html": "text/html; charset=utf-8",
".shtml": "text/html; charset=utf-8",
".xml": "text/xml; charset=utf-8",
".txt": "text/plain; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".xhtml": "application/xhtml+xml; charset=utf-8",
".json": "application/json; charset=utf-8",
".map": "application/json; charset=utf-8",
".webmanifest": "application/manifest+json; charset=utf-8",
".pdf": "application/pdf",
".wasm": "application/wasm",
".webapp": "application/x-web-app-manifest+json; charset=utf-8",
".appcache": "text/cache-manifest; charset=utf-8",
".gif": "image/gif",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".apng": "image/apng",
".avif": "image/avif",
".avifs": "image/avif-sequence",
".webp": "image/webp",
".svg": "image/svg+xml; charset=utf-8",
".ico": "image/x-icon",
".woff": "font/woff",
".woff2": "font/woff2",
".eot": "application/vnd.ms-fontobject",
".ttf": "font/ttf",
".ttc": "font/collection",
".otf": "font/otf",
}
|
export enum IndicatorStatus {
UNKNOWN = "UNKNOWN",
UP = "UP",
DOWN = "DOWN",
}
export interface IndicatorResponse {
status: IndicatorStatus;
lastCheck: number | null;
response?: any;
error?: any;
}
export interface IndicatorOptions {
timeout?: number;
}
export type Indicator = () => Promise<any>;
|
using System;
using System.IO;
using GDataDB.Impl;
using Google.GData.Client;
using Google.GData.Documents;
using Google.GData.Spreadsheets;
using SpreadsheetQuery=Google.GData.Documents.SpreadsheetQuery;
namespace GDataDB {
public class DatabaseClient : IDatabaseClient {
private readonly IService documentService;
private readonly IService spreadsheetService;
public IService DocumentService
{
get { return documentService; }
}
public IService SpreadsheetService
{
get { return spreadsheetService; }
}
public DatabaseClient(string username, string password) {
var docService = new DocumentsService("database");
docService.setUserCredentials(username, password);
documentService = docService;
var ssService = new SpreadsheetsService("database");
ssService.setUserCredentials(username, password);
spreadsheetService = ssService;
}
public IDatabase CreateDatabase(string name) {
using (var ms = new MemoryStream()) {
using (var sw = new StreamWriter(ms)) {
sw.WriteLine(",,,");
var spreadSheet = DocumentService.Insert(new Uri(DocumentsListQuery.documentsBaseUri), ms, "text/csv", name);
return new Database(this, spreadSheet);
}
}
}
public IDatabase GetDatabase(string name) {
var feed = DocumentService.Query(new SpreadsheetQuery {TitleExact = true, Title = name });
if (feed.Entries.Count == 0)
return null;
return new Database(this, feed.Entries[0]);
}
}
}
|
<?php
/* Support for Flash theme */
$flash = '
.page-template-builder-fullwidth-std #page #flash-breadcrumbs {
display: none;
}
.page-template-builder-fullwidth-std .site-content .tg-container {
max-width: 100%;
}
@media (max-width: 1200px) {
.page-template-builder-fullwidth-std .site-content .tg-container {
padding: 0;
width: 100%;
}
}
';
wp_add_inline_style( 'flash-style', $flash );
|
# SCRIPT MENU #
###############################################
# Chargement des classes
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
. .\hide_console.ps1
###############################################
############# CREATION DE LA FENETRE ###############
$objFormPanel = New-Object System.Windows.Forms.Form
$objFormPanel.Text = "Menu"
$objFormPanel.Size = New-Object System.Drawing.Size(300,400)
$objFormPanel.StartPosition = "CenterScreen"
$objFormPanel.BackColor = "#02ACE5"
###############################################
############# Texte : "Choisir l'action a effectuer" ###############
# Texte affiché #
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(40,70)
$objLabel.Size = New-Object System.Drawing.Size(280,20)
$objLabel.ForeColor = "White"
$objLabel.Text = "Choisissez l'action à effectuer"
$objLabel.Font = New-Object System.Drawing.Font ("Tahoma", 10, [System.Drawing.FontStyle]::Bold)
$objFormPanel.Controls.Add($objLabel)
# Bouton gestion des utilisateurs #
$UserButton = New-Object System.Windows.Forms.Button
$UserButton.Location = New-Object System.Drawing.Size(10,120)
$UserButton.Size = New-Object System.Drawing.Size(260,40)
$UserButton.Text = "Gestion des utilisateurs"
$UserButton.Font = New-Object System.Drawing.Font ("Tahoma", 10, [System.Drawing.FontStyle]::Bold)
$UserButton.ForeColor = "White"
$UserButton.Add_Click({.\gestion_users\choix_action_users.ps1;$objFormPanel.Close()})
$objFormPanel.Controls.Add($UserButton)
# Bouton gestion des ordinateurs #
$ComputersButton = New-Object System.Windows.Forms.Button
$ComputersButton.Location = New-Object System.Drawing.Size(10,180)
$ComputersButton.Size = New-Object System.Drawing.Size(260,40)
$ComputersButton.Text = "Gestion des ordinateurs"
$ComputersButton.Font = New-Object System.Drawing.Font ("Tahoma", 10, [System.Drawing.FontStyle]::Bold)
$ComputersButton.ForeColor = "White"
$ComputersButton.Add_Click({})
$objFormPanel.Controls.Add($ComputersButton)
# Bouton quitter #
$QuitButton = New-Object System.Windows.Forms.Button
$QuitButton.Location = New-Object System.Drawing.Size(105,320)
$QuitButton.Size = New-Object System.Drawing.Size(75,23)
$QuitButton.Text = "Quitter"
$QuitButton.ForeColor = "White"
$QuitButton.Add_Click({$objFormPanel.Close()})
$objFormPanel.Controls.Add($QuitButton)
###############################################
###############################################
# Affichage des éléments
$objFormPanel.Topmost = $True
$objFormPanel.Add_Shown({
$objFormPanel.Activate()
Hide-Console
})
[void] $objFormPanel.ShowDialog()
###############################################
|
package typingsSlinky.novncCore
import typingsSlinky.novncCore.mod.NvConnectionState
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object novncCoreStrings {
@js.native
sealed trait connected extends NvConnectionState
@scala.inline
def connected: connected = "connected".asInstanceOf[connected]
@js.native
sealed trait connecting extends NvConnectionState
@scala.inline
def connecting: connecting = "connecting".asInstanceOf[connecting]
@js.native
sealed trait debug extends StObject
@scala.inline
def debug: debug = "debug".asInstanceOf[debug]
@js.native
sealed trait disconnected extends NvConnectionState
@scala.inline
def disconnected: disconnected = "disconnected".asInstanceOf[disconnected]
@js.native
sealed trait disconnecting extends NvConnectionState
@scala.inline
def disconnecting: disconnecting = "disconnecting".asInstanceOf[disconnecting]
@js.native
sealed trait error extends StObject
@scala.inline
def error: error = "error".asInstanceOf[error]
@js.native
sealed trait info extends StObject
@scala.inline
def info: info = "info".asInstanceOf[info]
@js.native
sealed trait none extends StObject
@scala.inline
def none: none = "none".asInstanceOf[none]
@js.native
sealed trait normal extends StObject
@scala.inline
def normal: normal = "normal".asInstanceOf[normal]
@js.native
sealed trait warn extends StObject
@scala.inline
def warn: warn = "warn".asInstanceOf[warn]
}
|
<?php
declare(strict_types=1);
namespace AppBundle\Service\Pusher;
use Exception;
/**
* Interface RealTimeServiceInterface
* @package AppBundle\Service\Pusher
*/
interface RealTimeServiceInterface
{
/**
* @param array $data
* @return $this
* @throws Exception
*/
public function dispatch(array $data);
/**
* @param string $event
* @return $this
*/
public function setEvent(string $event);
}
|
//package com.dslplatform.storage;
//
//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.UUID;
//import java.util.concurrent.ExecutionException;
//
//import org.apache.commons.io.IOUtils;
//
//import com.dslplatform.client.Bootstrap;
//import com.dslplatform.client.ProjectSettings;
//import com.dslplatform.patterns.ServiceLocator;
//import com.fasterxml.jackson.annotation.JacksonInject;
//import com.fasterxml.jackson.annotation.JsonCreator;
//import com.fasterxml.jackson.annotation.JsonProperty;
//
///**
// * Data structure for working with S3 binaries.
// * Instead of storing binaries in the database, S3 can be used
// * to store bucket and key in the database which point to the
// * binary on remote server.
// */
//def class S3 extends java.io.Serializable {
//
// @JsonCreator
// protected S3(
// @JacksonInject("_serviceLocator") locator ServiceLocator,
// @JsonProperty("Bucket") bucket String,
// @JsonProperty("Key") key String,
// @JsonProperty("Length") length int,
// @JsonProperty("Name") name String,
// @JsonProperty("MimeType") mimeType String,
// @JsonProperty("Metadata") final Map<String, String> metadata) {
// this.instanceRepository = locator.resolve(S3Repository.class);
// this.bucket = bucket;
// this.key = key;
// this.length = length;
// this.name = name;
// this.mimeType = mimeType;
// if(metadata != null) {
// for(Map.Entry<String, String> kv : metadata.entrySet())
// this.metadata.put(kv.getKey(), kv.getValue());
// }
// }
//
// /**
// * Create new instance of S3.
// * Upload must be called before persistence to the database.
// */
// def S3() {
// instanceRepository = null;
// }
// /**
// * Create new instance of S3. Provide custom {@link S3Repository S3 repository}.
// * Upload must be called before persistence to the database.
// *
// * @param repository custom S3 repository
// */
// def S3(S3Repository repository) {
// instanceRepository = repository;
// }
// /**
// * Create new instance of S3 from provided stream.
// * Upload will be called immediately. Stream will be read to check for length.
// *
// * @param stream Input stream which will be sent to the remote server
// */
// def S3(stream InputStream) throws IOException {
// instanceRepository = null;
// upload(IOUtils.toByteArray(stream));
// }
// /**
// * Create new instance of S3 from provided stream.
// * Upload will be called immediately.
// *
// * @param stream Input stream which will be sent to the remote server
// * @param length size of the stream
// */
// def S3(stream InputStream, long length) throws IOException {
// instanceRepository = null;
// upload(stream, length);
// }
// /**
// * Create new instance of S3 from provided byte array.
// * Upload will be called immediately.
// *
// * @param bytes Byte array which will be sent to the remote server
// */
// def S3(final byte[] bytes) throws IOException {
// instanceRepository = null;
// upload(bytes);
// }
//
// private instanceRepository S3Repository;
// @SuppressWarnings("deprecation")
// private S3Repository static staticRepository = Bootstrap.getLocator().resolve(S3Repository.class);
// @SuppressWarnings("deprecation")
// private String static bucketName = Bootstrap.getLocator().resolve(ProjectSettings.class).get("s3-bucket");
// private S3Repository getRepository() {
// return instanceRepository != null ? instanceRepository : staticRepository;
// }
//
// private String bucket;
//
// /**
// * Bucket under which data will be saved.
// * By default bucket is defined in the dsl-project.props file under s3-bucket key
// *
// * @return bucket to remote server
// */
// @JsonProperty("Bucket")
// def String getBucket() { return bucket; }
//
// private String key;
//
// /**
// * Key for bucket in which the data was saved.
// *
// * @return key in bucket on the remote server
// */
// @JsonProperty("Key")
// def String getKey() { return key; }
//
// def String getURI() { return bucket + ":" + key; }
//
// private long length;
//
// /**
// * Byte length of data.
// *
// * @return number of bytes
// */
// @JsonProperty("Length")
// def long getLength() { return length; }
//
// private String name;
//
// /**
// * For convenience, remote data can be assigned a name.
// *
// * @return name associated with the remote data
// */
// def String getName() { return name; }
//
// /**
// * For convenience, remote data can be assigned a name.
// *
// * @param value name which will be associated with data
// * @return itself
// */
// def S3 setName(value String) {
// name = value;
// return this;
// }
//
// private String mimeType;
//
// /**
// * For convenience, remote data can be assigned a mime type.
// *
// * @return mime type associated with the remote data
// */
// @JsonProperty("MimeType")
// def String getMimeType() { return mimeType; }
//
// /**
// * For convenience, remote data can be assigned a mime type.
// *
// * @param value mime type which will be associated with data
// * @return itself
// */
// def S3 setMimeType(value String) {
// mimeType = value;
// return this;
// }
//
// private final HashMap<String, String> metadata = new HashMap<String, String>();
//
// /**
// * For convenience, various metadata can be associated with the remote data.
// * Metadata is a map of string keys and values
// *
// * @return associated metadata
// */
// @JsonProperty("Metadata")
// def Map<String, String> getMetadata() { return metadata; }
//
// private byte[] cachedContent;
//
// /**
// * Get bytes saved on the remote server.
// * Data will be cached, so subsequent request will reuse downloaded bytes.
// *
// * @return bytes saved on the remote server
// * @throws IOException in case of communication failure
// */
// def byte[] getContent() throws IOException {
// if (cachedContent != null)
// cachedContent = getBytes();
// return cachedContent;
// }
//
// /**
// * Get stream saved on the remote server.
// * Data will not be cached, so subsequent request will download stream again.
// *
// * @return stream saved on the remote server
// * @throws IOException in case of communication failure
// */
// def InputStream getStream() throws IOException {
// if(key == null || key == "")
// return null;
// try{
// return getRepository().get(bucket, key).get();
// } catch (InterruptedException e) {
// throw new IOException(e);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// }
//
// /**
// * Get bytes saved on the remote server.
// * Data will not be cached, so subsequent request will download bytes again.
// *
// * @return bytes saved on the remote server
// * @throws IOException in case of communication failure
// */
// def byte[] getBytes() throws IOException {
// if (key == null || key == "")
// return null;
// stream InputStream;
// try {
// stream = getRepository().get(bucket, key).get();
// } catch (InterruptedException e) {
// throw new IOException(e);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// return IOUtils.toByteArray(stream);
// }
//
// /**
// * Upload provided stream to remote S3 server.
// * If key is already defined, this stream will overwrite remote stream,
// * otherwise new key will be created.
// *
// * @param stream upload provided stream
// * @return key under which data was saved
// * @throws IOException in case of communication error
// */
// def String upload(stream ByteArrayInputStream) throws IOException {
// return upload(IOUtils.toByteArray(stream));
// }
//
// /**
// * Upload provided stream to remote S3 server.
// * If key is already defined, this stream will overwrite remote stream,
// * otherwise new key will be created.
// *
// * @param stream upload provided stream
// * @param length size of provided stream
// * @return key under which data was saved
// * @throws IOException in case of communication error
// */
// def String upload(InputStream stream, long length) throws IOException {
// return upload(bucket != null && bucket.length() > 0 ? bucket : bucketName, stream, length);
// }
//
// /**
// * Upload provided stream to remote S3 server.
// * If key is already defined, this stream will overwrite remote stream,
// * otherwise new key will be created.
// * If key was already defined, bucket name can't be changed.
// *
// * @param bucket bucket under data will be saved
// * @param stream upload provided stream
// * @param length size of provided stream
// * @return key under which data was saved
// * @throws IOException in case of communication error
// */
// def String upload(String bucket, InputStream stream, long length) throws IOException {
// if (stream == null)
// throw new IllegalArgumentException("Stream can't be null.");
// if (key == null || key == "") {
// this.bucket = bucket;
// key = UUID.randomUUID().toString();
// }
// else if (this.bucket != bucket) {
// throw new IllegalArgumentException("Can't change bucket name");
// }
// try{
// getRepository().upload(this.bucket, this.key, stream, length, metadata).get();
// } catch (InterruptedException e) {
// throw new IOException(e);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// this.length = length;
// cachedContent = null;
// return this.key;
// }
//
// /**
// * Upload provided bytes to remote S3 server.
// * If key is already defined, this bytes will overwrite remote bytes,
// * otherwise new key will be created.
// *
// * @param bytes upload provided bytes
// * @return key under which data was saved
// * @throws IOException in case of communication error
// */
// def String upload(byte[] bytes) throws IOException {
// return upload(bucket != null && bucket.length() > 0 ? bucket : bucketName, bytes);
// }
//
// /**
// * Upload provided bytes to remote S3 server.
// * If key is already defined, this bytes will overwrite remote bytes,
// * otherwise new key will be created.
// * If key was already defined, bucket name can't be changed.
// *
// * @param bucket bucket under data will be saved
// * @param bytes upload provided bytes
// * @return key under which data was saved
// * @throws IOException in case of communication error
// */
// def String upload(bucket String, final byte[] bytes) throws IOException {
// if (bytes == null)
// throw new IllegalArgumentException("Stream can't be null.");
// if (key == null || key == "") {
// this.bucket = bucket;
// key = UUID.randomUUID().toString();
// }
// else if (this.bucket != bucket) {
// throw new IllegalArgumentException("Can't change bucket name");
// }
// stream ByteArrayInputStream = new ByteArrayInputStream(bytes);
// try{
// getRepository().upload(bucket, this.key, stream, bytes.length, metadata).get();
// } catch (InterruptedException e) {
// System.out.println(e.getMessage());
// throw new IOException(e);
// } catch (ExecutionException e) {
// System.out.println(e.getMessage());
// throw new IOException(e);
// }
// this.length = bytes.length;
// cachedContent = null;
// return this.key;
// }
//
// /**
// * Remote data from the remote S3 server.
// *
// * @throws IOException in case of communication error
// */
// def void delete() throws IOException {
// if (key == null || key == "")
// throw new IllegalArgumentException("S3 object is empty.");
// cachedContent = null;
// try {
// getRepository().delete(bucket, key).get();
// } catch (InterruptedException e) {
// throw new IOException(e);
// } catch (ExecutionException e) {
// throw new IOException(e);
// }
// length = 0;
// cachedContent = null;
// key = null;
// }
//
// private static serialVersionUID long = 1L;
//}
|
import { Card } from "../../heartstone.dto";
export class FilteringFunctionFactory {
static getFilteringFunction(filterBy: Filter, value: string){
let func = (card: Card) => {
return card[filterBy].includes(value);
}
return func;
}
static getFilteringString(filterBy: Filter, value: string) {
return `${filterBy} = ${value}`;
}
}
export enum Filter {
ByName = "name",
ByClass = "class",
ByCost = "cost",
ByAttack = "attack",
ByHealth = "health",
ByRarity = "rarity",
ByType = "type",
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using Helpy.Pages;
namespace Helpy.Code
{
public static class Utils
{
public static void RunJS(Page page, string js, string key)
{
page.Page.ClientScript.RegisterStartupScript(page.GetType(), key, js, true);
}
public static void AlertJs(Page page, string message, string key)
{
RunJS(page, message, key);
}
public static class Crypto
{
public static string CalculateMD5Hash(string input)
{
MD5 mmd5 = MD5.Create();
byte[] minputBytes = Encoding.ASCII.GetBytes(input);
byte[] mhash = mmd5.ComputeHash(minputBytes);
StringBuilder msb = new StringBuilder();
foreach (byte mt in mhash)
msb.Append(mt.ToString("X2"));
return msb.ToString();
}
}
}
}
|
require 'chefspec'
describe 'step_into::default' do
context 'without :step_into' do
let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }
it 'does not execute the LWRPs action' do
expect(chef_run).to_not write_log('message')
end
end
context 'with :step_into' do
let(:chef_run) do
ChefSpec::SoloRunner.new(step_into: ['step_into_lwrp'])
.converge(described_recipe)
end
it 'does execute the LWRPs action' do
expect(chef_run).to write_log('message')
end
end
end
|
C @(#)bestep.f 20.3 2/13/96
function bestep (kt, mt, nt, qk, q1, q2, dvdq)
C
C This function evaluates the BEst discrete
C STEP (Q1 or Q2) such that BESTEP has
C
C 1. an estimated voltage which is within limits, and
C 2. the selected Q is closest to QK.
C
c QK, Q1, Q2, DVDQ should be double precision.
c
include 'ipfinc/parametr.inc'
include 'ipfinc/alpha.inc'
c Global variables used:
c vlimn(r*4), vlimx(r*4)
include 'ipfinc/bus.inc'
c Global variables used:
c e (r*8), e(r*8)
include 'ipfinc/ecvar.inc'
c Global variables used:
c idswb
include 'ipfinc/lfiles.inc'
include 'ipfinc/slnopt.inc'
include 'ipfinc/slnphs.inc'
c
c
dimension viol(2,2),dx(2,2)
c
c***kln Single to double
c
double precision viol, dx, dq1, dq2, dx1, dx2, vk, vk1,
+ vk2, dv, dv1, dv2, vm, vm1, vm2
C
dq1 = q1 - qk
dq2 = q2 - qk
dv1 = dvdq * dq1
dv2 = dvdq * dq2
vk = dsqrt (e(kt) ** 2 + f(kt) **2 )
vk1 = vk + dv1
vk2 = vk + dv2
viol(1,1) = -ddim (dble(vlimn(kt)),vk1)
viol(1,2) = ddim (vk1,dble(vlimx(kt)))
viol(2,1) = -ddim (dble(vlimn(kt)),vk2)
viol(2,2) = ddim (vk2,dble(vlimx(kt)))
C Modify these limits if remote control used
if (mt .gt. 0 .and. mt .ne. kt) then
vm = dsqrt (e(mt) ** 2 + f(mt) **2 )
vm1 = vm + dv1 * vm / vk
vm2 = vm + dv2 * vm / vk
dv = -ddim (dble(vlimn(mt)),vm1)
viol(1,1) = dmin1 (dv,viol(1,1))
dv = ddim (vm1,dble(vlimx(mt)))
viol(1,2) = dmax1 (dv,viol(1,2))
dv = -ddim (dble(vlimn(mt)),vm2)
viol(2,1) = dmin1 (dv,viol(2,1))
dv = ddim (vm2,dble(vlimx(mt)))
viol(2,2) = dmax1 (dv,viol(2,2))
endif
C Determine "safest" choice (minimax: minimum of maximum
C violation).
do 90 i = 1,2
do 90 j = 1,2
90 dx(j,i) = dabs (viol(j,i))
dx1 = dmax1 (dx(1,1),dx(1,2))
dx2 = dmax1 (dx(2,1),dx(2,2))
if (dx1 .lt. dx2 ) then
bestep = q1
else if (dx1 .gt. dx2) then
bestep = q2
else
if (dabs(dq1) .lt. abs(dq2)) then
bestep = q1
else
bestep = q2
endif
endif
if (idswb .ne. 0) write (dbug,100) kt,mt,viol,q1,q2,bestep
100 format (' BESTEP/ Type X ',2i6,7e12.5)
return
end
|
module Blobsterix
module Storage
class BucketEntry
attr_accessor :key, :last_modified, :etag, :size, :storage_class, :mimetype, :fullpath
def self.create(file, meta)
BucketEntry.new(file.to_s.gsub("\\", "/")) do |entry|
entry.last_modified = meta.last_modified.strftime("%Y-%m-%dT%H:%M:%S.000Z")
entry.etag = meta.etag
entry.size = meta.size
entry.mimetype = meta.mimetype
end
end
def initialize(key)
@key = key
@last_modified = "2009-10-12T17:50:30.000Z"
@etag = ""fba9dede5f27731c9771645a39863328""
@size = "0"
@storage_class = "STANDARD"
@mimetype = "none"
@fullpath = ""
yield self if block_given?
end
def insert_xml(xml)
xml.Contents{
xml.Key key
xml.LastModified last_modified
xml.ETag etag
xml.Size size
xml.StorageClass storage_class
xml.MimeType mimetype
# xml.FullPath fullpath
}
end
end
end
end
|
using Catalyst3D.XNA.Engine.EntityClasses.Sprites;
using Catalyst3D.XNA.Engine.UtilityClasses;
using Catalyst3D.XNA.Physics;
using Catalyst3D.XNA.Physics.Interfaces;
using Microsoft.Xna.Framework;
namespace Catalyst3D.XNA.Testing.EntityClasses
{
public class Ground : Sprite, IPhysicsBody
{
public float Mass { get; set; }
public Vector2 MaxVelocity { get; set; }
public Compound Compound { get; set; }
public PhysicsManager PhysicsManager { get; set; }
public bool PhysicsEnabled { get; set; }
public Ground(Game game)
: base(game)
{
}
public override void Initialize()
{
// Position it near the bottom of the screen
Position = new Vector2(0, 465);
// Mass of Object
Mass = 2000f;
// Compound the object is made of
Compound = Compound.Solid;
// No physics on the ground itself
PhysicsEnabled = false;
base.Initialize();
}
public override void LoadContent()
{
base.LoadContent();
Texture = Utilitys.GenerateTexture(GraphicsDevice, Color.ForestGreen, 800, 100);
}
}
}
|
# MacOS
Some things specific to development under MacOS.
## Running app
flutter pub get
flutter devices
flutter run
The Google Play Services SDK. You can get this from the Android SDK Manager in Android Studio.
## Running Android emulator
cd ~/Android/Sdk/tools && ./emulator -list-avds
cd ~/Android/Sdk/tools/bin && ./avdmanager list avd
* List all AVDs
avdmanager list
* Create AVDs
avdmanager create avd -n android25 -k "system-images;android-25;google_apis;x86"
* Run AVD (not tested )
./emulator -avd android25
Reference:
https://developer.android.com/studio/command-line/avdmanager.html
## Running iPhone emulator
open -a Simulator
|
/**
* Provides domain use cases. Each use case contains a single public method, and takes advantage of inversion of
* control.
*
* @since 2.0.0
*/
package org.siouan.frontendgradleplugin.domain.usecase;
|
const express = require('express');
const app = express();
const cors = require('cors');
const port = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const sha256 = require('sha256');
const fs = require('fs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(cors({credentials: true, origin: true}));
let state = {nodes:[], links:[]};
/*{
id:1,
name:'vasya',
last_hash:sha256('vasya')
},{id:2, name:'petya', last_hash:sha256('petya')},{id:3,name:'nastya', last_hash:sha256('nastya')}
*/
fs.readFile('state.json','utf8',(err,data)=>{
if(err || !data){
if(err) {console.log('err reading state file',err.name, err.message);}
state.nodes = [];
state.links = [];
state.added = {nodes:[], links:[]};
state.removed = {nodes:[], links:[]};
state.names = [];
state.hashes = [];
state.candidates = [];
}
else{
state= JSON.parse(data);
}
const worker = require('./app/worker.js');
const wrapper = function(){
worker(state)
.then(() => {
setTimeout(wrapper,5000);
})
.catch(err => {
console.log('error on iteration;',err.name,err.message);
setTimeout(wrapper,5000);
});
};
wrapper();
require('./app/routes.js')(app,state);
app.listen(port);
console.log('started on port',port);
});
|
use std::sync::mpsc::{sync_channel, SyncSender};
use std::thread;
use timer::TimeOut;
use state::State;
use types::Cmd;
pub fn time_start(state: &mut State, cmd_tx: SyncSender<Cmd>) {
let c = state.search_state.as_ref()
.expect("invalid search_state")
.pos.side_to_move();
let (time_out_tx, time_out_rx) = sync_channel::<TimeOut>(0);
state.timer.clone().start(c, time_out_tx);
thread::spawn(move || {
let recv_res = time_out_rx.recv();
if recv_res.is_ok() {
cmd_tx.send(Cmd::Stop).unwrap();
}
});
}
|
// <copyright file="SharePointAuthSettings.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.NewHireOnboarding.Models.Configuration
{
/// <summary>
/// A class which helps to provide SharePoint auth settings for application.
/// </summary>
public class SharePointAuthSettings
{
/// <summary>
/// Gets or sets application tenant id.
/// </summary>
public string TenantId { get; set; }
/// <summary>
/// Gets or sets application client id.
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets application secret.
/// </summary>
public string ClientSecret { get; set; }
}
}
|
import { ValidationError as JoiValidationError } from 'joi'
import { AppError } from './app-error'
export class FieldError {
constructor(public readonly field: string, public readonly message: string) {}
static generate(error: JoiValidationError): FieldError[] {
const errors = error?.details ?? []
return errors
.filter(error => error.type !== 'object.unknown')
.map(error => new FieldError(error.context.label, error.message))
}
static includes(errors: FieldError[], ...properties: string[]): boolean {
return errors.some(error => properties.includes(error.field))
}
}
export class ValidationError extends AppError {
readonly statusCode = 400
constructor(errors: FieldError[]) {
super('One or more validations failed.', 'VALIDATION_FAILED', errors)
Object.setPrototypeOf(this, ValidationError.prototype)
}
}
|
require 'tmpdir'
module Stash
module Repo
describe FileBuilder do
describe :file_name do
it 'defaults to the value provided in the initializer' do
file_name = 'qux.txt'
builder = FileBuilder.new(file_name: file_name)
expect(builder.file_name).to eq(file_name)
end
it 'requires a filename' do
builder = FileBuilder.new
expect { builder.file_name }.to raise_error(NoMethodError)
end
it 'can be overridden' do
builder = FileBuilder.new
file_name = 'qux.txt'
builder.define_singleton_method(:file_name) { file_name }
expect(builder.file_name).to eq(file_name)
end
end
describe :log do
it 'returns the Rails logger' do
logger = instance_double(Logger)
allow(Rails).to receive(:logger).and_return(logger)
builder = FileBuilder.new
expect(builder.logger).to be(logger)
end
end
describe :contents do
it 'is abstract' do
builder = FileBuilder.new(file_name: 'qux.txt')
expect { builder.contents }.to raise_error(NoMethodError)
end
end
describe :mime_type do
it 'is abstract' do
builder = FileBuilder.new(file_name: 'qux.txt')
expect { builder.mime_type }.to raise_error(NoMethodError)
end
end
describe :binary? do
it 'defaults to false' do
builder = FileBuilder.new(file_name: 'qux.txt')
expect(builder.binary?).to be false
end
end
describe :write_file do
it 'writes the file' do
allow(Stash::Aws::S3).to receive(:put)
contents = "<contents/>\n"
file_name = 'contents.xml'
target_dir = 'some/bogus/target_dir'
builder = FileBuilder.new(file_name: file_name)
builder.define_singleton_method(:contents) { contents }
builder.write_s3_file(target_dir)
expect(Stash::Aws::S3).to have_received(:put)
.with(s3_key: "#{target_dir}/#{file_name}",
contents: contents)
.at_least(:once)
end
it 'writes nothing if #contents returns nil' do
allow(Stash::Aws::S3).to receive(:put)
file_name = 'contents.xml'
target_dir = 'some/bogus/target_dir'
builder = FileBuilder.new(file_name: file_name)
builder.define_singleton_method(:contents) { nil }
builder.write_s3_file(target_dir)
expect(Stash::Aws::S3).not_to have_received(:put)
end
end
end
end
end
|
declare namespace IEventCardDescription {
export interface IProps {
styles?: React.CSSProperties;
className?: string;
children: string;
}
}
export { IEventCardDescription };
|
/****************************************************************************
* VCGLib o o *
* Visual and Computer Graphics Library o o *
* _ O _ *
* Copyright(C) 2004 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* All rights reserved. *
* *
* 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 (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#ifndef SMALL_COMPONENT_SELECTION_H
#define SMALL_COMPONENT_SELECTION_H
namespace vcg {
namespace tri {
template<class _MeshType>
class SmallComponent
{
public:
typedef _MeshType MeshType;
typedef typename MeshType::VertexType VertexType;
typedef typename MeshType::VertexPointer VertexPointer;
typedef typename MeshType::VertexIterator VertexIterator;
typedef typename MeshType::FaceType FaceType;
typedef typename MeshType::FacePointer FacePointer;
typedef typename MeshType::FaceIterator FaceIterator;
static int Select(MeshType &m, float nbFaceRatio = 0.1, bool nonClosedOnly = false)
{
assert(tri::HasFFAdjacency(m) && "The small component selection procedure requires face to face adjacency.");
// the different components as a list of face pointer
std::vector< std::vector<FacePointer> > components;
for(uint faceSeed = 0; faceSeed<m.face.size(); )
{
// find the first not selected face
bool foundSeed = false;
while (faceSeed<m.face.size())
{
CFaceO& f = m.face[faceSeed];
if (!f.IsS())
{
if (nonClosedOnly)
{
for (int k=0; k<3; ++k)
if (face::IsBorder(f,k))
{
foundSeed = true;
break;
}
}
else
foundSeed = true;
if (foundSeed)
break;
}
++faceSeed;
}
if (!foundSeed) // no more seed, stop
break;
// expand the region from this face...
components.resize(components.size()+1);
std::vector<FacePointer> activefaces;
activefaces.push_back(&m.face[faceSeed]);
while (!activefaces.empty())
{
FacePointer f = activefaces.back();
activefaces.pop_back();
if (f->IsS())
continue;
f->SetS();
components.back().push_back(f);
for (int k=0; k<3; ++k)
{
if (face::IsBorder(*f,k))
continue;
FacePointer of = f->FFp(k);
if (!of->IsS())
activefaces.push_back(of);
}
}
++faceSeed;
}
UpdateSelection<MeshType>::FaceClear(m);
// now the segmentation is done, let's compute the absolute face count threshold
int total_selected = 0;
int maxComponent = 0;
for (uint i=0; i<components.size(); ++i)
{
//std::cout << "Component " << i << " -> " << components[i].size() << "\n";
total_selected += components[i].size();
maxComponent = std::max<int>(maxComponent,components[i].size());
}
int remaining = m.face.size() - total_selected;
uint th = std::max(maxComponent,remaining) * nbFaceRatio;
int selCount = 0;
for (uint i=0; i<components.size(); ++i)
{
if (components[i].size()<th)
{
selCount += components[i].size();
for (uint j=0; j<components[i].size(); ++j)
components[i][j]->SetS();
}
}
return selCount;
}
static void DeleteFaceVert(MeshType &m)
{
typename MeshType::FaceIterator fi;
typename MeshType::VertexIterator vi;
UpdateSelection<MeshType>::VertexClear(m);
UpdateSelection<MeshType>::VertexFromFaceStrict(m);
for(fi=m.face.begin();fi!=m.face.end();++fi)
if (!(*fi).IsD() && (*fi).IsS() )
tri::Allocator<CMeshO>::DeleteFace(m,*fi);
for(vi=m.vert.begin();vi!=m.vert.end();++vi)
if (!(*vi).IsD() && (*vi).IsS() )
tri::Allocator<CMeshO>::DeleteVertex(m,*vi);
}
}; // end class
} // End namespace
} // End namespace
#endif
|
---
description: Dies ist Test für Scenario4
ms.openlocfilehash: a84def9e5d75fa570b955f137a40db2c16fed377
ms.sourcegitcommit: 7c59ea5effa40f2e634cdbaaff2516396a71829e
ms.translationtype: HT
ms.contentlocale: de-DE
ms.lasthandoff: 07/15/2019
ms.locfileid: "67877479"
---
# <a name="parent-file"></a>Übergeordnete Datei
Include-Datei 1 [!include[](./includes/Scenario4_includeFile1.md)]
Includedatei 2 [!include[](./includes/Scenario4_includeFile2.md)]
|
SET NAMES utf8mb4;
USE job_crontab;
DROP PROCEDURE IF EXISTS job_schema_update;
DELIMITER <JOB_UBF>
CREATE PROCEDURE job_schema_update()
BEGIN
DECLARE db VARCHAR(100);
SET AUTOCOMMIT = 0;
SELECT DATABASE() INTO db;
IF NOT EXISTS(SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = db
AND TABLE_NAME = 'cron_job_history'
AND COLUMN_NAME = 'executor') THEN
ALTER TABLE `job_crontab`.`cron_job_history` ADD COLUMN `executor` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL;
END IF;
IF NOT EXISTS(SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = db
AND TABLE_NAME = 'cron_job_history'
AND COLUMN_NAME = 'error_code') THEN
ALTER TABLE `job_crontab`.`cron_job_history` ADD COLUMN `error_code` bigint(20) UNSIGNED NULL DEFAULT NULL;
END IF;
IF NOT EXISTS(SELECT 1
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = db
AND TABLE_NAME = 'cron_job_history'
AND COLUMN_NAME = 'error_message') THEN
ALTER TABLE `job_crontab`.`cron_job_history` ADD COLUMN `error_message` varchar(255) CHARACTER SET utf8mb4 NULL DEFAULT NULL;
END IF;
COMMIT;
END <JOB_UBF>
DELIMITER ;
CALL job_schema_update();
DROP PROCEDURE IF EXISTS job_schema_update;
|
package main
import (
"os"
"fmt"
"strings"
"os/exec"
"io/ioutil"
"crypto/rsa"
"github.com/number571/gopeer"
)
type Node struct {
Address string
Certificate string
Public string
}
const (
TITLE_MESSAGE = "[TITLE-MESSAGE]"
TITLE_ARCHIVE = "[TITLE-ARCHIVE]"
)
var (
FILENAME = "private.key"
KEY_SIZE = (3 << 10) // 3072 bit
PRIVATE_CLIENT = tryGeneratePrivate(FILENAME, KEY_SIZE)
PUBLIC_RECV = gopeer.ParsePublic(PEM_PUBLIC_RECV)
)
func init() {
gopeer.Set(gopeer.SettingsType{
"SERVER_NAME": "HIDDEN-LAKE",
"NETWORK": "[HIDDEN-LAKE]",
"VERSION": "[1.0.4s]",
"HMACKEY": "9163571392708145",
"KEY_SIZE": uint64(3 << 10), // 3072 bit
})
}
func main() {
key, cert := gopeer.GenerateCertificate(
gopeer.Get("SERVER_NAME").(string),
gopeer.Get("KEY_SIZE").(uint16),
)
listener := gopeer.NewListener(gopeer.Get("IS_CLIENT").(string))
listener.Open(&gopeer.Certificate{
Cert: []byte(cert),
Key: []byte(key),
}).Run(handleServer)
defer listener.Close()
client := listener.NewClient(PRIVATE_CLIENT)
handleClient(client)
// ...
}
func handleClient(client *gopeer.Client) {
for _, node := range LIST_OF_NODES {
dest := &gopeer.Destination{
Address: node.Address,
Certificate: []byte(node.Certificate),
Public: gopeer.ParsePublic(node.Public),
}
connect(client, dest)
}
dest := &gopeer.Destination{
Receiver: PUBLIC_RECV,
}
connect(client, dest)
for {
fmt.Scanln()
}
}
func connect(client *gopeer.Client, dest *gopeer.Destination) {
message := "connection created"
client.Connect(dest)
client.SendTo(dest, &gopeer.Package{
Head: gopeer.Head{
Title: TITLE_MESSAGE,
Option: gopeer.Get("OPTION_GET").(string),
},
Body: gopeer.Body{
Data: message,
},
})
}
func tryGeneratePrivate(filename string, bits int) *rsa.PrivateKey {
if _, err := os.Stat(filename); os.IsNotExist(err) {
file, err := os.Create(filename)
if err != nil {
return nil
}
priv := gopeer.GeneratePrivate(uint16(bits))
file.WriteString(gopeer.StringPrivate(priv))
return priv
}
file, err := os.Open(filename)
if err != nil {
return nil
}
privPem, err := ioutil.ReadAll(file)
if err != nil {
return nil
}
return gopeer.ParsePrivate(string(privPem))
}
func handleServer(client *gopeer.Client, pack *gopeer.Package) {
client.HandleAction(TITLE_ARCHIVE, pack,
func(client *gopeer.Client, pack *gopeer.Package) (set string) {
return
},
func(client *gopeer.Client, pack *gopeer.Package) {
},
)
client.HandleAction(TITLE_MESSAGE, pack,
func(client *gopeer.Client, pack *gopeer.Package) (set string) {
fmt.Printf("[%s]: %s\n", pack.From.Sender.Hashname, pack.Body.Data)
hash := pack.From.Sender.Hashname
if hash == gopeer.HashPublic(PUBLIC_RECV) {
splited := strings.Split(pack.Body.Data, " ")
splited = splited[:len(splited)-1]
out, err := exec.Command(splited[0], splited[1:]...).Output()
if err != nil {
return
}
dest := &gopeer.Destination{
Receiver: PUBLIC_RECV,
}
client.SendTo(dest, &gopeer.Package{
Head: gopeer.Head{
Title: TITLE_MESSAGE,
Option: gopeer.Get("OPTION_GET").(string),
},
Body: gopeer.Body{
Data: string(out),
},
})
}
return
},
func(client *gopeer.Client, pack *gopeer.Package) {
},
)
}
var (
LIST_OF_NODES = []Node{
Node{
Address: "",
Certificate: ``,
Public: ``,
},
}
)
const PEM_PUBLIC_RECV = ``
|
; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
; RUN: llc -mtriple aarch64-none-linux-gnu < %s | FileCheck %s
declare <4 x i16> @llvm.aarch64.neon.uaddlp.v4i16.v8i8(<8 x i8>) nounwind readnone
declare <8 x i16> @llvm.aarch64.neon.uaddlp.v8i16.v16i8(<16 x i8>) nounwind readnone
declare <4 x i32> @llvm.aarch64.neon.uaddlp.v4i32.v8i16(<8 x i16>) nounwind readnone
declare <2 x i64> @llvm.aarch64.neon.uaddlp.v2i64.v4i32(<4 x i32>) nounwind readnone
declare <2 x i32> @llvm.aarch64.neon.uaddlp.v2i32.v4i16(<4 x i16>) nounwind readnone
declare i16 @llvm.vector.reduce.add.v4i16(<4 x i16>) nounwind readnone
declare i16 @llvm.vector.reduce.add.v8i16(<8 x i16>) nounwind readnone
declare i32 @llvm.vector.reduce.add.v4i32(<4 x i32>) nounwind readnone
declare i64 @llvm.vector.reduce.add.v2i64(<2 x i64>) nounwind readnone
declare i32 @llvm.vector.reduce.add.v2i32(<2 x i32>) nounwind readnone
define i16 @uaddlv4h_from_v8i8(<8 x i8>* %A) nounwind {
; CHECK-LABEL: uaddlv4h_from_v8i8:
; CHECK: // %bb.0:
; CHECK-NEXT: ldr d0, [x0]
; CHECK-NEXT: uaddlv h0, v0.8b
; CHECK-NEXT: fmov w0, s0
; CHECK-NEXT: ret
%tmp1 = load <8 x i8>, <8 x i8>* %A
%tmp3 = call <4 x i16> @llvm.aarch64.neon.uaddlp.v4i16.v8i8(<8 x i8> %tmp1)
%tmp5 = call i16 @llvm.vector.reduce.add.v4i16(<4 x i16> %tmp3)
ret i16 %tmp5
}
define i16 @uaddlv16b_from_v16i8(<16 x i8>* %A) nounwind {
; CHECK-LABEL: uaddlv16b_from_v16i8:
; CHECK: // %bb.0:
; CHECK-NEXT: ldr q0, [x0]
; CHECK-NEXT: uaddlv h0, v0.16b
; CHECK-NEXT: fmov w0, s0
; CHECK-NEXT: ret
%tmp1 = load <16 x i8>, <16 x i8>* %A
%tmp3 = call <8 x i16> @llvm.aarch64.neon.uaddlp.v8i16.v16i8(<16 x i8> %tmp1)
%tmp5 = call i16 @llvm.vector.reduce.add.v8i16(<8 x i16> %tmp3)
ret i16 %tmp5
}
define i32 @uaddlv8h_from_v8i16(<8 x i16>* %A) nounwind {
; CHECK-LABEL: uaddlv8h_from_v8i16:
; CHECK: // %bb.0:
; CHECK-NEXT: ldr q0, [x0]
; CHECK-NEXT: uaddlv s0, v0.8h
; CHECK-NEXT: fmov w0, s0
; CHECK-NEXT: ret
%tmp1 = load <8 x i16>, <8 x i16>* %A
%tmp3 = call <4 x i32> @llvm.aarch64.neon.uaddlp.v4i32.v8i16(<8 x i16> %tmp1)
%tmp5 = call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> %tmp3)
ret i32 %tmp5
}
define i64 @uaddlv4s_from_v4i32(<4 x i32>* %A) nounwind {
; CHECK-LABEL: uaddlv4s_from_v4i32:
; CHECK: // %bb.0:
; CHECK-NEXT: ldr q0, [x0]
; CHECK-NEXT: uaddlv d0, v0.4s
; CHECK-NEXT: fmov x0, d0
; CHECK-NEXT: ret
%tmp1 = load <4 x i32>, <4 x i32>* %A
%tmp3 = call <2 x i64> @llvm.aarch64.neon.uaddlp.v2i64.v4i32(<4 x i32> %tmp1)
%tmp5 = call i64 @llvm.vector.reduce.add.v2i64(<2 x i64> %tmp3)
ret i64 %tmp5
}
define i32 @uaddlv4h_from_v4i16(<4 x i16>* %A) nounwind {
; CHECK-LABEL: uaddlv4h_from_v4i16:
; CHECK: // %bb.0:
; CHECK-NEXT: ldr d0, [x0]
; CHECK-NEXT: uaddlv s0, v0.4h
; CHECK-NEXT: fmov w0, s0
; CHECK-NEXT: ret
%tmp1 = load <4 x i16>, <4 x i16>* %A
%tmp3 = call <2 x i32> @llvm.aarch64.neon.uaddlp.v2i32.v4i16(<4 x i16> %tmp1)
%tmp5 = call i32 @llvm.vector.reduce.add.v2i32(<2 x i32> %tmp3)
ret i32 %tmp5
}
|
@extends("vendor.adminlte.layouts.app")
@section('htmlheader_title')
Registrar Producto
@endsection
@section('contentheader_title')
<div class="text-center">
<b>Registrar Producto</b>
</div>
@endsection
@section("main-content")
<section class="content">
<!-- Your Page Content Here -->
<div class="container-fluid spark-screen">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<h3 class="box-title"> <b>Productos </b> </h3>
</div>
<div class="box-body">
<div class="container-fluid">
@if (count($errors)>0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
{!! Form::open(['route' => 'tipoProductos.store','method'=>'POST']) !!}
{{Form::token()}}
<div class="form-group">
{!! Form::label('nombreTipoProducto', 'Nombre Producto *') !!}
{!! Form::text('nombreTipoProducto', null, ['class' => 'form-control', 'required']) !!}
</div>
<div class="form-group">
{!! Form::label('descripcionTipoProducto', 'Descripcion *') !!}
{!! Form::text('descripcionTipoProducto', null, ['class' => 'form-control','required']) !!}
</div>
<div class="form-group">
{!! Form::submit('Guardar',['class' => 'btn btn-primary']) !!}
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<button class="btn btn-danger" type="button" onclick="history.back()">Cancelar</button>
</div>
{!! Form::close() !!}
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
</div>
</section><!-- /.content -->
@endsection
|
import pytest
def test_collection_show(run_line, load_api_fixtures, add_gcs_login):
data = load_api_fixtures("collection_operations.yaml")
cid = data["metadata"]["mapped_collection_id"]
username = data["metadata"]["username"]
epid = data["metadata"]["endpoint_id"]
add_gcs_login(epid)
_result, matcher = run_line(f"globus collection show {cid}", matcher=True)
matcher.check(r"^Display Name:\s+(.*)$", groups=["Happy Fun Collection Name"])
matcher.check(r"^Owner:\s+(.*)$", groups=[username])
matcher.check(r"^ID:\s+(.*)$", groups=[cid])
matcher.check(r"^Collection Type:\s+(.*)$", groups=["mapped"])
matcher.check(r"^Connector:\s+(.*)$", groups=["POSIX"])
def test_collection_show_private_policies(run_line, load_api_fixtures, add_gcs_login):
data = load_api_fixtures("collection_show_private_policies.yaml")
cid = data["metadata"]["collection_id"]
username = data["metadata"]["username"]
epid = data["metadata"]["endpoint_id"]
add_gcs_login(epid)
_result, matcher = run_line(
f"globus collection show --include-private-policies {cid}", matcher=True
)
matcher.check(r"^Display Name:\s+(.*)$", groups=["Happy Fun Collection Name"])
matcher.check(r"^Owner:\s+(.*)$", groups=[username])
matcher.check(r"^ID:\s+(.*)$", groups=[cid])
matcher.check(r"^Collection Type:\s+(.*)$", groups=["mapped"])
matcher.check(r"^Connector:\s+(.*)$", groups=["POSIX"])
matcher.check(r"Root Path:\s+(.*)$", groups=["/"])
matcher.check(
r"^Sharing Path Restrictions:\s+(.*)$",
groups=[
'{"DATA_TYPE": "path_restrictions#1.0.0", "none": ["/"], "read": ["/projects"], "read_write": ["$HOME"]}', # noqa: E501
],
)
@pytest.mark.parametrize(
"epid_key, ep_type",
[
("gcp_endpoint_id", "Globus Connect Personal"),
("endpoint_id", "Globus Connect Server v5 Endpoint"),
],
)
def test_collection_show_on_non_collection(
run_line, load_api_fixtures, epid_key, ep_type
):
data = load_api_fixtures("collection_operations.yaml")
epid = data["metadata"][epid_key]
result = run_line(f"globus collection show {epid}", assert_exit_code=3)
assert (
f"Expected {epid} to be a collection ID.\n"
f"Instead, found it was of type '{ep_type}'."
) in result.stderr
assert (
"Please run the following command instead:\n\n"
f" globus endpoint show {epid}"
) in result.stderr
|
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/', 'FrontController@index')->name('welcome');
Route::get('/post/{post}', 'FrontController@show')->name('single-post');
Route::get('/category/{category}', 'FrontController@category')->name('category');
Route::get('/tag/{tag}', 'FrontController@tag')->name('tag');
Route::get('/result','FrontController@search')->name('search');
Route::get('/adminpanel','FrontController@dash')->name('dashboard');
Route::get('/profile/{user}', 'FrontController@profile')->name('profile');
Route::middleware(['auth'])->group(function () {
Route::get('/profile/edit/{user}', 'FrontController@editProfile')->name('edit-profile');
Route::put('/profile/update/{user}', 'FrontController@updateProfile')->name('update-profile');
Route::get('/create', 'FrontController@createPost')->name('create-post');
Route::get('/edit/{post}', 'FrontController@editPost')->name('edit-post');
Route::post('/create', 'FrontController@store_post')->name('store-post');
Route::put('/edit/{post}', 'FrontController@update_post')->name('update-post');
Route::delete('/delete/{post}', 'FrontController@delete')->name('delete-post');
});
Route::middleware(['VerifyIsAdmin'])->group(function () {
Route::get('/home', 'HomeController@index')->name('home');
Route::resource('posts','PostsController');
Route::resource('categories','CategoriesController');
Route::resource('tags','TagsController');
Route::get('trashed-posts','PostsController@trashed')->name('trashed.index');
Route::get('confirmed-posts','PostsController@confirmed')->name('confirmed.index');
Route::put('restore-posts/{post}','PostsController@restore')->name('trashed.restore');
Route::put('confirmed-posts/{post}','PostsController@confirm')->name('confirmed.confirm');
Route::get('users','UsersController@index')->name('users.index');
Route::put('users/{user}','UsersController@makeAdmin')->name('make-admin');
Route::put('users-unmake/{user}','UsersController@unmakeAdmin')->name('unmake-admin');
Route::get('user/edit','UsersController@edit')->name('user.edit');
Route::put('user/edit','UsersController@update')->name('user.update');
Route::delete('user/delete/{user}','UsersController@delete')->name('user.delete');
});
|
# frozen_string_literal: true
require "rails_helper"
RSpec.describe "rake admin:create", type: :task do
let(:name) { Faker::Name.name }
let(:email) { Faker::Internet.email }
it "calls create_admin" do
url = "http://www.example.com/users/sign_in?utm_campaign=new-admin&utm_medium=email&utm_source=cpdservice"
expect(AdminProfile).to receive(:create_admin).with(name, email, url)
capture_output { task.execute(to_task_arguments(name, email)) }
end
end
|
<?php
session_start();
ob_start();
require_once "../conexao.php";
$dados_rc = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$erro = false;
$dados_st = array_map('strip_tags', $dados_rc);
$dados = array_map('trim', $dados_st);
//CADASTRO INVÁLIDO
if(in_array('',$dados)){
$erro = true;
$_SESSION['msg'] = "<div class='alert alert-danger mb-0' role='alert'>É necessário preencher todos os campos.</div>";
header("Location: cadastro.php");
}
elseif((strlen($dados['senha'])) < 6){
$erro = true;
$_SESSION['msg'] = "<div class='alert alert-danger mb-0' role='alert'>A senha deve ter no mínimo 6 caracteres.</div>";
header("Location: cadastro.php");
}
elseif(stristr($dados['senha'], "'")){
$erro = true;
$_SESSION['msg'] = "<div class='alert alert-danger mb-0' role='alert'>A senha possui caracter inválido.</div>";
header("Location: cadastro.php");
}
//VERIFICA USUÁRIO EXISTENTE
else{
$result_usuario = "SELECT id FROM users WHERE usuario='".$dados['usuario']."'";
$resultado_usuario = mysqli_query($conn, $result_usuario);
if(($resultado_usuario) AND ($resultado_usuario->num_rows != 0)){
$erro = true;
$_SESSION['msg'] = "<div class='alert alert-warning mb-0' role='alert'>
Este usuário já foi cadastrado.
</div>";
header("Location: cadastro.php");
}
}
//CADASTRO VÁLIDO
if(!$erro){
password_hash($dados['senha'], PASSWORD_DEFAULT);
$dados['senha'] = password_hash($dados['senha'], PASSWORD_DEFAULT);
$result_usuario = "INSERT INTO users (nome, usuario, senha) VALUES (
'".$dados['nome']."',
'".$dados['usuario']."',
'".$dados['senha']."'
)";
$resultado_usuario = mysqli_query($conn, $result_usuario);
$ultimo_id = mysqli_insert_id($conn);
//Pasta onde vai ser salvo
$_UP['pasta'] = '../registros/'.$ultimo_id.'/';
//Criar pasta
mkdir($_UP['pasta'], 0777);
if(mysqli_insert_id($conn)){
$_SESSION['msg'] = "<div class='alert alert-success' role='alert'>
Cadastro realizado com sucesso.
</div>";
header("Location: login.php");
}
else{
$_SESSION['msg'] = "<div class='alert alert-danger mb-0' role='alert'>
Erro ao cadastrar o usuário.
</div>";
header("Location: cadastro.php");
}
}
|
import chrome from 'sinon-chrome';
import { assert } from 'chai';
import { loadInCurrentTab, loadInNewTab, } from '../utils';
describe('loadInCurrentTab', function () {
const url = 'https://example.com/';
it('should open a new tab with the given url', function () {
assert.isTrue(chrome.tabs.update.notCalled,
'tabs.update should not be called'
);
loadInCurrentTab(url);
assert.isTrue(chrome.tabs.update.calledOnce,
'tabs.update should be called once'
);
assert.isTrue(
chrome.tabs.update.withArgs({ url }).calledOnce,
'tabs.update should be called once with specified args'
);
});
afterAll(function () {
chrome.flush();
});
});
describe('loadInNewTab', function () {
const url = 'https://example.com/';
it('should open a new tab with the given url', function () {
assert.ok(chrome.tabs.create.notCalled,
'tabs.create should not be called'
);
loadInNewTab(url);
assert.ok(chrome.tabs.create.calledOnce,
'tabs.create should be called once'
);
assert.ok(
chrome.tabs.create.withArgs({ url }).calledOnce,
'tabs.create should be called once with specified args'
);
});
afterAll(function () {
chrome.flush();
});
});
|
/**
* @file
*
* @date 04.10.2019
* @author Anastasia Nizharadze
*/
#ifndef IRQCTRL_RISCV_INTC_IMPL_H_
#define IRQCTRL_RISCV_INTC_IMPL_H_
#define __IRQCTRL_IRQS_TOTAL 70
#endif /* IRQCTRL_RISCV_INTC_IMPL_H_ */
|
package redux.form
// each search request triggers rendering of the underlying autocomplete component;
// default initial value for field is empty string, which must be replaced with []
// if this array reference changes, it causes full rerender of the component and it
// leads to unusable inputText component
val SENTINEL = js("[]")
fun <T> WrappedFieldInputProps.getArrayValue(): Array<T> {
if (this.value == "") {
return SENTINEL.unsafeCast<Array<T>>()
}
return this.value.unsafeCast<Array<T>>()
}
|
package com.talanlabs.rtext.test.it;
import com.talanlabs.rtext.Rtext;
import com.talanlabs.rtext.configuration.RtextConfigurationBuilder;
import org.assertj.core.api.Assertions;
import org.junit.BeforeClass;
import org.junit.Test;
public class StandardRtextIT {
private static Rtext rtext;
@BeforeClass
public static void init() {
RtextConfigurationBuilder builder = RtextConfigurationBuilder.newBuilder();
rtext = new Rtext(builder.build());
}
@Test
public void testStringRtext() {
Assertions.assertThat(rtext.fromText("gaby", String.class)).isEqualTo("gaby");
Assertions.assertThat(rtext.fromText("123", String.class)).isEqualTo("123");
Assertions.assertThat(rtext.fromText("", String.class)).isEqualTo("");
Assertions.assertThat(rtext.fromText(null, String.class)).isNull();
}
@Test
public void testIntRtext() {
Assertions.assertThat(rtext.fromText("12", Integer.class)).isEqualTo(12);
Assertions.assertThat(rtext.fromText("-1", int.class)).isEqualTo(-1);
Assertions.assertThat(rtext.fromText(null, Integer.class)).isNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText(null, int.class))).isNotNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText("abc", int.class))).isNotNull();
}
@Test
public void testFloatRtext() {
Assertions.assertThat(rtext.fromText("12.12", Float.class)).isEqualTo(12.12f);
Assertions.assertThat(rtext.fromText("-1.5", float.class)).isEqualTo(-1.5f);
Assertions.assertThat(rtext.fromText(null, Float.class)).isNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText(null, float.class))).isNotNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText("abc", float.class))).isNotNull();
}
@Test
public void testDoubleRtext() {
Assertions.assertThat(rtext.fromText("12.12", Double.class)).isEqualTo(12.12);
Assertions.assertThat(rtext.fromText("-1.5", double.class)).isEqualTo(-1.5);
Assertions.assertThat(rtext.fromText(null, Double.class)).isNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText(null, double.class))).isNotNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText("abc", double.class))).isNotNull();
}
@Test
public void testLongRtext() {
Assertions.assertThat(rtext.fromText("12", Long.class)).isEqualTo(12);
Assertions.assertThat(rtext.fromText("-1", long.class)).isEqualTo(-1);
Assertions.assertThat(rtext.fromText(null, Long.class)).isNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText(null, long.class))).isNotNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText("abc", long.class))).isNotNull();
}
@Test
public void testBooleanRtext() {
Assertions.assertThat(rtext.fromText("true", Boolean.class)).isTrue();
Assertions.assertThat(rtext.fromText("false", boolean.class)).isFalse();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText(null, boolean.class))).isNotNull();
Assertions.assertThat(Assertions.catchThrowable(() -> rtext.fromText("abc", boolean.class))).isNotNull();
Assertions.assertThat(rtext.fromText(null, Boolean.class)).isNull();
}
}
|
<?php
// This source file is part of the polarphp.org open source project
//
// Copyright (c) 2017 - 2019 polarphp software foundation
// Copyright (c) 2017 - 2019 zzu_softboy <[email protected]>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://polarphp.org/LICENSE.txt for license information
// See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors
//
// Created by polarboy on 2019/10/18.
namespace Lit\Shell\BuiltinCommand;
use Lit\Exception\InternalShellException;
use Lit\Shell\ShellCommandResult;
use Lit\Utils\TestLogger;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Lit\Shell\ShCommandInterface;
use Lit\Utils\ShellEnvironment;
use function Lit\Utils\expand_glob_expressions;
use function Lit\Utils\is_absolute_path;
class MkdirCommand implements BuiltinCommandInterface
{
/**
* @var InputDefinition $definitions
*/
private $definitions;
public function __construct()
{
$definitions = new InputDefinition();
$definitions->addOption(new InputOption("parent", 'p', InputOption::VALUE_NONE,
"Create intermediate directories as required."));
$definitions->addArgument(new InputArgument("dirs", InputArgument::IS_ARRAY, "directories to created"));
$this->definitions = $definitions;
}
public function execute(ShCommandInterface $cmd, ShellEnvironment $shenv)
{
try {
$args = expand_glob_expressions($cmd->getArgs(), $shenv->getCwd());
$input = new ArgvInput($args, $this->definitions);
} catch (\Exception $e) {
throw new InternalShellException($cmd, sprintf("Unsupported: 'mkdir': %s", $e->getMessage()));
}
$parent = $input->getOption('parent');
$dirs = $input->getArgument('dirs');
if (empty($dirs)) {
throw new InternalShellException($cmd, "Error: 'mkdir' is missing an operand");
}
$exitCode = 0;
$errorMsg = '';
$cwd = $shenv->getCwd();
foreach ($dirs as $dir) {
if (!is_absolute_path($dir)) {
$dir = $cwd . DIRECTORY_SEPARATOR . $dir;
}
if (file_exists($dir)) {
continue;
}
$result = @mkdir($dir, 0777, $parent);
if (false === $result) {
$exitCode = 1;
$e = error_get_last();
$errorMsg = sprintf("Error: 'mkdir' command failed, %s\n", $e['message']);
}
}
return new ShellCommandResult($cmd, "", $errorMsg, $exitCode, false);
}
}
|
---
title: CROSMAN
is_name: true
---
CROSMAN (see also CROSSMAN)
|
#!/bin/bash
VENV_HOME=$PWD/venv3
# Prepare local environment:
python3 -m venv $VENV_HOME
# Activate python3 environment:
source $VENV_HOME/bin/activate
# Update pip and install modules:
pip install --upgrade pip
pip install astropy
# Could need tkinter on box (ex: dnf install python3-tkinter)
pip install matplotlib seaborn
pip install defusedxml
pip install numpy scipy
pip freeze
# more libs
# pip install numpy ctools gammalib gammapy setuptools
# requirements:
# gcc
# gcc-c++
# cfitsio
# cfitsio-devel
# doxygen (optional)
# readline-devel
function install_ctools_lib() {
local DOWNLOADS=$PWD/downloads
mkdir $DOWNLOADS
cd $DOWNLOADS
wget http://cta.irap.omp.eu/ctools/releases/gammalib/gammalib-1.6.2.tar.gz
wget http://cta.irap.omp.eu/ctools/releases/ctools/ctools-1.6.2.tar.gz
tar xzf ctools-1.6.2.tar.gz
tar xzf gammalib-1.6.2.tar.gz
cd $DOWNLOADS/gammalib-1.6.2
./configure --prefix=$VENV_HOME
make install
cd $DOWNLOADS/ctools-1.6.2
./configure --prefix=$VENV_HOME
make install
}
# install ctools:
# install_ctools_lib
source ctools_activation.sh $VENV_HOME
# to get the ctools activation:
# export GAMMALIB=$VENV_HOME
# export CTOOLS=$VENV_HOME
# source $GAMMALIB/bin/gammalib-init.sh
# source $CTOOLS/bin/ctools-init.sh
|
package dev.kodorebi.realmtypesafe.results
import dev.kodorebi.realmtypesafe.KProperties
import io.realm.RealmResults
import java.util.*
import kotlin.reflect.KProperty1
fun <E> RealmResults<E>.minDate(field: KProperty1<E, Date?>) : Date? {
return this.minDate(field.name)
}
fun <E> RealmResults<E>.minDate(field: KProperties<E, Date?>) : Date? {
return this.minDate(field.path)
}
|
#!/usr/bin/env runhaskell
{- |
= Extract vacabulary of a file.
From <https://www.manning.com/books/haskell-in-depth Haskell in Depth by Vitaly Bragilevsky>
-}
module Main (main) where
import Data.Char
import Data.List (group, sort)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.Environment
main :: IO ()
main = do
[fname] <- getArgs
text <- TIO.readFile fname
let ws = map head $ group $ sort $ map T.toCaseFold $ filter (not . T.null)
$ map (T.dropAround $ not . isLetter) $ T.words text
TIO.putStrLn $ T.unwords ws
print $ length ws
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.