text
stringlengths 27
775k
|
|---|
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/no-default-export */
import { Box } from "@chakra-ui/react";
export default function Button(props: any): JSX.Element {
return (
<Box
px={4}
py={2}
as="button"
transition="all 0.3s ease"
borderRadius="25px"
fontSize="16px"
fontWeight="semibold"
border="1px solid var(--chakra-colors-brand-primary)"
background="brand.transparent"
color="var(--chakra-colors-brand-primary)"
_hover={{
background: "brand.primary",
color: "white",
}}
_active={{
transform: "scale(0.90)",
boxShadow: "md",
}}
{...props}
boxShadow="lg"
>
{props.children}
</Box>
);
}
|
import React from "react";
import styles from "./styles.module.scss";
const TitleSection = ({titulo}:{titulo:string}) =>{
return(
<div className={styles.TitleSection}>
<h2>{titulo}</h2>
</div>
)
}
export default TitleSection;
|
import 'dart:math';
import 'dart:ui';
import 'QCalHolder.dart';
import 'QCalModel.dart';
class QCalculator {
// @override
static List<Week> generate(Date date) {
// DateTime start =DateTime.now();
DateTime firstDateInMon = DateTime(date.year, date.month, 1);
int offset2FirstWeekDay =
(firstDateInMon.weekday + DAYS_PERWEEK - firstDayInWeek) % DAYS_PERWEEK;
DateTime firstDate =
firstDateInMon.subtract(Duration(days: offset2FirstWeekDay));
List<Week> monthDate = [];
for (int weekIndex = 0; weekIndex < WEEK_IN_MONTH; weekIndex++) {
Week week = Week();
for (int dayIndex = 0; dayIndex < DAYS_PERWEEK; dayIndex++) {
week.add(
Date.from(firstDate.add(Duration(days: weekIndex * 7 + dayIndex))));
}
monthDate.add(week);
}
// print(
// "generateMonthDate: ${date}, ${firstDateInMon.weekday}, offset: ${offset2FirstWeekDay}, ${firstDate}");
// print(
// "generateMonthDate: ${date}, ${DateTime.now().difference(start).inMilliseconds} ms");
return monthDate;
}
static Date offsetMonthTo(Date baseDate, int offset) {
// int offsetYear = (offset + baseDate.month) ~/ MAX_MONTH;
// int offsetMonth = ((offset + baseDate.month + MAX_MONTH) % MAX_MONTH).toInt() + 1;
// int toYear = baseDate.year + offsetYear;
// int toMonth = offsetMonth;
// if (toMonth > MAX_MONTH+1) {
// toMonth -= MAX_MONTH +1;
// }
DateTime toMonthMaxDate =
DateTime(baseDate.year, baseDate.month + offset + 1, 1)
.subtract(Duration(days: 1));
// Date date = ;
// print(
// "\n\n ++++++++++offsetMonthTo:: ${offset}, ${baseDate} , ${toMonthMaxDate} => ${date}");
return Date.from(DateTime(baseDate.year, baseDate.month + offset,
min(toMonthMaxDate.day, baseDate.date)));
}
static Date offsetWeekTo(Date date, int offset) {
return Date.from(
date.toDateTime().add(Duration(days: offset * DAYS_PERWEEK)));
}
static Date calcFocusDateByOffset(
Offset offset, Size size, QCalHolder model, List<Week> weeks) {
int focusIndexOfWeek = -1;
for (int i = 0; i < WEEK_IN_MONTH; i++) {
Week week = weeks[i];
if (week.hasDate(model.focusDateTime)) {
focusIndexOfWeek = i;
break;
}
}
int indexDay = offset.dx ~/ (size.width / DAYS_PERWEEK);
int indexWeek = focusIndexOfWeek;
switch (model.mode) {
case Mode.WEEK:
break;
default:
indexWeek = offset.dy ~/ (size.height / WEEK_IN_MONTH);
}
return weeks[indexWeek].dates[indexDay];
}
static Date calcFocusDate(
Offset offset, Size size, QCalHolder model, List<Week> weeks) {
int focusIndexOfWeek = 0;
for (int i = 0; i < WEEK_IN_MONTH; i++) {
Week week = weeks[i];
if (week.hasDate(model.focusDateTime)) {
focusIndexOfWeek = i;
break;
}
}
int indexDay = offset.dx ~/ (size.width / DAYS_PERWEEK);
int indexWeek = focusIndexOfWeek;
switch (model.mode) {
case Mode.WEEK:
break;
default:
indexWeek = offset.dy ~/ (size.height / WEEK_IN_MONTH);
}
return weeks[indexWeek].dates[indexDay];
}
}
|
### **瓜瓜talk服务端**
cdn服务器
msg服务器
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<title>DevExtremeAspNetCoreApp</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" href="~/css/vendor.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/site.css" />
<script src="~/js/vendor.js" asp-append-version="true"></script>
</head>
<body>
<div id="app-side-nav-outer-toolbar">
<div class="layout-header">
@(Html.DevExtreme().Toolbar()
.Items(items => {
items.Add()
.Widget(w => w
.Button()
.Icon("menu")
.OnClick("DevExtremeAspNetCoreApp.onMenuButtonClick")
)
.Location(ToolbarItemLocation.Before)
.CssClass("menu-button");
items.Add()
.Html("<div>DevExtremeAspNetCoreApp</div>")
.Location(ToolbarItemLocation.Before)
.CssClass("header-title");
})
)
</div>
<div class="layout-body">
@(Html.DevExtreme().Drawer()
.ID("layout-drawer")
.Position(DrawerPosition.Left)
.Opened(new JS("DevExtremeAspNetCoreApp.restoreDrawerOpened()"))
.Content(@<text>
<div id="layout-drawer-scrollview" class="with-footer">
<div class="content">
@RenderBody()
</div>
<div class="content-block">
<div class="content-footer">
<div id="footer">
Copyright (c) 2000-2019 Developer Express Inc.
<br />
All trademarks or registered trademarks are property of their respective owners.
</div>
</div>
</div>
</div>
</text>)
.Template(new TemplateName("navigation-menu"))
)
</div>
</div>
@using(Html.DevExtreme().NamedTemplate("navigation-menu")) {
<div class="menu-container dx-swatch-additional">
@functions{
bool IsCurrentPage(string pageName) {
var pageUrl = Url.Page(pageName);
var currentPageUrl = Url.Page(ViewContext.RouteData.Values["page"].ToString());
return pageUrl == currentPageUrl;
}
}
@(Html.DevExtreme().TreeView()
.Items(items => {
items.Add()
.Text("Home")
.Icon("home")
.Option("path", Url.Page("Index"))
.Selected(IsCurrentPage("Index"));
items.Add()
.Text("About")
.Icon("info")
.Option("path", Url.Page("About"))
.Selected(IsCurrentPage("About"));
})
.ExpandEvent(TreeViewExpandEvent.Click)
.SelectionMode(NavSelectionMode.Single)
.SelectedExpr("selected")
.FocusStateEnabled(false)
.Width(250)
.OnItemClick("DevExtremeAspNetCoreApp.onTreeViewItemClick")
)
</div>
}
<script>
var DevExtremeAspNetCoreApp = (function() {
var DRAWER_OPENED_KEY = "DevExtremeAspNetCoreApp-drawer-opened";
var breakpoints = {
xSmallMedia: window.matchMedia("(max-width: 599.99px)"),
smallMedia: window.matchMedia("(min-width: 600px) and (max-width: 959.99px)"),
mediumMedia: window.matchMedia("(min-width: 960px) and (max-width: 1279.99px)"),
largeMedia: window.matchMedia("(min-width: 1280px)")
};
function getDrawer() {
return $("#layout-drawer").dxDrawer("instance");
}
function restoreDrawerOpened() {
var isLarge = breakpoints.largeMedia.matches;
if(!isLarge)
return false;
var state = sessionStorage.getItem(DRAWER_OPENED_KEY);
if(state === null)
return isLarge;
return state === "true";
}
function saveDrawerOpened() {
sessionStorage.setItem(DRAWER_OPENED_KEY, getDrawer().option("opened"));
}
function updateDrawer() {
var isXSmall = breakpoints.xSmallMedia.matches,
isLarge = breakpoints.largeMedia.matches;
getDrawer().option({
openedStateMode: isLarge ? "shrink" : "overlap",
revealMode: isXSmall ? "slide" : "expand",
minSize: isXSmall ? 0 : 60,
shading: !isLarge,
});
}
function init() {
$("#layout-drawer-scrollview").dxScrollView({ direction: "vertical" });
$.each(breakpoints, function(_, size) {
size.addListener(function(e) {
if(e.matches)
updateDrawer();
});
});
updateDrawer();
}
function navigate(url, delay) {
if(url)
setTimeout(function() { location.href = url }, delay);
}
function onMenuButtonClick() {
getDrawer().toggle();
saveDrawerOpened();
}
function onTreeViewItemClick(e) {
var drawer = getDrawer();
var savedOpened = restoreDrawerOpened();
var actualOpened = drawer.option("opened");
if(!actualOpened) {
drawer.show();
} else {
var willHide = !savedOpened || !breakpoints.largeMedia.matches;
var willNavigate = !e.itemData.selected;
if(willHide)
drawer.hide();
if(willNavigate)
navigate(e.itemData.path, willHide ? 400 : 0);
}
}
return {
init: init,
restoreDrawerOpened: restoreDrawerOpened,
onMenuButtonClick: onMenuButtonClick,
onTreeViewItemClick: onTreeViewItemClick
};
})();
document.addEventListener("DOMContentLoaded", function documentReady() {
this.removeEventListener("DOMContentLoaded", documentReady);
DevExtremeAspNetCoreApp.init();
});
</script>
</body>
</html>
|
module Main where
import Utilities
-- Input processing
type Input = [Int]
parse :: String -> Input
parse = map read . lines
-- Part One
solve1 :: Input -> Int
solve1 xs = head [product ns | (ns, _) <- choose 2 xs, sum ns == 2020]
tests1 :: [(String, Int)]
tests1 = [(testInput, 514579)]
testInput :: String
testInput = "\
\1721\n\
\979\n\
\366\n\
\299\n\
\675\n\
\1456\n"
-- Part Two
solve2 :: Input -> Int
solve2 xs = head [product ns | (ns, _) <- choose 3 xs, sum ns == 2020]
tests2 :: [(String, Int)]
tests2 = [(testInput, 241861950)]
main :: IO ()
main = do
s <- readFile "input/01.txt"
let input = parse s
putStr (unlines (failures "solve1" (solve1 . parse) tests1))
print (solve1 input)
putStr (unlines (failures "solve2" (solve2 . parse) tests2))
print (solve2 input)
|
class TopApps::Scraper
def self.scrape_index(index_url)
doc = Nokogiri::HTML(open(index_url))
free_apps_section = doc.css(".section.chart-grid.apps div.section-content").first
free_apps_list = free_apps_section.css("li")
free_apps_list.map do |app|
{
name: app.css("h3 a").text,
category: app.css("h4 a").text,
rank: app.css("strong").text.chomp("."),
profile_url: app.css("a").attribute("href").value
}
end
end
def self.scrape_profile(profile_url)
doc = Nokogiri::HTML(open(profile_url))
notes = doc.css("div.we-editor-notes.lockup.ember-view p").text.strip
notes == "" ? notes = "Unavailable." : nil
{
notes: notes,
developer: doc.css("h2.product-header__identity.app-header__identity a").text,
rating: doc.css("figcaption.we-rating-count.star-rating__count").text.split(",").first
}
end
end
|
<?php
use Faker\Generator as Faker;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB as DB;
class MessageParticipantsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(Faker $faker)
{
//Empty the message_participants table
// DB::table('message_participants')->delete();
$userIds = App\Models\User::all()->pluck('id')->toArray();
$messageSubjectIds = App\Models\MessageSubject::all()->pluck('id')->toArray();
if(count($messageSubjectIds) > 0 && count($userIds) > 0){
foreach ($messageSubjectIds as $messageSubject) {
foreach ($userIds as $user) {
$data = [
[
"user_id" => $user,
"message_subject_id" => $messageSubject,
"created_at" => strftime("%Y-%m-%d %H:%M:%S"),
"updated_at" => strftime("%Y-%m-%d %H:%M:%S")
]
];
DB::table("message_participants")->insert($data);
}
}
}
}
}
|
package excel_data_import.repository.implementation;
import javax.persistence.EntityManager;
import excel_data_import.domain.Match;
import excel_data_import.repository.MatchRepository;
public class MatchRepositoryImpl implements MatchRepository {
@Override
public void persist(Match match) {
try {
EntityManager entityManager = HaurRankingDatabaseUtils.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(match);
entityManager.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package crypto
import (
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"fmt"
"hash"
"io"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
var (
DigestAlgorithmSHA1 Algorithm = algorithmSHAImpl{"sha1"}
DigestAlgorithmSHA256 Algorithm = algorithmSHAImpl{"sha256"}
DigestAlgorithmSHA512 Algorithm = algorithmSHAImpl{"sha512"}
)
type algorithmSHAImpl struct {
name string
}
func (a algorithmSHAImpl) Name() string { return a.name }
func (a algorithmSHAImpl) CreateDigest(reader io.Reader) (Digest, error) {
hash := a.hashFunc()
_, err := io.Copy(hash, reader)
if err != nil {
return nil, bosherr.WrapError(err, "Copying file for digest calculation")
}
return NewDigest(a, fmt.Sprintf("%x", hash.Sum(nil))), nil
}
func (a algorithmSHAImpl) hashFunc() hash.Hash {
switch a.name {
case "sha1":
return sha1.New()
case "sha256":
return sha256.New()
case "sha512":
return sha512.New()
default:
panic("Internal inconsistency")
}
}
type unknownAlgorithmImpl struct {
name string
}
func NewUnknownAlgorithm(name string) unknownAlgorithmImpl {
return unknownAlgorithmImpl{name: name}
}
func (c unknownAlgorithmImpl) Name() string { return c.name }
func (c unknownAlgorithmImpl) CreateDigest(reader io.Reader) (Digest, error) {
return nil, bosherr.Errorf("Unable to create digest of unknown algorithm '%s'", c.name)
}
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class admin_producto_detalle_controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('admin_producto_detalle_model');
}
public function index()
{
$data= array (
'title' => 'CRUD || ProductosDetalles');
$this->load->view('template/admin_header',$data);
$this->load->view('template/admin_navbar');
$this->load->view('admin_producto_detalle_view');
$this->load->view('template/admin_footer');
}
//Funciones mostrar
public function get_producto_detalle(){
$respuesta= $this->admin_producto_detalle_model->get_producto_detalle();
echo json_encode($respuesta);
}
public function get_producto(){
$id = $this->input->post('id');
$respuesta = $this->admin_producto_detalle_model->get_producto($id);
echo json_encode($respuesta);
}
public function get_talla(){
$respuesta = $this->admin_producto_detalle_model->get_talla();
echo json_encode($respuesta);
}
public function get_color(){
$respuesta = $this->admin_producto_detalle_model->get_color();
echo json_encode($respuesta);
}
public function get_categoria(){
$id = $this->input->post('id');
$respuesta = $this->admin_producto_detalle_model->get_categoria();
echo json_encode($respuesta);
}
//Funcion buscar en tabla
public function buscar()
{
$palabra = $this->input->post('palabra');
$respuesta = $this->admin_producto_detalle_model->buscar_palabra($palabra);
echo json_encode($respuesta);
}
//FUNCION ELIMINAR
public function eliminar(){
$id = $this->input->post('id');
$respuesta = $this->admin_producto_detalle_model->eliminar($id);
echo json_encode($respuesta);
}
//FUNCION INGRESAR
public function ingresar(){
$registro = $this->input->post('registro');
if ($registro!=0) {
$exist = $this->input->post('exist');
$datos['producto'] = $this->input->post('producto');
$datos['talla'] = $this->input->post('talla');
$datos['color'] = $this->input->post('color');
$cantidadInput= $this->input->post('cantidad');
$cantidadSum=$exist +$cantidadInput;
$datos['cantidad'] = $cantidadSum;
$respuesta = $this->admin_producto_detalle_model->set_cantidad($datos);
echo json_encode($respuesta);
}else{
$datos['producto'] = $this->input->post('producto');
$datos['talla'] = $this->input->post('talla');
$datos['color'] = $this->input->post('color');
$datos['cantidad'] = $this->input->post('cantidad');
$respuesta = $this->admin_producto_detalle_model->set_detalle($datos);
echo json_encode($respuesta);
}
}
//FUNCIONES CONSULTAS
public function existencia(){
$producto = $this->input->post('producto');
$talla = $this->input->post('talla');
$color = $this->input->post('color');
$respuesta = $this->admin_producto_detalle_model->existencia($producto,$talla,$color);
echo json_encode($respuesta);
}
//FUNCIONES ACTUALIZAR
public function get_datos(){
$id = $this->input->post('id');
$respuesta = $this->admin_producto_detalle_model->get_datos($id);
echo json_encode($respuesta);
}
public function actualizar(){
$datos['id'] = $this->input->post('id_producto_detalle');
$datos['cantidad'] = $this->input->post('cantidad');
$respuesta = $this->admin_producto_detalle_model->actualizar($datos);
echo json_encode($respuesta);
}
/*public function get_imagen()
{
$id = $this->input->post('id');
$respuesta= $this->admin_categoria_model->get_imagen($id);
echo json_encode($respuesta);
}*/
}
?>
|
import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class CrudServiceService {
httpOptions = {
'responseType': 'xml' as 'json'
};
constructor(private http: HttpClient) { }
country: string;
state: string;
regNum: string;
getdata(country:string, state:string, regNumber:string): Promise<any> {
return new Promise((resolve, reject) => {
var func, url;
switch (country) {
case "GBR":
func = "Check";
break;
case "AUS":
func = "CheckAustralia";
break;
case "DNK":
func = "CheckDenmark";
break;
case "EST":
func = "CheckEstonia";
break;
case "FIN":
func = "CheckFinland";
break;
case "FRA":
func = "CheckFrance";
break;
case "HUN":
func = "CheckHungary";
break;
case "IND":
func = "CheckIndia";
break;
case "IRL":
func = "CheckIreland";
break;
case "ITA":
func = "CheckItaly";
break;
case "NLD":
func = "CheckNetherlands ";
break;
case "NZL":
func = "CheckNewZealand ";
break;
case "NOR":
func = "CheckNorway ";
break;
case "PRT":
func = "CheckPortugal ";
break;
case "RUS":
func = "CheckRussia ";
break;
case "SVK":
func = "CheckSlovakia ";
break;
case "ZAF":
func = "CheckSouthAfrica ";
break;
case "ESP":
func = "CheckSpain ";
break;
case "LKA":
func = "CheckSriLanka ";
break;
case "SWE":
func = "CheckSweden ";
break;
case "ARE":
func = "CheckUAE ";
break;
case "USA":
func = "CheckUSA";
break;
}
url = "http://regcheck.org.uk/api/reg.asmx/" + func + "?RegistrationNumber=" + regNumber + "&username=dananos"
// "http://regcheck.org.uk/api/reg.asmx/Check?RegistrationNumber=YYO7XHH&username=dananos"
this.http
.get(url, this.httpOptions)
.subscribe(
json => {
resolve(json);
},
error => {
reject(error);
}
);
});
// });
}
setdata(country, state, regNum) {
this.country = country;
this.state = state;
this.regNum = regNum;
}
getinfo() {
return { country: this.country, state: this.state, regNum: this.regNum };
}
}
|
exports.update_value_id = function(id, value) {
document.getElementById(id).value = value;
}
exports.append_value_id = function(id, value) {
document.getElementById(id).value += value;
}
exports.update_view_id = function(id, value) {
document.getElementById(id).innerText = value;
}
exports.update_background_id = function (id, color) {
document.getElementById(id).style.background = color;
}
|
# Get-VstsAssemblyReference
[table of contents](../Commands.md#toc) | [brief](../Commands.md#get-vstsassemblyreference)
```
NAME
Get-VstsAssemblyReference
SYNOPSIS
Gets assembly reference information.
SYNTAX
Get-VstsAssemblyReference [-LiteralPath] <String> [<CommonParameters>]
DESCRIPTION
Not supported for use during task execution. This function is only intended to help developers resolve
the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client
SDK. The interface and output may change between patch releases of the VSTS Task SDK.
Only a subset of the referenced assemblies may actually be required, depending on the functionality used
by your task. It is best to bundle only the DLLs required for your scenario.
Walks an assembly's references to determine all of it's dependencies. Also walks the references of the
dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for
in the directory of the specified assembly. NET Framework assemblies are omitted.
See https://github.com/Microsoft/azure-pipelines-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage
when working with the TFS extended client SDK from a task.
PARAMETERS
-LiteralPath <String>
Assembly to walk.
Required? true
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
<CommonParameters>
This cmdlet supports the common parameters: Verbose, Debug,
ErrorAction, ErrorVariable, WarningAction, WarningVariable,
OutBuffer, PipelineVariable, and OutVariable. For more information, see
about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216).
-------------------------- EXAMPLE 1 --------------------------
PS C:\>Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\
net45\Microsoft.TeamFoundation.Build2.WebApi.dll
```
|
class Events {
private _callbacks = {};
public bind(name, callback, context?) {
if (!this._callbacks[name]) {
this._callbacks[name] = [];
}
// this._callbacks[name].push({'cb':callback, context:context});
this._callbacks[name].push(callback);
}
public unbind(name,callback) {
for (var i = 0; i < this._callbacks[name]; i++) {
if(this._callbacks[name][i] == callback) {
this._callbacks[name].splice(i,1);
return;
}
}
}
public emit(name, args?: any) {
if(this._callbacks[name]) {
for (var i = 0; i < this._callbacks[name].length; i++) {
this._callbacks[name][i](args);
}
}
}
}
|
package com.spike.text.lucene.indexing.analysis;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.junit.Test;
import com.spike.text.lucene.util.LuceneAppAnalyzerUtil;
import com.spike.text.lucene.util.LuceneAppUtil;
import com.spike.text.lucene.util.SearchingMemIndexTestBase;
import com.spike.text.lucene.util.anno.BookPartEnum;
import com.spike.text.lucene.util.anno.LuceneInAction2ndBook;
@LuceneInAction2ndBook(part = BookPartEnum.CORE_LUCENE, chapter = 4, section = { 7 })
public class SearchUnAnalyzedFiledTest extends SearchingMemIndexTestBase {
private static final String fld_partnum = "partnum";
private static final String fldValue_partnum = "Q36";
private static final String fld_description = "description";
private static final String fldValue_description = "Illidium Space Modulator";
/**
* @throws IOException
* @throws ParseException
* @see SimpleAnalyzer
* @see QueryParser
* @see PerFieldAnalyzerWrapper
* @see KeywordAnalyzer
*/
@Test
public void searchUnanalyzedField() throws IOException, ParseException {
LuceneAppAnalyzerUtil.renderTokensWithFullDetails(new SimpleAnalyzer(), fldValue_partnum);
LuceneAppAnalyzerUtil.renderTokensWithFullDetails(new SimpleAnalyzer(), fldValue_description);
IndexSearcher indexSearcher = this.getIndexSearcher();
Query query = new TermQuery(new Term(fld_partnum, fldValue_partnum));
TopDocs topDocs = indexSearcher.search(query, 10);
assertEquals(1, topDocs.totalHits);
LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_partnum);
query =
new QueryParser(fld_description, new SimpleAnalyzer())
.parse(fld_partnum + ":Q36 AND SPACE");
assertEquals("+partnum:q +description:space", query.toString());
topDocs = indexSearcher.search(query, 10);
assertEquals(0, topDocs.totalHits);
LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_description);
Map<String, Analyzer> analyzerPerField = new HashMap<String, Analyzer>();
// KeywordAnalyzer treat `Q36` as a complete word,
// just as tokenized=false in indexing phase
analyzerPerField.put(fld_partnum, new KeywordAnalyzer());
PerFieldAnalyzerWrapper analyzerWrapper =
LuceneAppAnalyzerUtil.constructPerFieldAnalyzerWrapper(new SimpleAnalyzer(),
analyzerPerField);
query = new QueryParser(fld_description, analyzerWrapper).parse(fld_partnum + ":Q36 AND SPACE");
System.out.println(query.toString());
assertEquals("+partnum:Q36 +description:space", query.toString());
topDocs = indexSearcher.search(query, 10);
assertEquals(1, topDocs.totalHits);
LuceneAppUtil.renderSearchResultWithExplain(query, indexSearcher, topDocs, fld_description);
}
@Override
protected Analyzer defineAnalyzer() {
return new SimpleAnalyzer();
}
@Override
protected void doIndexing() throws IOException {
IndexWriter indexWriter = this.indexWriter;
Document document = new Document();
document.add(LuceneAppUtil.createStringField(fld_partnum, fldValue_partnum, Store.NO, false,
IndexOptions.DOCS, true));
document.add(LuceneAppUtil.createStringField(fld_description, fldValue_description, Store.YES,
true, IndexOptions.DOCS, true));
indexWriter.addDocument(document);
}
}
|
namespace StripeTests.Terminal
{
using Newtonsoft.Json;
using Stripe.Terminal;
using Xunit;
public class LocationTest : BaseStripeTest
{
public LocationTest(StripeMockFixture stripeMockFixture)
: base(stripeMockFixture)
{
}
[Fact]
public void Deserialize()
{
string json = this.GetFixture("/v1/terminal/locations/loc_123");
var location = JsonConvert.DeserializeObject<Location>(json);
Assert.NotNull(location);
Assert.IsType<Location>(location);
Assert.NotNull(location.Id);
Assert.Equal("terminal.location", location.Object);
}
}
}
|
@file:Suppress("CHECKRESULT")
package com.shimmer.microcore.extension
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
inline fun <T> Observable<T>.subscribe3(
crossinline onNext: T.() -> Unit,
crossinline onError: (Throwable) -> Unit = {},
crossinline onComplete: () -> Unit = {},
) {
this.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
it.onNext()
}, { error ->
onError(error)
}, {
onComplete()
})
}
|
stitching_version="1.9.0"
stitching_git_hash="master"
synapse_version="1.4.1"
synapse_git_hash="1.4.1"
synapse_dask_version="1.3.1"
neuron_segmentation_version="1.0.0"
neuron_segmentation_git_hash="1.0.0"
n5_spark_tools_version="3.11.0"
n5_spark_tools_git_hash="exm-3.11.0"
|
#!/bin/bash
ARGS=()
[[ -z "$DEVICE" ]] && ARGS+=("-Dwebdriver.url=https://${BROWSERSTACK_USERNAME}:${BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub")
[[ ! -z "$BROWSERSTACK_LOCAL_IDENTIFIER" ]] && ARGS+=("-Dwebdriver.cap.browserstack.localIdentifier=${BROWSERSTACK_LOCAL_IDENTIFIER}")
[[ ! -z "$BROWSER" ]] && ARGS+=("-Dwebdriver.cap.browser=$BROWSER")
[[ ! -z "$WEBDRIVER_TYPE" ]] && ARGS+=("-Dwebdriver.type=$WEBDRIVER_TYPE") || ARGS+=('-Dwebdriver.type=remote')
[[ ! -z "$OS" ]] && ARGS+=("-Dwebdriver.cap.os=${OS}")
[[ ! -z "$OS_VER" ]] && ARGS+=("-Dwebdriver.cap.os_version=${OS_VER}")
[[ ! -z "$DEVICE" ]] && ARGS+=("-Dwebdriver.appium.url=https://${BROWSERSTACK_USERNAME}:${BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub")
[[ ! -z "$DEVICE" ]] && ARGS+=("-Dwebdriver.cap.device=${DEVICE}")
[[ ! -z "$DEVICE" ]] && ARGS+=('-Dwebdriver.cap.realMobile=true')
mvn clean install "${ARGS[@]}"
|
package typingsSlinky.grammarkdown
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object stringwriterMod {
@JSImport("grammarkdown/dist/stringwriter", "StringWriter")
@js.native
class StringWriter () extends StObject {
def this(eol: String) = this()
var _depth: js.Any = js.native
var _eol: js.Any = js.native
var _indents: js.Any = js.native
var _newLine: js.Any = js.native
var _text: js.Any = js.native
def dedent(): Unit = js.native
var flushNewLine: js.Any = js.native
def indent(): Unit = js.native
def size: Double = js.native
def write(): Unit = js.native
def write(text: String): Unit = js.native
def writeln(): Unit = js.native
def writeln(text: String): Unit = js.native
}
}
|
---
layout: watch
title: TLP6 - 07/02/2021 - M20210207_002532_TLP_6T.jpg
date: 2021-02-07 00:25:32
permalink: /2021/02/07/watch/M20210207_002532_TLP_6
capture: TLP6/2021/202102/20210206/M20210207_002532_TLP_6T.jpg
---
|
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// OtherResources=process_sync_script.dart
import "dart:io";
import "package:expect/expect.dart";
import 'package:path/path.dart';
test(int blockCount, int stdoutBlockSize, int stderrBlockSize, int exitCode,
[int nonWindowsExitCode]) {
// Get the Dart script file that generates output.
var scriptFile = new File(
Platform.script.resolve("process_sync_script.dart").toFilePath());
var args = <String>[]
..addAll(Platform.executableArguments)
..addAll([
scriptFile.path,
blockCount.toString(),
stdoutBlockSize.toString(),
stderrBlockSize.toString(),
exitCode.toString()
]);
ProcessResult syncResult = Process.runSync(Platform.executable, args);
Expect.equals(blockCount * stdoutBlockSize, syncResult.stdout.length);
Expect.equals(blockCount * stderrBlockSize, syncResult.stderr.length);
if (Platform.isWindows) {
Expect.equals(exitCode, syncResult.exitCode);
} else {
if (nonWindowsExitCode == null) {
Expect.equals(exitCode, syncResult.exitCode);
} else {
Expect.equals(nonWindowsExitCode, syncResult.exitCode);
}
}
Process.run(Platform.executable, args).then((asyncResult) {
Expect.equals(syncResult.stdout, asyncResult.stdout);
Expect.equals(syncResult.stderr, asyncResult.stderr);
Expect.equals(syncResult.exitCode, asyncResult.exitCode);
});
}
main() {
test(10, 10, 10, 0);
test(10, 100, 10, 0);
test(10, 10, 100, 0);
test(100, 1, 10, 0);
test(100, 10, 1, 0);
test(100, 1, 1, 0);
test(1, 100000, 100000, 0);
// The buffer size used in process.h.
var kBufferSize = 16 * 1024;
test(1, kBufferSize, kBufferSize, 0);
test(1, kBufferSize - 1, kBufferSize - 1, 0);
test(1, kBufferSize + 1, kBufferSize + 1, 0);
test(10, 10, 10, 1);
test(10, 10, 10, 255);
test(10, 10, 10, -1, 255);
test(10, 10, 10, -255, 1);
}
|
export interface CommonColors {
readonly black: string;
readonly white: string;
readonly grey0: string;
readonly grey1: string;
readonly grey2: string;
readonly grey3: string;
readonly grey4: string;
readonly grey5: string;
readonly greyOutline: string;
readonly disabled: string;
readonly divider: string;
readonly foreground: string;
readonly background: string;
}
export interface AccentColors {
readonly primary: string;
readonly secondary: string;
readonly success: string;
readonly warning: string;
readonly error: string;
}
export interface SocialColors {
readonly kakao: string;
readonly naver: string;
readonly google: string;
readonly facebook: string;
readonly apple: string;
}
export interface Colors extends CommonColors, AccentColors, SocialColors {}
export type Theme = {
light: Colors;
dark: Colors;
};
export interface ThemeContextState {
dark: boolean;
toggleTheme: () => void;
colors: Colors;
}
|
package consoleui
import (
"fmt"
"github.com/nsf/termbox-go"
"github.com/xosmig/roguelike/core/geom"
"github.com/xosmig/roguelike/gamemodel/status"
"log"
)
// getKeyForAction accepts the set of interesting keys and waits for one of these keys to be pressed,
// or for a cancellation request from the user (Ctrl+C pressed).
// It returns the pressed key and a boolean flag, indicating whether the exit was requested or not.
func (ui *consoleUi) getKeyForAction(actions map[termbox.Key]func()) (key termbox.Key, finish bool) {
var ev termbox.Event
for {
ev = termbox.PollEvent()
if ev.Type != termbox.EventKey {
continue
}
if ev.Key == termbox.KeyCtrlC {
log.Println("Ctrl+C is pressed")
return ev.Key, true
}
if _, present := actions[ev.Key]; present {
return ev.Key, false
}
log.Printf("Debug: Invalid command key: %v\n", ev.Key)
}
}
// restartOrExit blocks until the user presses Ctrl+C (in this case it just returns nil),
// or Ctrl+R (in this case it restarts the game via recursive call to Run method).
func (ui *consoleUi) restartOrExit() error {
ui.messagef("Press 'Ctrl+C' to exit, or 'Ctrl+R' to restart")
actions := map[termbox.Key]func(){
termbox.KeyCtrlR: nil,
}
_, finish := ui.getKeyForAction(actions)
if finish {
log.Println("Exit requested")
return nil
}
ui.reloadGameModel()
return ui.Run()
}
// Run does the read-execute-print-loop.
func (ui *consoleUi) Run() error {
var afterRender []func()
// delay delays the given function execution so that it is executed after rendering.
// It's useful to adjust the rendered picture.
// For example, by printing a message.
delay := func(f func()) {
afterRender = append(afterRender, f)
}
accessItem := func(idx int) {
err := ui.model.GetCharacter().WearOrTakeOff(idx)
if err != nil {
delay(func() { ui.messagef("inventory error: %v", err) })
}
}
actions := map[termbox.Key]func(){
termbox.KeyArrowUp: func() { ui.model.DoMove(geom.Up) },
termbox.KeyArrowDown: func() { ui.model.DoMove(geom.Down) },
termbox.KeyArrowLeft: func() { ui.model.DoMove(geom.Left) },
termbox.KeyArrowRight: func() { ui.model.DoMove(geom.Right) },
termbox.KeyCtrlA: func() { accessItem(0) },
termbox.KeyCtrlS: func() { accessItem(1) },
termbox.KeyCtrlD: func() { accessItem(2) },
}
gameLoop:
for {
err := ui.render()
if err != nil {
return fmt.Errorf("while rendering: %v", err)
}
for _, f := range afterRender {
f()
}
afterRender = nil
switch ui.model.Status() {
case status.Continue:
// continue
case status.Defeat:
ui.messagef("You lost :(")
return ui.restartOrExit()
case status.Victory:
ui.messagef("You won [^_^]")
return ui.restartOrExit()
}
key, finish := ui.getKeyForAction(actions)
if finish {
break gameLoop
}
actions[key]()
}
return nil
}
|
RSpec.describe NxtHttpClient do
it 'has a version number' do
expect(NxtHttpClient::VERSION).not_to be nil
end
context 'http methods', :vcr_cassette do
let(:client) do
Class.new(NxtHttpClient::Client) do
configure do |config|
config.base_url = nil
end
response_handler(NxtHttpClient::ResponseHandler.new) do |handler|
handler.on(200) do |response|
'200 from level four class level'
end
end
end
end
subject do
client.new
end
let(:url) { http_stats_url('200') }
it 'calls fire with the respective http method' do
expect(subject.post(url, params: { andy: 'calling' })).to eq('200 from level four class level')
expect(subject.get(url)).to eq('200 from level four class level')
expect(subject.patch(url)).to eq('200 from level four class level')
expect(subject.put(url)).to eq('200 from level four class level')
expect(subject.delete(url)).to eq('200 from level four class level')
end
end
end
|
import { IsInt, Max, Min } from 'class-validator';
export class UserNutritionGoalsDTO {
@IsInt()
@Min(600)
@Max(20000)
public kcal: number;
@IsInt()
@Min(1)
@Max(98)
public protein: number;
@IsInt()
@Min(1)
@Max(98)
public carbs: number;
@IsInt()
@Min(1)
@Max(98)
public fats: number;
}
|
<?php
namespace Tests\Feature;
use Tests\CustomTestCase;
class AuthTest extends CustomTestCase{
public function setUp(): void
{
parent::setUp(); // TODO: Change the autogenerated stub
}
public function test_register_user(){
$userInfo = [
'email'=>'[email protected]' ,
'password'=>'brodybrody' ,
'password_confirmation'=>'brodybrody',
'name'=>'diaa osama'
];
$result=$this->postJson("/api/auth/register" , $userInfo)->json();
$this->assertEquals($result['success'] , true);
$this->assertNotEmpty($result['data']['token']);
}
public function test_un_valid_data_for_register_user(){
$userInfo = [
'email'=>'' ,
'password'=>'brodybrody' ,
'password_confirmation'=>'brodybrodyd',
'name'=>''
];
$result = $this->postJson('/api/auth/register' , $userInfo)->json();
$this->assertEquals($result['code'] , 422);
$this->assertCount( 3, $result['data']['errors'] );
}
public function test_login_user(){
$user= createUser();
$this->postJson('/api/auth/login' , [
'email' =>$user['email'] ,
'password'=>$user['password']
])->assertStatus(200);
$this->assertAuthenticated();
}
public function test_un_valid_data_for_login_user(){
$result= $this->postJson('/api/auth/login' , [])
->assertStatus(422)->json();
$this->assertCount( 2, $result['data']['errors'] );
// un valid email
$result= $this->postJson('/api/auth/login' , [
'email' =>'fakeemailyahoocom',
'password'=>'fakepassword'
]) ->assertStatus(422);
// fake account
$this->postJson('/api/auth/login' , [
'email' =>'[email protected]',
'password'=>'fakepassword'
])->assertStatus(403);
}
public function test_logout_user(){
$this->login();
$this->assertAuthenticated();
$this->postJson('/api/auth/logout');
$this->assertGuest();
}
public function test_refresh_token_user(){
$authUser= $this->login();
$result=$this->postJson('/api/auth/refresh')
->assertStatus(200)->json();
$this->assertNotEmpty($result['data']['token']);
$user= $this->login($authUser , $result['data']['token']);
$this->assertEquals($authUser , $user);
}
}
|
(ns advent-of-code-2017.day1
(:require [clojure.string :refer [trim]]))
(defn load-input []
(trim (slurp "resources/day1.txt")))
(defn extract-pairs [input]
(partition 2 1
(map
#(Integer/valueOf (str %))
(str input (first input))))) ;; add the first value to the end to simulate wrapping
(defn solve-puzzle-1 []
(let [input (load-input)]
(reduce (fn [v [a b]] (if (= a b) (+ v a) v)) 0 (extract-pairs input))))
(defn solve-puzzle-2 []
(let [input (map #(Integer/valueOf (str %)) (load-input))
l (/ (count input) 2)
col1 (take l input)
col2 (take-last l input)]
(* 2
(reduce
+
(map
(fn [a b] (if (= a b) a 0))
col1
col2)))))
(defn solve []
(println (format "Day 1 - solution 1: %d - solution 2: %d" (solve-puzzle-1) (solve-puzzle-2))))
|
#include <stdint.h>
#include <stdlib.h>
#include "gba.h"
#include "drawable.h"
#include "input.h"
#include "tiles.h"
#include "font.h"
#include "text.h"
// The entry point for the game.
int main()
{
// Set display options.
// DCNT_MODE0 sets mode 0, which provides four tiled backgrounds.
// DCNT_OBJ enables objects.
// DCNT_OBJ_1D make object tiles mapped in 1D (which makes life easier).
REG_DISPCNT = DCNT_MODE0 | DCNT_BG0 | DCNT_BG1 | DCNT_BG2 | DCNT_BG3 | DCNT_OBJ | DCNT_OBJ_1D;
// Set background 0 options.
// BG_CBB sets the charblock base (where the tiles come from).
// BG_SBB sets the screenblock base (where the tilemap comes from).
// BG_8BPP uses 8bpp tiles.
// BG_REG_32x32 makes it a 32x32 tilemap.
REG_BG0CNT = BG_CBB(0) | BG_SBB(30) | BG_8BPP | BG_REG_32x32;
// Set background 1 options.
REG_BG1CNT = BG_CBB(0) | BG_SBB(29) | BG_8BPP | BG_REG_32x32;
REG_BG1HOFS = 0;
REG_BG1VOFS = 0;
// Set background 2 options.
REG_BG2CNT = BG_CBB(0) | BG_SBB(28) | BG_8BPP | BG_REG_32x32;
REG_BG2HOFS = 0;
REG_BG2VOFS = 0;
// Set background 3 options.
REG_BG3CNT = BG_CBB(0) | BG_SBB(27) | BG_8BPP | BG_REG_32x32;
REG_BG3HOFS = 0;
REG_BG3VOFS = 0;
// Set up the object palette.
SetPaletteObj(0, RGB(0, 0, 0)); // blank
SetPaletteObj(1, RGB(0, 0, 0)); // black
SetPaletteObj(2, RGB(31, 31, 31)); // white
SetPaletteObj(3, RGB(31, 31, 0)); // yellow
SetPaletteObj(4, RGB(31, 0, 0)); // red
SetPaletteBG(0, RGB(0, 0, 0)); // blank
SetPaletteBG(1, RGB(0, 0, 0)); // black
SetPaletteBG(2, RGB(31, 31, 31)); // white
SetPaletteBG(3, RGB(31, 31, 0)); // bright yellow
SetPaletteBG(4, RGB(31, 0, 0)); // red
SetPaletteBG(5, RGB(30, 0, 15)); // magenta
SetPaletteBG(6, RGB(23, 3, 5)); // pink?
SetPaletteBG(7, RGB(1, 4, 28)); // blueIhope
SetPaletteBG(8, RGB(2, 25, 2)); // greenish
SetPaletteBG(9, RGB(10, 10, 0)); // yellow?
SetPaletteBG(10, RGB(31, 31, 31)); // white
SetPaletteBG(11, RGB(20, 20, 31)); // pale blue (sky)
SetPaletteBG(12, RGB(25, 25, 25)); // grey (cloud)
SetPaletteBG(13, RGB(20, 10, 0)); // brown (brick)
// Alphabet tile counter.
int tile_num = 0;
// Loads the font tile-map to charblock 1.
for (tile_num = 0; tile_num < 129; tile_num++)
{
LoadTile8(1, tile_num, font_bold[tile_num]);
}
// Load the tile data above into video memory, putting it in charblock 0.
LoadTile8(0, 1, sky_tile);
LoadTile8(0, 2, cloud_tile);
LoadTile8(0, 3, brick_tile);
LoadTile8(0, 4, build_tile);
LoadTile8(0, 5, blank_tile); // tile number 0 = blank
LoadTile8(0, 6, red_box_tile); // tile number 1 = red box
LoadTile8(0, 7, LSD_box_tile); // my own tile 2
// Load the tiles for the objects into charblock 4.
// (Charblocks 4 and 5 are for object tiles;
// 8bpp tiles 0-255 are in CB 4, tiles 256-511 in CB 5.)
LoadTile8(4, 1, LSD_box_tile);
// set sky background and load cloud tiles
for (int y = 0; y < 32; y++)
{
for (int x = 0; x < 32; ++x)
{
SetTile(27, x, y, 1);
}
}
// clouds to screenblock 28.
for (int cl = 0; cl < 24; cl++) // cloudcounter
{
int clx = rand()%32; // generates a random position x for the clouds between numbers 1-32
int cly = rand()%14; // generates a random position y for the clouds between numbers 1-16
SetTile(28, clx, cly, 2); // puts down the actual tiles in the above positions
}
// Make sure no objects are on the screen, but why should they be?
ClearObjects();
// Initial object parameters
int smilex = 116;
int smiley = 76;
// Set up object 0 as a char in the middle of the screen.
SetObject(0,
ATTR0_SHAPE(0) | ATTR0_8BPP | ATTR0_REG | ATTR0_Y(smiley),
ATTR1_SIZE(0) | ATTR1_X(smilex),
ATTR2_ID8(1));
SetObjectX(0, 1);
SetObjectY(0, 1);
// Input handle
Input input;
// Initialize a frame counter.
int frames = 0;
int curbgOffSetX = 0;
int curbgOffSetY = 0;
while (true)
{
frames++;
Text::DrawText(22, 1, "Score:");
input.UpdateInput();
int dirx = input.GetInput().xdir;
int diry = input.GetInput().ydir;
input.ResetInput();
if (diry != 0)
{
smiley += diry;
SetObjectY(0, smiley);
}
if (dirx != 0)
{
smilex += dirx;
SetObjectX(0, smilex);
}
if (smilex >= SCREEN_WIDTH - 9)
{
smilex = SCREEN_WIDTH - 9;
}
if (smilex <= 0 + 1)
{
smilex = 0 + 1;
}
if (smiley >= SCREEN_HEIGHT - 9)
{
smiley = SCREEN_HEIGHT - 9;
}
if (smiley <= 0 + 1)
{
smiley = 0 + 1;
}
WaitVSync();
UpdateObjects();
}
return 0;
}
void DrawRandomCircles()
{
//WaitVSync();
//x = rand() % 240;
//y = rand() % 160;
//r = rand() % 50 + 10;
//uint16_t color = RGB(rand()%31, rand()%31, rand()%31);
//DrawCircle3(x, y, r, color);
//WaitVSync();
}
/// BG scroll and screen register switch
/*
//if ((REG_KEYINPUT & KEY_LEFT) == 0)
//{
// if (curbgOffSetX > 0)
// curbgOffSetX--;
//}
//
//else if ((REG_KEYINPUT & KEY_RIGHT) == 0)
//{
// if (curbgOffSetX < SCREEN_WIDTH)
// curbgOffSetX++;
//}
//
//if ((REG_KEYINPUT & KEY_UP) == 0)
//{
// if (curbgOffSetY > 0)
// curbgOffSetY--;
//}
//
//else if ((REG_KEYINPUT & KEY_DOWN) == 0)
//{
// if (curbgOffSetY < SCREEN_HEIGHT)
// curbgOffSetY++;
//}
//
//
//REG_BG0HOFS = curbgOffSetX;
//REG_BG0VOFS = curbgOffSetY;
//if ((REG_KEYINPUT & KEY_A) == 0)
//{
// REG_BG0CNT = BG_CBB(0) | BG_SBB(30) | BG_8BPP | BG_REG_32x32;
//}
//
//else if ((REG_KEYINPUT & KEY_B) == 0)
//{
// REG_BG0CNT = BG_CBB(0) | BG_SBB(31) | BG_8BPP | BG_REG_32x32;
//}
*/
|
using System;
using System.Diagnostics;
using System.Globalization;
using System.ServiceProcess;
using System.Threading;
namespace BacklightShifter {
internal static class ServiceStatusThread {
private static Thread Thread;
private static readonly ManualResetEvent CancelEvent = new ManualResetEvent(false);
public static void Start() {
if (Thread != null) { return; }
Thread = new Thread(Run) {
Name = "Service status",
CurrentCulture = CultureInfo.InvariantCulture
};
Thread.Start();
}
public static void Stop() {
try {
CancelEvent.Set();
while (Thread.IsAlive) { Thread.Sleep(10); }
Thread = null;
CancelEvent.Reset();
} catch { }
}
private static void Run() {
try {
using (var service = new ServiceController(AppService.Instance.ServiceName)) {
bool? lastIsRunning = null;
Tray.SetStatusToUnknown();
while (!CancelEvent.WaitOne(250, false)) {
bool? currIsRunning;
try {
service.Refresh();
currIsRunning = (service.Status == ServiceControllerStatus.Running);
} catch (InvalidOperationException) {
currIsRunning = null;
}
if (lastIsRunning != currIsRunning) {
if (currIsRunning == null) {
Tray.SetStatusToUnknown();
} else if (currIsRunning == true) {
Tray.SetStatusToRunning();
} else {
Tray.SetStatusToStopped();
}
}
lastIsRunning = currIsRunning;
}
}
} catch (ThreadAbortException) { }
}
}
}
|
/*
* Copyright 2021 HM Revenue & Customs
*
* 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 uk.gov.hmrc.customs.rosmfrontend.controllers.subscription
import javax.inject.{Inject, Singleton}
import play.api.Application
import play.api.mvc.{AnyContent, Request, Session}
import uk.gov.hmrc.customs.rosmfrontend.controllers.FeatureFlags
import uk.gov.hmrc.customs.rosmfrontend.domain._
import uk.gov.hmrc.customs.rosmfrontend.domain.registration.UserLocation
import uk.gov.hmrc.customs.rosmfrontend.domain.subscription.{SubscriptionFlow, SubscriptionPage, _}
import uk.gov.hmrc.customs.rosmfrontend.logging.CdsLogger.logger
import uk.gov.hmrc.customs.rosmfrontend.models.Journey
import uk.gov.hmrc.customs.rosmfrontend.services.cache.{RequestSessionData, SessionCache}
import uk.gov.hmrc.customs.rosmfrontend.services.subscription.SubscriptionDetailsService
import uk.gov.hmrc.customs.rosmfrontend.util.Constants.ONE
import uk.gov.hmrc.http.HeaderCarrier
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
case class SubscriptionFlowConfig(
pageBeforeFirstFlowPage: SubscriptionPage,
pagesInOrder: List[SubscriptionPage],
pageAfterLastFlowPage: SubscriptionPage
) {
private def lastPageInTheFlow(currentPos: Int): Boolean = currentPos == pagesInOrder.size - ONE
def determinePageBeforeSubscriptionFlow(uriBeforeSubscriptionFlow: Option[String]): SubscriptionPage =
uriBeforeSubscriptionFlow.fold(pageBeforeFirstFlowPage)(url => PreviousPage(url))
def stepInformation(
currentPage: SubscriptionPage,
uriBeforeSubscriptionFlow: Option[String]
): SubscriptionFlowInfo = {
val currentPos = pagesInOrder.indexOf(currentPage)
val nextPage = if (lastPageInTheFlow(currentPos)) pageAfterLastFlowPage else pagesInOrder(currentPos + ONE)
SubscriptionFlowInfo(stepNumber = currentPos + ONE, totalSteps = pagesInOrder.size, nextPage = nextPage)
}
}
@Singleton
class SubscriptionFlowManager @Inject()(
override val currentApp: Application,
requestSessionData: RequestSessionData,
cdsFrontendDataCache: SessionCache,
subscriptionDetailsService: SubscriptionDetailsService
) extends FeatureFlags {
def currentSubscriptionFlow(implicit request: Request[AnyContent]): SubscriptionFlow =
requestSessionData.userSubscriptionFlow
def stepInformation(
currentPage: SubscriptionPage
)(implicit hc: HeaderCarrier, request: Request[AnyContent]): SubscriptionFlowInfo =
SubscriptionFlows(currentSubscriptionFlow)
.stepInformation(currentPage, requestSessionData.uriBeforeSubscriptionFlow)
def startSubscriptionFlow(
journey: Journey.Value
)(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] =
startSubscriptionFlow(None, requestSessionData.userSelectedOrganisationType, journey)
def startSubscriptionFlow(
previousPage: Option[SubscriptionPage] = None,
cdsOrganisationType: CdsOrganisationType,
journey: Journey.Value
)(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] =
startSubscriptionFlow(previousPage, Some(cdsOrganisationType), journey)
def startSubscriptionFlow(
previousPage: Option[SubscriptionPage],
journey: Journey.Value
)(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] =
startSubscriptionFlow(previousPage, requestSessionData.userSelectedOrganisationType, journey)
private def startSubscriptionFlow(
previousPage: Option[SubscriptionPage],
orgType: => Option[CdsOrganisationType],
journey: Journey.Value
)(implicit hc: HeaderCarrier, request: Request[AnyContent]): Future[(SubscriptionPage, Session)] = {
val maybePreviousPageUrl = previousPage.map(page => page.url)
cdsFrontendDataCache.registrationDetails map { registrationDetails =>
{
val flow = selectFlow(registrationDetails, orgType, journey)
logger.info(s"select Subscription flow: ${flow.name}")
(
SubscriptionFlows(flow).pagesInOrder.head,
requestSessionData.storeUserSubscriptionFlow(
flow,
SubscriptionFlows(flow).determinePageBeforeSubscriptionFlow(maybePreviousPageUrl).url
)
)
}
}
}
private def selectFlow(
registrationDetails: RegistrationDetails,
maybeOrgType: => Option[CdsOrganisationType],
journey: Journey.Value
)(implicit request: Request[AnyContent], headerCarrier: HeaderCarrier): SubscriptionFlow = {
val userLocation = requestSessionData.selectedUserLocation
val subscribePrefix = (userLocation, journey, registrationDetails.customsId, rowHaveUtrEnabled) match {
case (
Some(UserLocation.Islands) | Some(UserLocation.ThirdCountry),
Journey.Migrate,
None,
true
) =>
"migration-eori-row-utrNino-enabled-"
case (
Some(UserLocation.Islands) | Some(UserLocation.ThirdCountry),
Journey.Migrate,
_,
_
) =>
"migration-eori-row-"
case (_, Journey.Migrate, _, _) => "migration-eori-" // This means UK
case _ => ""
}
val selectedFlow: SubscriptionFlow =
(registrationDetails, maybeOrgType, rowHaveUtrEnabled, registrationDetails.customsId, journey) match {
case (_: RegistrationDetailsOrganisation, Some(CdsOrganisationType.Partnership), _, _, _) =>
SubscriptionFlow(subscribePrefix + PartnershipSubscriptionFlow.name)
case (_: RegistrationDetailsOrganisation, _, true, None, Journey.Migrate) =>
SubscriptionFlow(subscribePrefix + OrganisationSubscriptionFlow.name)
case (_: RegistrationDetailsIndividual, _, true, None, Journey.Migrate) =>
SubscriptionFlow(subscribePrefix + IndividualSubscriptionFlow.name)
case (_: RegistrationDetailsOrganisation, _, _, _, _) =>
SubscriptionFlow(subscribePrefix + OrganisationSubscriptionFlow.name)
case (_: RegistrationDetailsIndividual, _, _, _, _) =>
SubscriptionFlow(subscribePrefix + IndividualSubscriptionFlow.name)
case _ => throw new IllegalStateException("Incomplete cache cannot complete journey")
}
maybeOrgType.fold(selectedFlow)(
orgType => SubscriptionFlows.flows.keys.find(_.name == (subscribePrefix + orgType.id)).getOrElse(selectedFlow)
)
}
}
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Game.Play.Handler where
import Prelude (IO, flip, pure, ($), (+), (<), (<$>),
(>), (>>=))
import Control.Lens (use, view, (.=), (^.))
import Control.Monad (when)
import Control.Monad.Except (MonadError, throwError)
import Control.Monad.RWS (ask, get)
import Control.Monad.Random (MonadRandom)
import Control.Monad.Reader (MonadReader)
import Data.Monoid ((<>))
import TextShow (showt)
import Servant ((:<|>) (..), ServerT)
import Auth (UserInfo)
import qualified Database.Class as Db
import Handler.Types (AppError (..), HandlerAuthT)
import Game.Agent (agentDo)
import Game.Api.Types (ErrorOr (..), GameError (..))
import Game.Bot (botMoves)
import qualified Game.Moves as Moves
import Game.Play (getMaxBetValue, withGame, withPlayer)
import qualified Game.Play.Api as Api
import Game.Play.Api.Types
import Game.Play.Types (Seating, seatLeft, seatMe, seatRight)
import Game.Types
handlers :: ServerT Api.Routes (HandlerAuthT IO)
handlers =
playCard
:<|> placeBet
placeBet
:: (Db.Read m, Db.Replace m, MonadError AppError m, MonadReader UserInfo m, MonadRandom m)
=> PlaceBetRq
-> m (ErrorOr Game)
placeBet req = withGame (req ^. pbrqAuth) $ do
seating <- ask
min <- use gPhase >>= \case
CardOrBet -> pure 1
Bet n -> pure $ n + 1
_ -> throwError $ GameError "placeBet in wrong phase"
max <- getMaxBetValue <$> get
when (req ^. pbrqValue < min) $
throwError $ GameError $ "Bet value must be bigger or equal to " <> showt min
when (req ^. pbrqValue > max) $
throwError $ GameError $ "Bet value must be smaller or equal to " <> showt max
flip withPlayer (seating ^. seatMe) $ agentDo $ Moves.placeBet $ req ^. pbrqValue
botMoves $ nextInLine seating
playCard
:: (Db.Read m, Db.Replace m, MonadError AppError m, MonadReader UserInfo m, MonadRandom m)
=> PlayCardRq
-> m (ErrorOr Game)
playCard req = withGame (req ^. pcrqAuth) $ do
seating <- ask
next <- use gPhase >>= \case
FirstCard -> do gPhase .= CardOrBet
view seatLeft
CardOrBet -> pure $ nextInLine seating
_ -> throwError $ GameError "playCard in wrong phase"
flip withPlayer (seating ^. seatMe) $
agentDo $ case req ^. pcrqCardKind of
Plain -> Moves.playPlain
Skull -> Moves.playSkull
botMoves next
nextInLine
:: Seating
-> [Player]
nextInLine seating =
seating ^. seatRight <> seating ^. seatLeft
|
import { PrivKey } from "../priv-key";
import { PubKey } from "../pub-key";
import { PrivKeySecp256k1 } from './priv-key';
describe('PrivKeySecp256k1', () => {
let privKey: PrivKeySecp256k1(privKey);
let pubkey: PrivKeySecp256k1(pubkey);
it('公開鍵を取得する', () => {
expect(pubkey).toEqual(getPubKey(privKey));
});
it('署名を作成する', () => {
expect(signature).toEqual(sign(signature));
});
it('JSON.stringify時に参照される', () => {
expect().toEqual();
});
});
|
#!/usr/bin/env bash
cat >hello.sh <<\EOF
#!/bin/sh
echo "Hello World!"
EOF
chmod +x hello.sh
./hello.sh
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* 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 org.apache.spark.sql.rapids
import java.util.{Locale, ServiceConfigurationError, ServiceLoader}
import scala.collection.JavaConverters._
import scala.util.{Failure, Success, Try}
import org.apache.spark.internal.Logging
import org.apache.spark.sql._
import org.apache.spark.sql.execution.SparkPlan
import org.apache.spark.sql.execution.datasources._
import org.apache.spark.sql.execution.datasources.csv.CSVFileFormat
import org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider
import org.apache.spark.sql.execution.datasources.json.JsonFileFormat
import org.apache.spark.sql.execution.datasources.orc.OrcFileFormat
import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat
import org.apache.spark.sql.execution.streaming._
import org.apache.spark.sql.execution.streaming.sources.{RateStreamProvider, TextSocketSourceProvider}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.sources._
import org.apache.spark.util.Utils
object GpuDataSource extends Logging {
/** A map to maintain backward compatibility in case we move data sources around. */
private val backwardCompatibilityMap: Map[String, String] = {
val jdbc = classOf[JdbcRelationProvider].getCanonicalName
val json = classOf[JsonFileFormat].getCanonicalName
val parquet = classOf[ParquetFileFormat].getCanonicalName
val csv = classOf[CSVFileFormat].getCanonicalName
val libsvm = "org.apache.spark.ml.source.libsvm.LibSVMFileFormat"
val orc = "org.apache.spark.sql.hive.orc.OrcFileFormat"
val nativeOrc = classOf[OrcFileFormat].getCanonicalName
val socket = classOf[TextSocketSourceProvider].getCanonicalName
val rate = classOf[RateStreamProvider].getCanonicalName
Map(
"org.apache.spark.sql.jdbc" -> jdbc,
"org.apache.spark.sql.jdbc.DefaultSource" -> jdbc,
"org.apache.spark.sql.execution.datasources.jdbc.DefaultSource" -> jdbc,
"org.apache.spark.sql.execution.datasources.jdbc" -> jdbc,
"org.apache.spark.sql.json" -> json,
"org.apache.spark.sql.json.DefaultSource" -> json,
"org.apache.spark.sql.execution.datasources.json" -> json,
"org.apache.spark.sql.execution.datasources.json.DefaultSource" -> json,
"org.apache.spark.sql.parquet" -> parquet,
"org.apache.spark.sql.parquet.DefaultSource" -> parquet,
"org.apache.spark.sql.execution.datasources.parquet" -> parquet,
"org.apache.spark.sql.execution.datasources.parquet.DefaultSource" -> parquet,
"org.apache.spark.sql.hive.orc.DefaultSource" -> orc,
"org.apache.spark.sql.hive.orc" -> orc,
"org.apache.spark.sql.execution.datasources.orc.DefaultSource" -> nativeOrc,
"org.apache.spark.sql.execution.datasources.orc" -> nativeOrc,
"org.apache.spark.ml.source.libsvm.DefaultSource" -> libsvm,
"org.apache.spark.ml.source.libsvm" -> libsvm,
"com.databricks.spark.csv" -> csv,
"org.apache.spark.sql.execution.streaming.TextSocketSourceProvider" -> socket,
"org.apache.spark.sql.execution.streaming.RateSourceProvider" -> rate
)
}
/**
* Class that were removed in Spark 2.0. Used to detect incompatibility libraries for Spark 2.0.
*/
private val spark2RemovedClasses = Set(
"org.apache.spark.sql.DataFrame",
"org.apache.spark.sql.sources.HadoopFsRelationProvider",
"org.apache.spark.Logging")
/** Given a provider name, look up the data source class definition. */
def lookupDataSource(provider: String, conf: SQLConf): Class[_] = {
val provider1 = backwardCompatibilityMap.getOrElse(provider, provider) match {
case name if name.equalsIgnoreCase("orc") &&
conf.getConf(SQLConf.ORC_IMPLEMENTATION) == "native" =>
classOf[OrcFileFormat].getCanonicalName
case name if name.equalsIgnoreCase("orc") &&
conf.getConf(SQLConf.ORC_IMPLEMENTATION) == "hive" =>
"org.apache.spark.sql.hive.orc.OrcFileFormat"
case "com.databricks.spark.avro" if conf.replaceDatabricksSparkAvroEnabled =>
"org.apache.spark.sql.avro.AvroFileFormat"
case name => name
}
val provider2 = s"$provider1.DefaultSource"
val loader = Utils.getContextOrSparkClassLoader
val serviceLoader = ServiceLoader.load(classOf[DataSourceRegister], loader)
try {
serviceLoader.asScala.filter(_.shortName().equalsIgnoreCase(provider1)).toList match {
// the provider format did not match any given registered aliases
case Nil =>
try {
Try(loader.loadClass(provider1)).orElse(Try(loader.loadClass(provider2))) match {
case Success(dataSource) =>
// Found the data source using fully qualified path
dataSource
case Failure(error) =>
if (provider1.startsWith("org.apache.spark.sql.hive.orc")) {
throw new AnalysisException(
"Hive built-in ORC data source must be used with Hive support enabled. " +
"Please use the native ORC data source by setting 'spark.sql.orc.impl' to " +
"'native'")
} else if (provider1.toLowerCase(Locale.ROOT) == "avro" ||
provider1 == "com.databricks.spark.avro" ||
provider1 == "org.apache.spark.sql.avro") {
throw new AnalysisException(
s"Failed to find data source: $provider1. Avro is built-in but external data " +
"source module since Spark 2.4. Please deploy the application as per " +
"the deployment section of \"Apache Avro Data Source Guide\".")
} else if (provider1.toLowerCase(Locale.ROOT) == "kafka") {
throw new AnalysisException(
s"Failed to find data source: $provider1. Please deploy the application as " +
"per the deployment section of " +
"\"Structured Streaming + Kafka Integration Guide\".")
} else {
throw new ClassNotFoundException(
s"Failed to find data source: $provider1. Please find packages at " +
"http://spark.apache.org/third-party-projects.html",
error)
}
}
} catch {
case e: NoClassDefFoundError => // This one won't be caught by Scala NonFatal
// NoClassDefFoundError's class name uses "/" rather than "." for packages
val className = e.getMessage.replaceAll("/", ".")
if (spark2RemovedClasses.contains(className)) {
throw new ClassNotFoundException(s"$className was removed in Spark 2.0. " +
"Please check if your library is compatible with Spark 2.0", e)
} else {
throw e
}
}
case head :: Nil =>
// there is exactly one registered alias
head.getClass
case sources =>
// There are multiple registered aliases for the input. If there is single datasource
// that has "org.apache.spark" package in the prefix, we use it considering it is an
// internal datasource within Spark.
val sourceNames = sources.map(_.getClass.getName)
val internalSources = sources.filter(_.getClass.getName.startsWith("org.apache.spark"))
if (internalSources.size == 1) {
logWarning(s"Multiple sources found for $provider1 (${sourceNames.mkString(", ")}), " +
s"defaulting to the internal datasource (${internalSources.head.getClass.getName}).")
internalSources.head.getClass
} else {
throw new AnalysisException(s"Multiple sources found for $provider1 " +
s"(${sourceNames.mkString(", ")}), please specify the fully qualified class name.")
}
}
} catch {
case e: ServiceConfigurationError if e.getCause.isInstanceOf[NoClassDefFoundError] =>
// NoClassDefFoundError's class name uses "/" rather than "." for packages
val className = e.getCause.getMessage.replaceAll("/", ".")
if (spark2RemovedClasses.contains(className)) {
throw new ClassNotFoundException(s"Detected an incompatible DataSourceRegister. " +
"Please remove the incompatible library from classpath or upgrade it. " +
s"Error: ${e.getMessage}", e)
} else {
throw e
}
}
}
}
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Displays form for password change
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Get HTML for the Change password dialog
*
* @param string $username username
* @param string $hostname hostname
*
* @return string html snippet
*/
function PMA_getHtmlForChangePassword($username, $hostname)
{
/**
* autocomplete feature of IE kills the "onchange" event handler and it
* must be replaced by the "onpropertychange" one in this case
*/
$chg_evt_handler = (PMA_USR_BROWSER_AGENT == 'IE'
&& PMA_USR_BROWSER_VER >= 5
&& PMA_USR_BROWSER_VER < 7)
? 'onpropertychange'
: 'onchange';
$is_privileges = basename($_SERVER['SCRIPT_NAME']) === 'server_privileges.php';
$html = '<form method="post" id="change_password_form" '
. 'action="' . basename($GLOBALS['PMA_PHP_SELF']) . '" '
. 'name="chgPassword" '
. 'class="' . ($is_privileges ? 'submenu-item' : '') . '">';
$html .= PMA_URL_getHiddenInputs();
if (strpos($GLOBALS['PMA_PHP_SELF'], 'server_privileges') !== false) {
$html .= '<input type="hidden" name="username" '
. 'value="' . htmlspecialchars($username) . '" />'
. '<input type="hidden" name="hostname" '
. 'value="' . htmlspecialchars($hostname) . '" />';
}
$html .= '<fieldset id="fieldset_change_password">'
. '<legend'
. ($is_privileges
? ' data-submenu-label="' . __('Change password') . '"'
: ''
)
. '>' . __('Change password') . '</legend>'
. '<table class="data noclick">'
. '<tr class="odd">'
. '<td colspan="2">'
. '<input type="radio" name="nopass" value="1" id="nopass_1" '
. 'onclick="pma_pw.value = \'\'; pma_pw2.value = \'\'; '
. 'this.checked = true" />'
. '<label for="nopass_1">' . __('No Password') . '</label>'
. '</td>'
. '</tr>'
. '<tr class="even vmiddle">'
. '<td>'
. '<input type="radio" name="nopass" value="0" id="nopass_0" '
. 'onclick="document.getElementById(\'text_pma_pw\').focus();" '
. 'checked="checked" />'
. '<label for="nopass_0">' . __('Password:') . ' </label>'
. '</td>'
. '<td>'
. '<input type="password" name="pma_pw" id="text_pma_pw" size="10" '
. 'class="textfield"'
. $chg_evt_handler . '="nopass[1].checked = true" />'
. ' ' . __('Re-type:') . ' '
. '<input type="password" name="pma_pw2" id="text_pma_pw2" size="10" '
. 'class="textfield"'
. $chg_evt_handler . '="nopass[1].checked = true" />'
. '</td>'
. '</tr>';
$default_auth_plugin = PMA_getCurrentAuthenticationPlugin(
'change', $username, $hostname
);
// See http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-5.html
if (PMA_Util::getServerType() == 'MySQL'
&& PMA_MYSQL_INT_VERSION >= 50705
) {
$html .= '<tr class="vmiddle">'
. '<td>' . __('Password Hashing:') . '</td>'
. '<td>'
. '<input type="radio" name="pw_hash" id="radio_pw_hash_mysql_native" '
. 'value="mysql_native_password"';
if ($default_auth_plugin == 'mysql_native_password') {
$html .= '" checked="checked"';
}
$html .= ' />'
. '<label for="radio_pw_hash_mysql_native">'
. __('MySQL native password')
. '</label>'
. '</td>'
. '</tr>'
. '<tr id="tr_element_before_generate_password">'
. '<td> </td>'
. '<td>'
. '<input type="radio" name="pw_hash" id="radio_pw_hash_sha256" '
. 'value="sha256_password"';
if ($default_auth_plugin == 'sha256_password') {
$html .= '" checked="checked"';
}
$html .= ' />'
. '<label for="radio_pw_hash_sha256">'
. __('SHA256 password')
. '</label>'
. '</td>'
. '</tr>';
} elseif (PMA_Util::getServerType() == 'MySQL'
&& PMA_MYSQL_INT_VERSION >= 50606
) {
$html .= '<tr class="vmiddle" id="tr_element_before_generate_password">'
. '<td>' . __('Password Hashing:') . '</td>'
. '<td>'
. '<input type="radio" name="pw_hash" id="radio_pw_hash_new" '
. 'value="' . $default_auth_plugin . '" checked="checked" />'
. '<label for="radio_pw_hash_new">' . $default_auth_plugin . '</label>'
. '</td>'
. '</tr>';
} else {
$html .= '<tr class="vmiddle">'
. '<td>' . __('Password Hashing:') . '</td>'
. '<td>'
. '<input type="radio" name="pw_hash" id="radio_pw_hash_new" '
. 'value="mysql_native_password" checked="checked" />'
. '<label for="radio_pw_hash_new">mysql_native_password</label>'
. '</td>'
. '</tr>'
. '<tr id="tr_element_before_generate_password" >'
. '<td> </td>'
. '<td>'
. '<input type="radio" name="pw_hash" id="radio_pw_hash_old" '
. 'value="old" />'
. '<label for="radio_pw_hash_old">' . __('MySQL 4.0 compatible')
. '</label>'
. '</td>'
. '</tr>';
}
$html .= '</table>';
$html .= '<div '
. ($default_auth_plugin != 'sha256_password' ? 'style="display:none"' : '')
. ' id="ssl_reqd_warning_cp">'
. PMA_Message::notice(
__(
'This method requires using an \'<i>SSL connection</i>\' '
. 'or an \'<i>unencrypted connection that encrypts the password '
. 'using RSA</i>\'; while connecting to the server.'
)
. PMA_Util::showMySQLDocu('sha256-authentication-plugin')
)
->getDisplay()
. '</div>';
$html .= '</fieldset>'
. '<fieldset id="fieldset_change_password_footer" class="tblFooters">'
. '<input type="hidden" name="change_pw" value="1" />'
. '<input type="submit" value="' . __('Go') . '" />'
. '</fieldset>'
. '</form>';
return $html;
}
|
export enum MODES {
Lydian,
Ionian,
Mixolydian,
Dorian,
Aeolian,
Phrygian,
Locrian
}
export const enum Intervals {
unison,
minorSecond, // semitone
majorSecond, // tone
minorThird,
majorThird,
perfectFourth,
tritone, // dim 5th, aug 4th
perfectFifth,
minorSixth,
majorSixth,
minorSeventh,
majorSeventh,
octave
}
export enum Degrees {
"I",
"II",
"III",
"IV",
"V",
"VI",
"VII"
}
export enum DegreeNames { // unused
tonic,
supertonic,
mediant,
subdominant,
dominant,
submediant,
leadingTone
}
export enum ChordColors {
major = "#A53F2B",
minor = "#81A4CD",
diminished = "#AEC5EB",
augmented = "#78BC61",
sus2 = "#388659",
sus4 = "#388659",
maj7 = "#F7B538",
dom7 = "#F7B538",
dim7 = "#AEC5EB",
major1nv = "#A53F2B",
major2nv = "#A53F2B",
minor1nv = "#81A4CD",
minor2nv = "#81A4CD",
default = "#424C55"
}
export class ChordShapes {
public static major = [Intervals.majorThird, Intervals.minorThird];
public static minor = [Intervals.minorThird, Intervals.majorThird];
public static diminished = [Intervals.minorThird, Intervals.minorThird];
public static augmented = [Intervals.majorThird, Intervals.majorThird];
public static sus2 = [Intervals.majorSecond, Intervals.perfectFourth];
public static sus4 = [Intervals.perfectFourth, Intervals.majorSecond];
public static maj7 = [Intervals.majorThird, Intervals.minorThird, Intervals.majorThird];
public static dom7 = [Intervals.majorThird, Intervals.minorThird, Intervals.majorThird];
public static dim7 = [Intervals.minorThird, Intervals.majorSecond, Intervals.minorThird];
public static major1nv = [Intervals.minorThird, Intervals.perfectFourth];
public static major2nv = [Intervals.perfectFourth, Intervals.majorThird];
public static minor1nv = [Intervals.majorThird, Intervals.perfectFourth];
public static minor2nv = [Intervals.perfectFourth, Intervals.minorThird];
}
|
<?php
namespace PrestaShop\PSTAF;
use PrestaShop\PSTAF\Helper\FileSystem as FS;
class ConfigurationFile implements Util\DataStoreInterface
{
private $path;
private $options;
private static $instances = [];
public function __construct($path)
{
$this->path = $path;
$this->options = new Util\DataStore();
if (file_exists($path)) {
$data = json_decode(file_get_contents($path), true);
$this->update($data);
}
if (!$this->get("shop.filesystem_path")) {
$this->set("shop.filesystem_path", realpath(dirname($this->path)));
}
}
public function update($options)
{
foreach ($options as $key => $value) {
$this->set($key, $value);
}
return $this;
}
public function save()
{
file_put_contents($this->path, json_encode($this->options->toArray(), JSON_PRETTY_PRINT));
}
public function get($value)
{
return $this->options->get($value);
}
public function set($key, $value)
{
$this->options->set($key, $value);
return $this;
}
public function toArray()
{
return $this->options->toArray();
}
/**
* Returns a key that may represent a relative path
* relative to $this->path as an absolute path
* @param boolean $ensure_exists throw exception if final path does not exist
* @return string
*/
public function getAsAbsolutePath($key, $ensure_exists = true)
{
$path = $this->get($key);
if (!$path)
throw new \Exception("Configuration key `$key` not found in `{$this->path}`.");
if (!FS::isAbsolutePath($path))
$path = realpath(FS::join(dirname($this->path), $path));
if ($ensure_exists && !file_exists($path))
throw new \Exception("File or folder `$path` doesn't exist!");
return $path;
}
public static function getDefaultPath()
{
return 'pstaf.conf.json';
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Volo.Abp.Application.Dtos;
namespace Bamboo.Filter
{
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
public class FilterBase: PagedAndSortedResultRequestDto
{
public int Page { get; set; } = 0;
public int Size { get; set; } = 0;
public string Keyword { get; set; }
public string Format { get; set; }
public List<KeyValuePair<string, string>> OrderBy { get; set; }
public string ToUrlEncoded()
{
var keyValueContent = ToKeyValue(this);
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
var urlEncodedString = formUrlEncodedContent.ReadAsStringAsync().GetAwaiter().GetResult();
return urlEncodedString;
}
public static string ToUrlEncoded(object filter)
{
var keyValueContent = ToKeyValue(filter);
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
var urlEncodedString = formUrlEncodedContent.ReadAsStringAsync().GetAwaiter().GetResult();
return urlEncodedString;
}
/// https://geeklearning.io/serialize-an-object-to-an-url-encoded-string-in-csharp/
public static IDictionary<string, string> ToKeyValue(object metaToken)
{
if (metaToken == null)
{
return null;
}
JToken token = metaToken as JToken;
if (token == null)
{
return ToKeyValue(JObject.FromObject(metaToken));
}
if (token.HasValues)
{
var contentData = new Dictionary<string, string>();
foreach (var child in token.Children().ToList())
{
var childContent = ToKeyValue(child);
if (childContent != null)
{
contentData = contentData.Concat(childContent)
.ToDictionary(k => k.Key, v => v.Value);
}
}
return contentData;
}
var jValue = token as JValue;
if (jValue?.Value == null)
{
return null;
}
var value = jValue?.Type == JTokenType.Date ?
jValue?.ToString("o", CultureInfo.InvariantCulture) :
jValue?.ToString(CultureInfo.InvariantCulture);
return new Dictionary<string, string> { { token.Path, value } };
}
}
}
|
package com.example.web.wbfitness;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link TipsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link TipsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class TipsFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_TITLE = "Title";
private static final String ARG_STEPS = "Steps";
private static final String ARG_SOURCES = "Sources";
private String mTitle;
private String mSteps;
private String mSource;
private OnFragmentInteractionListener mListener;
public TipsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param title Parameter 1.
* @param steps Parameter 2.
* @return A new instance of fragment TipsFragment.
*/
// TODO: Rename and change types and number of parameters
public static TipsFragment newInstance(String title, String steps, String sources) {
TipsFragment fragment = new TipsFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_STEPS, steps);
args.putString(ARG_SOURCES, sources);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mTitle = getArguments().getString(ARG_TITLE);
mSteps = getArguments().getString(ARG_STEPS);
mSource = getArguments().getString(ARG_SOURCES);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tips, container, false);
TextView tipTitle = view.findViewById(R.id.tipTitle);
TextView tipSteps = view.findViewById(R.id.tipSteps);
Button sourceButton = view.findViewById(R.id.sourceButton);
if(mTitle != null) {
tipTitle.setText(mTitle);
}
if(mSteps != null) {
tipSteps.setText(Html.fromHtml(mSteps));
}
if(mSource != null) {
sourceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Declare the intent and set data with website
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(mSource));
// //Decide whether the user's phone has related software to run this functionality
if(intent.resolveActivity(getActivity().getPackageManager()) != null){
startActivity(intent);
}
else{
Toast.makeText(getContext(),
"You do not have the correct software.",
Toast.LENGTH_SHORT).show();
}
}
});
}
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
|
import {Rule} from '../Rule';
import {RuleConfig} from '../config/RuleConfig';
import {RULE_DICTIONARY} from './index';
import {PACK} from './SimpleRulePack';
interface RuleDictionary {
[key: string]: (conf: RuleConfig) => Rule;
}
export class RuleFactory {
static readonly RULES: RuleDictionary = {
...RULE_DICTIONARY,
...PACK,
};
static create(config: RuleConfig): Rule {
const factory = RuleFactory.RULES[config.type];
if (factory) {
return factory(config);
}
throw {
message: `Can't find any rule of type ${config.type}`,
};
}
static register(ruletype: string, factory: (conf: RuleConfig) => Rule) {
RuleFactory.RULES[ruletype] = factory;
}
}
|
#!/bin/bash
if [ ! $1 ]; then
echo "usage: $0 name"
exit
fi
NAME=$1
docker rm -f $NAME 2>/dev/null
docker run --name $NAME --hostname $NAME --restart=always -p 32777:27017 -v `pwd`/session:/data/db -d mongo
|
using System;
using System.IO;
using KoiCatalog.Plugins.FileIO;
using FileInfo = KoiCatalog.Plugins.FileIO.FileInfo;
namespace KoiCatalog.Plugins.Koikatu
{
[FileHandlerDependency(typeof(FileInfoFileHandler))]
public sealed class KoikatuFileHandler : FileHandler
{
public override void HandleFile(FileLoader loader)
{
if (!Path.GetExtension(loader.Source.AbsolutePath)
.Equals(".png", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
var fileInfo = loader.Entity.GetComponent(FileInfo.TypeCode);
ChaFile chaFile;
try
{
using (var stream = fileInfo.OpenRead())
{
chaFile = new ChaFile(stream);
}
}
catch (Exception)
{
return;
}
var card = loader.Entity.AddComponent(KoikatuCharacterCard.TypeCode);
card.Initialize(chaFile);
}
}
}
|
<?php
/*
* This file is part of the IPTools package.
*
* (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Tests\Unit;
use \Longman\IPTools\Ip;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <[email protected]>
* @copyright Avtandil Kikabidze <[email protected]>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class IpTest extends TestCase
{
/**
* @test
*/
public function test0()
{
$status = Ip::isValid('192.168.1.1');
$this->assertTrue($status);
$status = Ip::isValid('192.168.1.255');
$this->assertTrue($status);
$status = Ip::isValidv4('192.168.1.1');
$this->assertTrue($status);
$status = Ip::isValid('2001:0db8:85a3:08d3:1319:8a2e:0370:7334');
$this->assertTrue($status);
$status = Ip::isValidv4('2001:0db8:85a3:08d3:1319:8a2e:0370:7334');
$this->assertFalse($status);
$status = Ip::isValidv6('2001:0db8:85a3:08d3:1319:8a2e:0370:7334');
$this->assertTrue($status);
$status = Ip::isValid('192.168.1.256');
$this->assertFalse($status);
$status = Ip::isValid('2001:0db8:85a3:08d3:1319:8a2e:0370:733432');
$this->assertFalse($status);
}
/**
* @test
*/
public function test1()
{
$status = Ip::match('192.168.1.1', '192.168.0.*');
$this->assertFalse($status);
$status = Ip::match('192.168.1.1', '192.168.0/24');
$this->assertFalse($status);
$status = Ip::match('192.168.1.1', '192.168.0.0/255.255.255.0');
$this->assertFalse($status);
}
/**
* @test
*/
public function test2()
{
$status = Ip::match('192.168.1.1', '192.168.*.*');
$this->assertTrue($status);
$status = Ip::match('192.168.1.1', '192.168.1/24');
$this->assertTrue($status);
$status = Ip::match('192.168.1.1', '192.168.1.1/255.255.255.0');
$this->assertTrue($status);
}
/**
* @test
*/
public function test3()
{
$status = Ip::match('192.168.1.1', '192.168.1.1');
$this->assertTrue($status);
}
/**
* @test
*/
public function test4()
{
$status = Ip::match('192.168.1.1', '192.168.1.2');
$this->assertFalse($status);
}
/**
* @test
*/
public function test5()
{
$status = Ip::match('192.168.1.1', array('192.168.123.*', '192.168.123.124'));
$this->assertFalse($status);
$status = Ip::match('192.168.1.1', array('122.128.123.123', '192.168.1.*', '192.168.123.124'));
$this->assertTrue($status);
}
/**
* @test
* @expectedException \InvalidArgumentException
*/
public function test6()
{
$status = Ip::match('192.168.1.256', '192.168.1.2');
}
/**
* @test
*/
public function test7()
{
$status = Ip::match('192.168.5.5', '192.168.5.1-192.168.5.10');
$this->assertTrue($status);
$status = Ip::match('192.168.5.5', '192.168.1.1-192.168.10.10');
$this->assertTrue($status);
$status = Ip::match('192.168.5.5', '192.168.6.1-192.168.6.10');
$this->assertFalse($status);
}
/**
* @test
*/
public function test8()
{
$status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652', '2001:cdba:0000:0000:0000:0000:3257:*');
$this->assertTrue($status);
$status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652', '2001:cdba:0000:0000:0000:0000:*:*');
$this->assertTrue($status);
$status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:9652',
'2001:cdba:0000:0000:0000:0000:3257:1234-2001:cdba:0000:0000:0000:0000:3257:9999');
$this->assertTrue($status);
$status = Ip::match('2001:cdba:0000:0000:0000:0000:3258:9652', '2001:cdba:0000:0000:0000:0000:3257:*');
$this->assertFalse($status);
$status = Ip::match('2001:cdba:0000:0000:0000:1234:3258:9652', '2001:cdba:0000:0000:0000:0000:*:*');
$this->assertFalse($status);
$status = Ip::match('2001:cdba:0000:0000:0000:0000:3257:7778',
'2001:cdba:0000:0000:0000:0000:3257:1234-2001:cdba:0000:0000:0000:0000:3257:7777');
$this->assertFalse($status);
}
/**
* @test
*/
public function test9()
{
$long = Ip::ip2long('192.168.1.1');
$this->assertEquals('3232235777', $long);
$dec = Ip::long2ip('3232235777');
$this->assertEquals('192.168.1.1', $dec);
$long = Ip::ip2long('fe80:0:0:0:202:b3ff:fe1e:8329');
$this->assertEquals('338288524927261089654163772891438416681', $long);
$dec = Ip::long2ip('338288524927261089654163772891438416681', true);
$this->assertEquals('fe80::202:b3ff:fe1e:8329', $dec);
}
/**
* @test
*/
public function test_match_range()
{
$range = Ip::matchRange('192.168.100.', '192.168..');
$this->assertTrue($range);
$range = Ip::matchRange('192.168.1.200', '192.168.1.');
$this->assertTrue($range);
$range = Ip::matchRange('192.168.1.200', '192.168.2.');
$this->assertFalse($range);
}
public function testLocal()
{
$status = Ip::isLocal('192.168.5.5');
$this->assertTrue($status);
$status = Ip::isLocal('fe80::202:b3ff:fe1e:8329');
$this->assertTrue($status);
}
/**
* @test
*/
public function testRemote()
{
$status = Ip::isRemote('8.8.8.8');
$this->assertTrue($status);
}
}
|
#!/usr/bin/env python3
import os
ret = os.system("git add .")
if(ret!=0):
print("Error running the previous command")
message = input("Please enter the commit message: ")
ret = os.system("git commit -m \"" +str(message)+"\"")
ret = os.system("git push origin ; git push personal")
|
package no.nav.klage.search.clients.ereg
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
@JsonIgnoreProperties(ignoreUnknown = true)
data class Organisasjon(
val navn: Navn,
val organisasjonsnummer: String,
val type: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
data class Navn(
val navnelinje1: String?,
val navnelinje2: String?,
val navnelinje3: String?,
val navnelinje4: String?,
val navnelinje5: String?,
val redigertnavn: String?
) {
fun sammensattNavn(): String =
listOfNotNull(navnelinje1, navnelinje2, navnelinje3, navnelinje4, navnelinje5).joinToString(separator = " ")
}
|
<section class="nav">
<div class="container">
<nav>
<a href="{{ route('home') }}" class="{{ $nav->match('home') }}">Главная</a>
<a href="{{ route('docs') }}" class="{{ $nav->match('docs') }}">Документаця</a>
<a href="{{ route('articles') }}" class="{{ $nav->match('articles') }}">Статьи</a>
<a href="#">Пакеты</a>
<a href="#">Работа</a>
<a href="#" class="hidden-sm">Pastebin</a>
<a href="#" class="ideas hidden-sm"></a>
</nav>
</div>
</section>
|
// Copyright 2021 TFCloud Co.,Ltd. All rights reserved.
// This source code is licensed under Apache-2.0 license
// that can be found in the LICENSE file.
package messaging
type ChannelType string
const (
SMS ChannelType = "sms"
Email ChannelType = "email"
)
|
## EventForm Component
A component that handles event creation.
### Example
```js
<EventForm
{...fields}
invalid={invalid}
onAddGuest={this.handleAddingGuest}
onRemoveGuest={this.handleRemovingGuest}
guestList={guestList}
eventTypes={eventTypes}
pastHosts={hosts}
pastGuests={guests}
onSubmit={this.handleSubmit}
/>
```
### Props
| Prop | Type | Default | Possible Values
| ------------- | -------- | ----------- | ---------------------------------------------
| **onSubmit** | Func | | Any function value
| **pastGuests** | Array | | An array of past guests
| **eventTypes** | Array | | An array of event types
| **guestList** | Array | | The current guest list for the submission
| **onRemoveGuest** | Func | | Any function value
| **onAddGuest** | Func | | Any function value
| **invalid** | Bool | | Boolean to determine if the form is valid or not
|
/* --------------------------------------------------------------------------------
Version history
--------------------------------------------------------------------------------
0.1.0 - initial version October 2014 Mark Farrall
-------------------------------------------------------------------------------- */
angular.module('csDumb', [
'ngRoute',
'csApi',
'ui.bootstrap',
'ui.bootstrap.modal',
'restangular',
'browse'
]);
angular.module('csDumb').config(function($routeProvider) {
$routeProvider.
when('/browse', { templateUrl: 'views/browse/browse.html', controller: 'BrowseController' }).
when('/browse/:id', { templateUrl: 'views/browse/browse.html', controller: 'BrowseController' }).
otherwise({ redirectTo: '/browse' });
});
angular.module('csDumb').run(function(appConfig, browseConfig, csApiConfig) {
// set the title
/*var appCustom = {
title: 'A new title'
};
appConfig.configure(appCustom);*/
// configure the browse module
/*var browseCustom = {
startNode: 53912
};
browseConfig.configure(browseCustom);*/
});
|
import {ImageStyle, TextStyle, ViewStyle} from 'react-native';
export type Breakpoints = 'sm' | 'md' | 'lg' | 'xlg' | 'max';
export type BreakpointLength = {min: number; max: number};
export type BreakpointEntries = [Breakpoints, BreakpointLength][];
export type Media = Record<Breakpoints, {min: boolean; max: boolean}> & {current: string};
export type Scale = {width: number; height: number; font: number};
export type Orientation = 'horizontal' | 'vertical';
export type ResponsiveFont = (value: number) => number;
export type ResponsiveWidth = (value: number) => number;
export type ResponsiveHeight = (value: number) => number;
export type ResponsiveStyle = {rw: ResponsiveFont; rh: ResponsiveHeight; rf: ResponsiveFont};
export type Styles<T> = {[P in keyof T]: ViewStyle | TextStyle | ImageStyle};
export type StylesFunction<T> = (params: ResponsiveStyle) => T;
|
import { validatePattern } from "utils/validations";
export const delegateRegistration = (t: any) => ({
username: (usernames: string[]) => ({
required: t("COMMON.VALIDATION.FIELD_REQUIRED", {
field: t("COMMON.DELEGATE_NAME"),
}),
maxLength: {
value: 20,
message: t("COMMON.VALIDATION.MAX_LENGTH", {
field: t("COMMON.DELEGATE_NAME"),
maxLength: 20,
}),
},
validate: {
pattern: (value: string) => validatePattern(t, value, /[a-z0-9!@$&_.]+/),
unique: (value: string) =>
!usernames.includes(value) || t("COMMON.VALIDATION.EXISTS", { field: t("COMMON.DELEGATE_NAME") }),
},
}),
});
|
package jug.workshops.poligon.typed
import akka.actor.typed.scaladsl.Behaviors
import akka.actor.typed.{ActorRef, ActorSystem, Behavior, Terminated}
import scala.concurrent.Await
object ChatRoom {
sealed trait Command
final case class GetSession(screenName: String, replyTo: ActorRef[SessionEvent]) extends Command
private final case class PostSessionMessage(screenName: String, message: String) extends Command
sealed trait SessionEvent
final case class SessionGranted(handle: ActorRef[PostMessage]) extends SessionEvent
final case class SessionDenied(reason: String) extends SessionEvent
final case class MessagePosted(screenName: String, message: String) extends SessionEvent
final case class PostMessage(message: String)
val behavior:Behavior[Command] = chatRoom(List.empty)
private def chatRoom(sessions: List[ActorRef[SessionEvent]]): Behavior[Command] =
Behaviors.receive[Command] { (ctx, msg) =>
msg match {
case GetSession(screenName, client) =>
val wrapper = ctx.messageAdapter{
p: PostMessage => PostSessionMessage(screenName, p.message)
}
client ! SessionGranted(wrapper)
chatRoom(client :: sessions)
case PostSessionMessage(screenName, message) =>
val mp = MessagePosted(screenName,message)
sessions foreach (_ ! mp)
Behaviors.same
}
}
val gabbler = Behaviors.receive[SessionEvent]{ (_,msg) =>
msg match {
case SessionGranted(handle) =>
handle ! PostMessage("Hello World!")
Behaviors.same
case MessagePosted(screenName,message) =>
println(s"message has been posted by '$screenName': $message")
Behaviors.stopped
case unsupported => throw new RuntimeException(s"received $unsupported")
}
}
def main(args: Array[String]): Unit = {
val root: Behavior[String] =Behaviors.setup{ ctx =>
val chatroom: ActorRef[Command] =ctx.spawn(behavior,"chatroom")
val gabblerRef: ActorRef[SessionEvent] =ctx.spawn(gabbler,"gabbler")
ctx.watch(gabblerRef)
Behaviors.receivePartial[String]{
case (_, "go") =>
chatroom ! GetSession("Gabber",gabblerRef)
Behaviors.same
}.receiveSignal{
case (_,Terminated(ref)) =>
println(s"$ref is terminated")
Behaviors.stopped
}
}
val system = ActorSystem(root, "chatroom")
system ! "go"
import scala.concurrent.duration._
Await.result(system.whenTerminated, 3.seconds)
}
}
|
import time
anoAtual = int(time.strftime('%Y', time.localtime()))
anoNasc = int(input('Digite o ano que você nasceu: '))
idade = anoAtual - anoNasc
if(idade == 18):
print(f'Você tem {idade} anos. Chegou a hora de se alistar')
elif(idade > 18):
print(f'Passou {idade - 18} anos da hora de se alistar')
elif(idade < 18):
print(f'Ainda não é hora de se alistar. Falta {18 - idade} anos')
|
# DT models are widely used for classification & regression tasks.
# Essentially, they learn a hierarchy of if/else questions, leading to a decision.
# if/else questions are called "tests"
# tests for continuous data are: "Is feature X1 larger than value M?"
import matplotlib.pyplot as plt
import mglearn
import numpy as np
from sklearn.datasets import make_moons
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
# Moon dataset parameters.
moon_ds_size = 100
moon_ds_noise = 0.15
X_moons, y_moons = make_moons(n_samples=moon_ds_size, noise=moon_ds_noise, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X_moons, y_moons, random_state=42)
# print(X_moons.shape) # (100, 2)
# print(y_moons.shape) # (100,)
moons_feature_1 = X_moons[:, 0]
moons_feature_2 = X_moons[:, 1]
# plt.scatter(moons_feature_1, moons_feature_2, c=y_moons)
# plt.title("sklearn.datasets.make_moons")
# plt.show()
# Implement decision tree to classification problem.
tree_model = DecisionTreeClassifier()
tree_model.fit(X_train, y_train)
y_predict = tree_model.predict(X_test)
print(accuracy_score(y_test, y_predict))
print(tree_model.score(X_train, y_train))
print(tree_model.score(X_test, y_test))
n_features = X_moons.shape[1]
features_names = ("f1", "f2")
for i, color in zip(range(n_features), "ry"):
idx = np.where(y_moons == i)
plt.scatter(
X_moons[idx, 0], X_moons[idx, 1],
c=color, label=features_names[i], edgecolor='black', s=15
)
plt.show() # ???
mglearn.plots.plot_tree_progressive()
plt.show()
|
use std::borrow::Cow;
use std::env;
use std::fs::File;
use std::io::{stdin, stdout, BufRead, BufReader, Read, Write};
use rand::seq::SliceRandom;
use rand::thread_rng;
trait Rule {
// returns the original string to replace
fn original(&self) -> Cow<str>;
// returns the string to be substituted.
// Allowed to have side-effects and should only be called once for each substitution.
fn substitution(&self) -> Cow<str>;
}
// substitutes 'original' for 'substitute'
#[derive(Clone, Debug)]
struct Substitution {
original: Box<str>,
substitute: Box<str>,
}
impl Substitution {
fn new(original: &str, substitute: &str) -> Self {
Substitution {
original: original.to_string().into_boxed_str(),
substitute: substitute.to_string().into_boxed_str(),
}
}
}
impl Rule for Substitution {
fn original(&self) -> Cow<str> {
Cow::Borrowed(&self.original)
}
fn substitution(&self) -> Cow<str> {
Cow::Borrowed(&self.substitute)
}
}
// replaces 'original' with line from stdin
#[derive(Clone, Debug)]
struct Input {
original: Box<str>,
}
impl Input {
fn new(original: &str) -> Self {
Input {
original: original.to_string().into_boxed_str(),
}
}
}
impl Rule for Input {
fn original(&self) -> Cow<str> {
Cow::Borrowed(&self.original)
}
fn substitution(&self) -> Cow<str> {
let mut out = String::new();
stdin().read_line(&mut out).unwrap();
out = out[..out.len() - 1].to_string();
Cow::Owned(out)
}
}
// replaces 'original' with the null string and outputs 'output' to stdout
#[derive(Clone, Debug)]
struct Output {
original: Box<str>,
output: Box<str>,
}
impl Output {
fn new(original: &str, output: &str) -> Self {
let mut output = output;
if output == "" {
output = "\n";
}
Output {
original: original.to_string().into_boxed_str(),
output: output.to_string().into_boxed_str(),
}
}
}
impl Rule for Output {
fn original(&self) -> Cow<str> {
Cow::Borrowed(&self.original)
}
fn substitution(&self) -> Cow<str> {
stdout().lock().write_all(&self.output.as_bytes()).unwrap();
Cow::Owned("".to_string())
}
}
fn main() -> Result<(), std::io::Error> {
let file_name = env::args().nth(1).expect("Missing program file argument!");
let file = File::open(file_name)?;
let mut buf_reader = BufReader::new(file);
let rule_list = parse_rules(&mut buf_reader)?;
let mut initial_state = String::new();
buf_reader.read_to_string(&mut initial_state)?;
initial_state = initial_state.replace("\n", "");
run_program(rule_list, initial_state);
Ok(())
}
// parses and returns list of rules, leaving the buffer at the first line after the list terminator
fn parse_rules(buf_reader: &mut BufReader<File>) -> Result<Box<[Box<dyn Rule>]>, std::io::Error> {
let mut out: Vec<Box<dyn Rule>> = vec![];
loop {
let mut next_line = String::new();
if buf_reader.read_line(&mut next_line).unwrap() == 0 {
panic!("Invalid input file!");
};
next_line = next_line[..next_line.len() - 1].to_string();
if let Some((original, substitute)) = get_rule_params(&next_line) {
if original.trim() == "" && substitute.trim() == "" {
// reached end of rule list
break;
} else if original.trim() == "" && substitute.trim() != "" {
panic!("Invalid syntax!");
} else if substitute == ":::" {
out.push(Box::new(Input::new(original)));
} else if substitute.starts_with('~') {
out.push(Box::new(Output::new(original, &substitute[1..])));
} else {
out.push(Box::new(Substitution::new(original, substitute)));
}
}
}
Ok(out.into_boxed_slice())
}
// returns the rule parameters as '(original, substitute)' or None if not a valid rule
fn get_rule_params(line: &str) -> Option<(&str, &str)> {
if let Some(i) = line.find("::=") {
let (head, tail) = line.split_at(i);
Some((head, &tail[3..]))
} else {
None
}
}
// runs Thue program using collected 'rule_list' and 'initial_state'
fn run_program(mut rule_list: Box<[Box<dyn Rule>]>, initial_state: String) {
let mut rng = thread_rng();
let mut state = initial_state;
let mut running = true;
while running {
rule_list.shuffle(&mut rng);
running = false;
for rule in rule_list.iter() {
let original = rule.original();
if let Some(index) = state
.match_indices(original.as_ref())
.map(|(i, _)| i)
.collect::<Vec<usize>>()
.choose(&mut rng)
{
running = true;
state.replace_range(*index..index + original.len(), &rule.substitution());
break;
}
}
}
print!("\n");
}
|
---
title: Postgres
authors: emesika
---
# Postgres
This page is obsolete.
## Installation
We are using version 9.1.x
## Authentication
```
Trust
Password
GSSAPI
SSPI
Kerberos
Ident
Peer
LDAP
RADIUS
Certificate
PAM
```
details:
[Authentication Methods](http://www.postgresql.org/docs/9.1/static/auth-methods.html)
## Creating a new user
[Create Role](http://www.postgresql.org/docs/9.1/static/sql-createrole.html)
[Create User](http://www.postgresql.org/docs/9.0/static/sql-createuser.html)
[The password file](http://www.postgresql.org/docs/9.0/static/libpq-pgpass.html)
## Configuration
Default postgres configuration files are under `/var/lib/pgsql/data`
### postgresql.conf
[defaults](http://www.postgresql.org/docs/current/static/view-pg-settings.html)
[reset](http://www.postgresql.org/docs/current/static/sql-reset.html)
### Reload configuration
If you are making modifications to the Postgres configuration file postgresql.conf (or similar), and you want to new settings to take effect without needing to restart the entire database, there are two ways to accomplish this.
option 1
```bash
su - postgres /usr/bin/pg_ctl reload option 2
echo "SELECT pg_reload_conf();" | psql -U <user> <database>
```
### Connection
[Connection parameters](http://www.postgresql.org/docs/current/static/runtime-config-connection.html)
### Remote access (listen_addresses)
[`pg_hba.conf`](http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html)
### max_connections
The maximum number of client connections allowed.
This is very important to some of the below parameters (particularly work_mem) because there are some memory resources that are or can be allocated on a per-client basis,
so the maximum number of clients suggests the maximum possible memory use.
Generally, PostgreSQL on good hardware can support a few hundred connections.
If you want to have thousands instead, you should consider using connection pooling software to reduce the connection overhead.
### shared_buffers
The shared_buffers configuration parameter determines how much memory is dedicated to PostgreSQL use for caching data.
One reason the defaults are low because on some platforms (like older Solaris versions and SGI) having large values requires invasive action like recompiling the kernel.
Even on a modern Linux system, the stock kernel will likely not allow setting shared_buffers to over 32MB without adjusting kernel settings first.
If you have a system with 1GB or more of RAM, a reasonable starting value for shared_buffers is 1/4 of the memory in your system.
If you have less ram you'll have to account more carefully for how much RAM the OS is taking up, closer to 15% is more typical there.
There are some workloads where even larger settings for shared_buffers are effective, but given the way PostgreSQL also relies on the operating system cache it's unlikely
you'll find using more than 40% of RAM to work better than a smaller amount.
### work_mem
Specifies the amount of memory to be used by internal sort operations and hash tables before writing to temporary disk files.
The value defaults to one megabyte (1MB). Note that for a complex query, several sort or hash operations might be running in parallel;
each operation will be allowed to use as much memory as this value specifies before it starts to write data into temporary files.
Also, several running sessions could be doing such operations concurrently.
Therefore, the total memory used could be many times the value of work_mem; it is necessary to keep this fact in mind when choosing the value.
Sort operations are used for ORDER BY, DISTINCT, and merge joins. Hash tables are used in hash joins, hash-based aggregation, and hash-based processing of IN subqueries.
### maintenance_work_mem
Specifies the maximum amount of memory to be used by maintenance operations, such as `VACUUM`, `CREATE INDEX`, and `ALTER TABLE ADD FOREIGN KEY`.
It defaults to 16 megabytes (16MB). Since only one of these operations can be executed at a time by a database session, and an installation normally doesn't have many of them running concurrently,
it's safe to set this value significantly larger than `work_mem`.
Larger settings might improve performance for vacuuming and for restoring database dumps.
### synchronous_commit
Asynchronous commit is an option that allows transactions to complete more quickly, at the cost that the most recent transactions may be lost if the database should crash.
In many applications this is an acceptable trade-off.
Asynchronous commit introduces the risk of data loss.
There is a short time window between the report of transaction completion to the client and the time that the transaction is truly committed (that is,
it is guaranteed not to be lost if the server crashes).
The risk that is taken by using asynchronous commit is of data loss, not data corruption.
If the database should crash, it will recover by replaying WAL up to the last record that was flushed.
The database will therefore be restored to a self-consistent state, but any transactions that were not yet flushed to disk will not be reflected in that state.
The net effect is therefore loss of the last few transactions.
The user can select the commit mode of each transaction, so that it is possible to have both synchronous and asynchronous commit transactions running concurrently.
This allows flexible trade-offs between performance and certainty of transaction durability.
### Guidlines for Dedicated/Shared server
For the following , a good understanding of the database clock lifecycle is needed.
```
page request --> changes --> dirty --> commit to WAL --> Statistics (pg_stat_user_tables etc.) (*) --> Write to disk & clean dirty flag (*)
(*) - async
```
Dedicated
```
logging can be more verbose
shared_buffers - 25% of RAM
work_mem should be `<OS cache size>` / (max_connections * 2)
maintenance_work_mem - 50MB per each 1GB of RAM
checkpoint_segments - at least 10 [1]
checkpoint_timeout
wal_buffers - 16MB [2]
```
[1] [`pg_buffercache`](http://www.postgresql.org/docs/9.1/static/pgbuffercache.html) - <http://www.postgresql.org/docs/9.1/static/pgbuffercache.html>
[1]: <http://www.postgresql.org/docs/9.1/static/pgbuffercache.html>
[2] [WAL Configuration](https://www.postgresql.org/docs/9.1/wal-configuration.html) - <https://www.postgresql.org/docs/9.1/wal-configuration.html>
[2]: <http://www.postgresql.org/docs/9.1/static/wal-configuration.html>
Shared
```
reduce logging
shared_buffers - 10% of RAM
be very stingy about increasing work_mem
all other recomendations from the Dedicated section may apply
```
### pgtune
pgtune takes the default postgresql.conf and expands the database server to be as powerful as the hardware it's being deployed on.
[How to tune your database](http://web.archive.org/web/20150416110332/http://sourcefreedom.com/tuning-postgresql-9-0-with-pgtune/)
## VACUUM
Cleans up after old transactions, including removing information that is no longer visible and reuse free space.
ANALYSE looks at tables in the database and collects statistics about them like number of distinct values etc.
Many aspects of query planning depends on this statistics data being accurate.
From 8.1 , there is a autovaccum daemon that runs in the background and do this work automatically.
## Logging
General logging is important especially if you have unexpected behaviour and you want to find the reason for that
The default logging level is only Errors but this can be easily changed.
### log_line_prefix
Controls the line prefix of each log message.
```
%t timestamp
%u user
%r remote host connection
%d database connection
%p pid of connection
```
### log_statement
Controls which statements are logged
```
none
ddl
mod
all
```
### log_min_duration_statement
Controls how long should a query being executed to be logged
Very usefull to find most expensive queries
|
-- 削除対象の日付を設定
DECLARE @dt date = (SELECT DATEADD(dd, -31, GETDATE()))
-- バックアップ履歴レコードの削除
EXEC msdb.dbo.sp_delete_backuphistory @dt
-- ジョブ実行履歴レコードの削除
EXEC msdb.dbo.sp_purge_jobhistory @oldest_date= @dt
-- メンテナンスプラン履歴レコードの削除
EXECUTE msdb..sp_maintplan_delete_log null,null, @dt
|
import { all } from 'redux-saga/effects';
import categoriesSaga from './categoriesSaga';
import cookbookSaga from './cookbookSaga';
function* rootSaga() {
yield all([categoriesSaga(), cookbookSaga()]);
}
export default rootSaga;
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WanderBehavior : SteeringBehavior
{
[SerializeField] private float mWanderDistance;
[SerializeField] private float mWanderRadius;
[SerializeField] private float mWanderJitter;
private float mWanderAngle;
private void Awake()
{
mWanderAngle = Random.Range(-Mathf.PI * 2, Mathf.PI * 2);
}
// Steering Behavior Reference:
// https://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-wander--gamedev-1624
public override Vector3 Calculate(Agent agent)
{
// Calculate the circle center
Vector3 circleCenter;
if (Vector3.SqrMagnitude(agent.velocity) == 0.0f)
{
return Vector3.zero;
}
circleCenter = Vector3.Normalize(agent.velocity);
circleCenter *= mWanderDistance;
// Calculate the displacement force
Vector3 displacement = new Vector3(0.0f, -1.0f);
displacement *= mWanderRadius;
// Randomly change direction by making it change its current angle
float len = Vector3.Magnitude(displacement);
displacement.x = Mathf.Cos(mWanderAngle) * len;
displacement.y = Mathf.Sin(mWanderAngle) * len;
// Change wanderAngle a bit
mWanderAngle += Random.Range(-mWanderJitter, mWanderJitter);
// Calculate and return the wander force
Vector3 wanderForce = circleCenter + displacement;
return wanderForce;
}
}
|
package service
import (
"k8s.io/api/admission/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
)
var scheme = runtime.NewScheme()
var codecs = serializer.NewCodecFactory(scheme)
// ToAdmissionResponse is a helper function to create an AdmissionResponse
// with an embedded error
func ToAdmissionResponse(err error) *v1beta1.AdmissionResponse {
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
|
# PythonでGUIをつくろう─はじめてのQt for Python 3.3.4 サンプルコード
Qt for Python(PySide2)バージョン情報の出力 をおこないます。
|
import 'dart:convert';
import 'package:shelf/shelf.dart' as shelf;
class HttpResponse {
static shelf.Response get ok {
return shelf.Response.ok(
'Ok',
headers: <String, String>{
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
},
);
}
static shelf.Response get notFound {
final bytes = jsonEncode(<String, Object>{
'error': 'Not found',
}).codeUnits;
return shelf.Response.notFound(
bytes,
headers: <String, String>{
'Content-Length': bytes.length.toString(),
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
},
);
}
static shelf.Response internalServerError(Object error) {
final bytes = jsonEncode(<String, Object>{
'error': error.toString(),
}).codeUnits;
return shelf.Response.internalServerError(
body: bytes,
headers: <String, String>{
'Content-Length': bytes.length.toString(),
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
},
);
}
}
|
import { useEffect, useState } from 'react';
import { RemoteParticipant } from 'twilio-video';
import useDominantSpeaker from '../useDominantSpeaker/useDominantSpeaker';
import useVideoContext from '../useVideoContext/useVideoContext';
export default function useParticipants() {
const { room } = useVideoContext();
const dominantSpeaker = useDominantSpeaker();
const [participants, setParticipants] = useState(Array.from(room.participants.values()));
// When the dominant speaker changes, they are moved to the front of the participants array.
// This means that the most recent dominant speakers will always be near the top of the
// ParticipantStrip component.
useEffect(() => {
if (dominantSpeaker) {
setParticipants(prevParticipants => [
dominantSpeaker,
...prevParticipants.filter(participant => participant !== dominantSpeaker),
]);
}
}, [dominantSpeaker]);
useEffect(() => {
const participantConnected = (participant: RemoteParticipant) => {
fetch(window.location.pathname.replace('Room', 'RoomInfo'))
.then(response => {
console.log(response);
return response.json();
})
.then(data => {
console.log(data);
return data;
})
.then(
data => {
(window as any).roomInfo = data;
},
error => {
// DO NOTHING
}
)
.then(() => {
setParticipants(prevParticipants => [...prevParticipants, participant]);
});
};
const participantDisconnected = (participant: RemoteParticipant) =>
setParticipants(prevParticipants => prevParticipants.filter(p => p !== participant));
room.on('participantConnected', participantConnected);
room.on('participantDisconnected', participantDisconnected);
return () => {
room.off('participantConnected', participantConnected);
room.off('participantDisconnected', participantDisconnected);
};
}, [room]);
return participants;
}
|
package com.patrykkosieradzki.theanimalapp
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.ktx.get
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfigSettings
import com.patrykkosieradzki.theanimalapp.domain.AppConfiguration
import timber.log.Timber
import java.util.concurrent.TimeUnit
interface RemoteConfigManager {
suspend fun checkMaintenanceMode(
onCompleteCallback: (Boolean) -> Unit,
onFailureCallback: (Exception) -> Unit
)
val maintenanceEnabled: Boolean
val maintenanceTitle: String
val maintenanceDescription: String
}
class RemoteConfigManagerImpl(
private val appConfiguration: AppConfiguration,
private val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig
) : RemoteConfigManager {
override val maintenanceEnabled = remoteConfig[IS_MAINTENANCE_MODE_KEY].asBoolean()
override val maintenanceTitle = remoteConfig[MAINTENANCE_TITLE_KEY].asString()
override val maintenanceDescription = remoteConfig[MAINTENANCE_DESCRIPTION_KEY].asString()
override suspend fun checkMaintenanceMode(
onCompleteCallback: (Boolean) -> Unit,
onFailureCallback: (Exception) -> Unit
) {
fetchAndActivate(
if (appConfiguration.debug) INSTANT else TWELVE_HOURS,
onCompleteCallback, onFailureCallback
)
}
private fun fetchAndActivate(
minimumFetchIntervalInSeconds: Long,
onCompleteCallback: (Boolean) -> Unit,
onFailureCallback: (Exception) -> Unit
) {
val remoteConfigSettings = remoteConfigSettings {
setMinimumFetchIntervalInSeconds(minimumFetchIntervalInSeconds)
fetchTimeoutInSeconds = FETCH_TIMEOUT_IN_SECONDS
}
remoteConfig.setConfigSettingsAsync(remoteConfigSettings).addOnCompleteListener {
remoteConfig.fetchAndActivate()
.addOnCompleteListener {
Timber.d("Remote Config fetched successfully")
onCompleteCallback.invoke(maintenanceEnabled)
}
.addOnFailureListener {
Timber.e(it, "Failure during Remote Config fetch")
onFailureCallback.invoke(it)
}
}
}
companion object {
const val IS_MAINTENANCE_MODE_KEY = "is_maintenance_mode"
const val MAINTENANCE_TITLE_KEY = "maintenance_title"
const val MAINTENANCE_DESCRIPTION_KEY = "maintenance_description"
const val FETCH_TIMEOUT_IN_SECONDS = 5L
val TWELVE_HOURS = TimeUnit.HOURS.toSeconds(12)
const val INSTANT = 0L
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PyramidNETRS232_TestApp_Simple
{
class Program
{
/// <summary>
/// Dead simple demo. The error handling and extra features have been omitted for simplicity.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Console.WriteLine("Enter port name in format: COMX");
var port = Console.ReadLine();
SingleBillValidator.Instance.Connect(port);
Console.WriteLine("Connected on port {0}", port);
Console.WriteLine("Press ESC to stop");
do
{
while (!Console.KeyAvailable) { }
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
Console.WriteLine("Quitting...");
SingleBillValidator.Instance.Disconnect();
}
}
}
|
require "socket"
require "uri"
require "json"
require "timeout"
require "digest"
Links = Hash.new
Struct.new("Response", :code, :status)
STATUS_CODES = {
200 => "200 OK",
301 => "301 Moved Permanently",
400 => "400 Bad Request",
403 => "403 Forbidden",
404 => "404 Not Found",
405 => "405 Method Not Allowed"
}
server = TCPServer.new('0.0.0.0', 2345)
def requestType(request_line)
request_uri = request_line.split(" ")[0]
end
def getPath(request_line)
request_uri = request_line.split(" ")[1]
path = URI.unescape(URI(request_uri).path)
end
def sendRedirect(socket, url, response)
socket.print "HTTP/1.1 "+getStatus(301)+"\r\n"+
"Location: "+url+"\r\n"+
"Content-Type: text/html\r\n"+
"Content-Length: #{response.bytesize}\r\n"+
"Connection: close\r\n"
socket.print "\r\n"
socket.close
end
def sendResponse(socket, response, code)
socket.print "HTTP/1.1 "+code+"\r\n"+
"Content-Type: application/json\r\n"+
"Content-Length: #{response.bytesize}\r\n"+
"Connection: close\r\n"
socket.print "\r\n"
socket.print response
socket.close
end
def getStatus(status)
code = STATUS_CODES.fetch(status, "500 Internal Server Error")
end
def getLink(code)
if code == ""
return ""
else
puts code
link = Links.fetch(code, "")
end
end
def getData(str)
hs = Hash.new
str.split("\n").map do |s|
b = s.split(": ")
hs[b[0]] = b[1]
end
end
def getCode(url)
Links.each do |key, value|
return key if value["url"] == url
end
t = Time.now.to_i.to_s
x = Digest::MD5.hexdigest t
code = x[-5..-1]
Links[code] = {"url" => url}
return code
end
loop do
socket = server.accept
request = socket.gets
path = getPath(request)
reqType = requestType(request)
if path == "/generate"
if reqType == "POST"
lines = []
begin
st = timeout(1) {
while line = socket.gets
if line == nil
puts "meme"
elsif line == ""
puts "lol"
break
else
lines.insert(-1, line.to_s)
end
end
}
rescue => error
begin
if lines == nil
puts "nil lines"
sendResponse(socket, Struct::Response.new(500, "500 Internal Server Error").to_h.to_json, getStatus(500))
else
p = lines.join("").to_s
if p == nil
sendResponse(socket, Struct::Response.new(500, "500 Internal Server Error").to_h.to_json, getStatus(500))
else
p = "{"+p.split("{")[1]
if p == nil
sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400))
else
data = JSON.parse(p)
if data
if data["url"] == nil
sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400))
elsif data["url"] == ""
sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400))
else
sendResponse(socket, Struct::Response.new(200, getCode(data["url"])).to_h.to_json, getStatus(200))
end
else
sendResponse(socket, Struct::Response.new(400, "400 Bad Request").to_h.to_json, getStatus(400))
end
end
end
end
rescue => error
puts error.message
puts error.backtrace
sendResponse(socket, Struct::Response.new(500, "500 Internal Server Error").to_h.to_json, getStatus(500))
end
end
else
sendResponse(socket, Struct::Response.new(405, "405 Method Not Allowed").to_h.to_json, getStatus(405))
end
else
path.sub! '/', ''
link = getLink(path)
if link == ""
sendResponse(socket, Struct::Response.new(404, "404 Not Found").to_h.to_json, getStatus(404))
else
sendRedirect(socket, "#{link['url']}", "301 Moved Permanently")
end
end
end
|
package top.chao.funding.bean;
public class TReturn {
private Integer id;
private Integer projectid;
private String type;
private Integer supportmoney;
private String content;
private Integer count;
private Integer signalpurchase;
private Integer purchase;
private Integer freight;
private String invoice;
private Integer rtndate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getProjectid() {
return projectid;
}
public void setProjectid(Integer projectid) {
this.projectid = projectid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
public Integer getSupportmoney() {
return supportmoney;
}
public void setSupportmoney(Integer supportmoney) {
this.supportmoney = supportmoney;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content == null ? null : content.trim();
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Integer getSignalpurchase() {
return signalpurchase;
}
public void setSignalpurchase(Integer signalpurchase) {
this.signalpurchase = signalpurchase;
}
public Integer getPurchase() {
return purchase;
}
public void setPurchase(Integer purchase) {
this.purchase = purchase;
}
public Integer getFreight() {
return freight;
}
public void setFreight(Integer freight) {
this.freight = freight;
}
public String getInvoice() {
return invoice;
}
public void setInvoice(String invoice) {
this.invoice = invoice == null ? null : invoice.trim();
}
public Integer getRtndate() {
return rtndate;
}
public void setRtndate(Integer rtndate) {
this.rtndate = rtndate;
}
}
|
#!/bin/bash
# I'm super lazy y'all
./main.sh --gin_config example_configs/biggan_posenc_imagenet32.gin \
--model_dir gs://octavian-training2/compare_gan/model/imagenet32/posenc \
--schedule eval_last \
$@
|
import INode, * as INodeUtil from './inode';
import File from './file';
import DiskDriver from './diskDriver/interface';
import Metadata, * as MetadataUtil from './metadata';
import BlockManager from './blockManager';
import INodeManager from './inodeManager';
export default class FileSystem {
static BLOCK_SIZE = 4096;
static INODE_SIZE = 128;
diskDriver: DiskDriver;
metadata: Metadata;
blockManager: BlockManager;
inodeManager: INodeManager;
createFileObject: (inode: INode) => File;
constructor(diskDriver: DiskDriver) {
this.diskDriver = diskDriver;
this.createFileObject = inode => new File(this, inode);
}
static async mkfs(diskDriver: DiskDriver,
rootNode: INode = INodeUtil.createEmpty(),
): Promise<FileSystem> {
// Create new metadata and write inode block list / block bitmap
let metadata: Metadata = {
version: 1,
bitmapId: 1,
blockListId: 2,
rootId: 3,
};
await diskDriver.write(0, MetadataUtil.encode(metadata));
// Populate bitmap node / file
let bitmapNode = INodeUtil.createEmpty();
bitmapNode.length = 3;
bitmapNode.pointers[0] = 1;
await diskDriver.write(128, INodeUtil.encode(bitmapNode));
let bitmapBlock = new Uint8Array(4096);
bitmapBlock.set([1, 2, 2]);
await diskDriver.write(4096, bitmapBlock);
// Populate block list node / file
let blockListNode = INodeUtil.createEmpty();
blockListNode.length = 12;
blockListNode.pointers[0] = 2;
await diskDriver.write(256, INodeUtil.encode(blockListNode));
let blockListBlock = new Uint8Array(4096);
blockListBlock.set([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15]);
await diskDriver.write(8192, blockListBlock);
// Populate root node
await diskDriver.write(384, INodeUtil.encode(rootNode));
return new FileSystem(diskDriver);
}
async init(): Promise<void> {
// Read metadata and read inode / block bitmap to buffer
this.metadata = MetadataUtil.decode(await this.diskDriver.read(0, 128));
this.blockManager = new BlockManager(this);
this.inodeManager = new INodeManager(this);
this.blockManager.init(await this.readFile(this.metadata.bitmapId));
this.inodeManager.init(await this.readFile(this.metadata.blockListId));
}
async close(): Promise<void> {
// Write metadata to disk
await this.diskDriver.write(0, MetadataUtil.encode(this.metadata));
}
async readBlock(
id: number, position?: number, size?: number,
): Promise<Uint8Array> {
let address = id * FileSystem.BLOCK_SIZE + (position || 0);
return this.diskDriver.read(address, size || FileSystem.BLOCK_SIZE);
}
async writeBlock(
id: number, position: number, buffer: Uint8Array,
): Promise<void> {
let address = id * FileSystem.BLOCK_SIZE + (position || 0);
return this.diskDriver.write(address, buffer);
}
async createFile(type: number = 0): Promise<File> {
// Get free inode and wrap file
let inode = await this.inodeManager.next();
inode.type = type;
inode.dirty = true;
return this.createFileObject(inode);
}
read(id: number): Promise<INode> {
// Read inode from disk, or buffer (if in cache)
return this.inodeManager.read(id);
}
async readFile(id: number): Promise<File> {
// Read inode and wrap with file
let inode = await this.inodeManager.read(id);
return this.createFileObject(inode);
}
async unlink(inode: INode): Promise<void> {
// Delete inode and mark on the bitmap
await this.inodeManager.unlink(inode);
}
async unlinkFile(file: File): Promise<void> {
// Delete whole data node
await file.truncate(0);
await this.inodeManager.unlink(file.inode);
}
setType(id: number, value: number): Promise<void> {
// Set bitmap data
return this.blockManager.setType(id, value);
}
}
|
import axios from 'axios';
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('agregar-cliente-component', require('./components/AgregarClienteComponent.vue').default);
Vue.component('editar-cliente-component', require('./components/EditarClienteComponent.vue').default);
Vue.component('modal-agregar', require('./components/ModalAgregar.vue').default);
Vue.component('modal-editar', require('./components/ModalEditar.vue').default);
const app = new Vue({
el: '#app',
data: {
clientes: [],
clienteEditar: {},
mostrarAgregar: false,
mostrarEdicion: false,
mostrarInformacion: false,
informacion: '',
busqueda: '',
alert: '',
showModal: false,
showModalEditar: false,
showModalImagen: false,
imagen: 'logotipo.jpg'
},
created() {
console.log(this.listarClientes())
},
mounted() {
console.log('mostrar imagen: '+this.mostrarImagen())
},
methods: {
listarClientes() {
axios.get('./api/listarClientes')
.then(response => this.clientes = response.data)
.catch(error => {
console.log(error.message + ' get: api/cliente');
})
.finally(
console.log(this.clientes)
);
},
/*editarCliente(cliente){
console.log('cargando cliente!');
console.log(cliente);
this.clienteEditar = cliente;
this.mostrarEdicion = true;
this.$nextTick(() => {
$('#ModalEditarCliente').modal('show');
});
},
cerrarEditar(){
$('#ModalEditarCliente').modal('hide');
this.$nextTick(() => {
this.mostrarEdicion = false;
});
},*/
borrarCliente(id) {
axios.post('./api/borrarCliente', {
id
}).then(res => {
this.listarClientes()
this.informacion = 'Cliente Borrado - STATUS PASO A 300',
this.mostrarInformacion = !this.mostrarInformacion
})
.catch(function (error) {
console.log(error)
})
.finally(
setTimeout(() => {
this.informacion = '',
this.mostrarInformacion = !this.mostrarInformacion
},3000)
);
},
busquedaClientes(busqueda) {
axios.get('./api/buscarClientes', {
params: {
busqueda
}
})
.then(
response => this.clientes = response.data
)
.catch(error => {
console.log(error.message + ' get: api/busquedaClientes');
});
},
cambiarInformacion() {
this.informacion = 'Cliente ACTUALIZADO',
this.mostrarInformacion = !this.mostrarInformacion,
setTimeout(() => {
this.informacion = '',
this.mostrarInformacion = !this.mostrarInformacion
},3000)
},
cambiarInformacionAgregar(error) {
this.informacion = error,
this.mostrarInformacion = !this.mostrarInformacion,
setTimeout(() => {
this.informacion = '',
this.mostrarInformacion = !this.mostrarInformacion
},3000)
},
cambioImagen() {
this.imagen = event.target.files[0];
},
getImage(event){
var formData = new FormData();
formData.append("imagenNueva", this.imagen);
axios.post('./api/cambiarImagen', formData)
.then(
response => this.imagen = response.data
)
.catch(error => {
console.log(error.message );
})
.finally(
this.close()
);
},
mostrarImagen() {
axios.get('./api/mostrarImagen')
.then(response => this.imagen = response.data)
.catch(error => {
console.log(error.message + ' error al mostrar imagen');
});
},
toggleModal () {
this.showModal = !this.showModal
},
toggleModalEdit (cliente) {
this.showModalEditar = !this.showModalEditar;
this.clienteEditar = cliente;
},
toggleModalImagen () {
this.showModalImagen = !this.showModalImagen
},
close() {
this.showModalImagen = false
},
updateColor(alert) {
this.alert = alert;
console.log(this.alert);
}
}
});
|
# Grid 栅格
采用24格划分的栅格系统
## 基本用法
通过 span 设置宽度占比,默认占 24 格即 100%。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<>
<Row>
<Col>
<div>col</div>
</Col>
</Row>
<Row>
<Col span={12}>
<div>col-12</div>
</Col>
<Col span={12}>
<div>col-12</div>
</Col>
</Row>
</>,
mountNode,
);
```
## 区块间隔
通过 Row 的 gutter 属性设置 Col 之间的水平间距。如果需要垂直间距,可以写成数组形式 [水平间距, 垂直间距]。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<>
<h4>水平间距</h4>
<Row gutter={6}>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
</Row>
<h4>水平间距, 垂直间距</h4>
<Row gutter={[6, 10]}>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={6}>
<div>col-6</div>
</Col>
<Col span={8}>
<div>col-8</div>
</Col>
<Col span={8}>
<div>col-8</div>
</Col>
<Col span={8}>
<div>col-8</div>
</Col>
</Row>
</>,
mountNode,
);
```
## 左间距
通过 offset 属性,设置 Col 的 margin-left。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<Row gutter={[0, 10]}>
<Col span={8}>
<div>col-8</div>
</Col>
<Col span={8} offset={8}>
<div>col-8 offset-8</div>
</Col>
<Col span={6} offset={6}>
<div>col-6 offset-6</div>
</Col>
<Col span={6} offset={6}>
<div>col-6 offset-6</div>
</Col>
</Row>,
mountNode,
);
```
## 左右偏移
通过 push 属性,设置 Col 的 左偏移; 通过 pull 属性,设置 Col 的 右偏移。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<Row>
<Col span={6} push={18}>
<div>col-6 push-18</div>
</Col>
<Col span={18} pull={6}>
<div>col-18 pull-6</div>
</Col>
</Row>,
mountNode
);
```
## 布局
通过 justify 属性,设置 Col 其在父节点里面的排版方式。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<>
<h4>justify start</h4>
<Row justify="start" className="row-bg">
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
</Row>
<h4>justify center</h4>
<Row justify="center" className="row-bg">
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
</Row>
<h4>justify end</h4>
<Row justify="end" className="row-bg">
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
</Row>
<h4>justify space-between</h4>
<Row justify="space-between" className="row-bg">
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
</Row>
<h4>justify space-around</h4>
<Row justify="space-around" className="row-bg">
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
<Col span={4}>
<div>col-4</div>
</Col>
</Row>
</>,
mountNode,
);
```
## 垂直对齐
通过 align 属性,设置 Col 的 垂直对齐方式。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<>
<h4>align top</h4>
<Row justify="center" align="top" className=" row-bg">
<Col span={8}>
<div className="col col-height-8">col-8</div>
</Col>
<Col span={8}>
<div>col-8</div>
</Col>
<Col span={8}>
<div className="col col-height-10">col-8</div>
</Col>
</Row>
<h4>align middle</h4>
<Row justify="center" align="middle" className=" row-bg">
<Col span={8}>
<div className="col col-height-8">col-8</div>
</Col>
<Col span={8}>
<div>col-8</div>
</Col>
<Col span={8}>
<div className="col col-height-10">col-8</div>
</Col>
</Row>
<h4>align bottom</h4>
<Row justify="center" align="bottom" className=" row-bg">
<Col span={8}>
<div className="col col-height-8">col-8</div>
</Col>
<Col span={8}>
<div>col-8</div>
</Col>
<Col span={8}>
<div className="col col-height-10">col-8</div>
</Col>
</Row>
<h4>align stretch</h4>
<Row justify="center" align="stretch" className=" row-stretch row-bg">
<Col span={8}>
<div className="col col-height-8">col-8</div>
</Col>
<Col span={8}>
<div>col-8</div>
</Col>
<Col span={8}>
<div className="col col-height-10">col-8</div>
</Col>
</Row>
</>,
mountNode,
);
```
## 排序
通过 order 属性,设置 Col 的 顺序。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<Row justify="center" align="top">
<Col span={8} order={2}>
<div>col-8 第1个</div>
</Col>
<Col span={8} order={1}>
<div>col-8 第2个</div>
</Col>
<Col span={8} order={0}>
<div>col-8 第3个</div>
</Col>
</Row>,
mountNode,
);
```
## flex
通过 flex 属性,设置 Col 样式。
```jsx
import { Row, Col } from 'zarm-web';
ReactDOM.render(
<>
<Row gutter={[0, 10]}>
<Col flex={2}>
<div>2 / 5</div>
</Col>
<Col flex={3}>
<div>3 / 5</div>
</Col>
</Row>
<Row gutter={[0, 10]}>
<Col flex="100px">
<div>100px</div>
</Col>
<Col flex="auto">
<div>Fill Rest</div>
</Col>
</Row>
<Row gutter={[0, 10]}>
<Col flex="1 1 200px">
<div>1 1 200px</div>
</Col>
<Col flex="0 1 300px">
<div>0 1 300px</div>
</Col>
</Row>
</>,
mountNode
);
```
## API
<h3>Row</h3>
| 属性 | 类型 | 默认值 | 说明 |
| :--- | :--- | :--- | :--- |
| gutter | number \| [number, number] | 0 | 设置栅格水平间隔,使用数组可同时设置`[水平间隔,垂直间隔]` |
| align | string | 'stretch' | 垂直对齐方式,可选值为 `top`、 `middle`、 `bottom`、 `stretch` |
| justify | string | 'start' | 水平排列方式,可选值为 `start`、`end`、`center`、`space-around`、`space-between` |
<h3>Col</h3>
| 属性 | 类型 | 默认值 | 说明 |
| :--- | :--- | :--- | :--- |
| flex | string \| number | - | flex 布局属性 |
| offset | number | - | 栅格左侧的间隔格数 |
| order | number | - | 栅格顺序 |
| pull | number | - | 栅格向左移动格数 |
| push | number | - | 栅格向右移动格数 |
| span | number | - | 栅格占位格数,为 0 时相当于 display: none |
|
// See LICENSE.BU for license details.
// See LICENSE.IBM for license details.
package dana
import chisel3._
import chisel3.util._
// [TODO] This module is currently non-working. It was an initial
// solution to the problem of dealing with random writes from the
// Processing Elements and needing to maintain a record of which
// entries were valid. Knowledge of valid entries is necessary to
// ensure that subsequent PE reads are only reading valid data. This
// approach introduces metadata into each SRAM block that contains the
// number of valid entries in that block.
class SRAMElementCounterResp (
val sramDepth: Int
) extends Bundle {
override def cloneType = new SRAMElementCounterResp (
sramDepth = sramDepth).asInstanceOf[this.type]
val index = UInt(log2Up(sramDepth).W)
}
class SRAMElementCounterInterface (
val dataWidth: Int,
val sramDepth: Int,
val numPorts: Int,
val elementWidth: Int
) extends Bundle {
override def cloneType = new SRAMElementInterface(
dataWidth = dataWidth,
sramDepth = sramDepth,
numPorts = numPorts,
elementWidth = elementWidth).asInstanceOf[this.type]
val we = Output(Vec(numPorts, Bool()))
val din = Output(Vec(numPorts, UInt(elementWidth.W)))
val addr = Output(Vec(numPorts, UInt(log2Up(sramDepth * dataWidth / elementWidth).W)))
val dout = Input(Vec(numPorts, UInt(dataWidth.W)))
// lastBlock sets which is the last block in the SRAM
val lastBlock = Input(Vec(numPorts, UInt(log2Up(sramDepth).W)))
// lastCount sets the number of elements in the last block
val lastCount = Input(Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W)))
val resp = Vec(numPorts, Decoupled(new SRAMElementCounterResp (
sramDepth = sramDepth)) )
}
// write (i.e., SRAMElement), but also includes a count of the number
// of valid elements in each block. When a block is determined to be
// completely valid, this module generates an output update signal
// indicating which block is now valid.
class SRAMElementCounter (
val dataWidth: Int = 32,
val sramDepth: Int = 64,
val elementWidth: Int = 8,
val numPorts: Int = 1
) extends Module {
val io = IO(Flipped(new SRAMElementCounterInterface(
dataWidth = dataWidth,
sramDepth = sramDepth,
numPorts = numPorts,
elementWidth = elementWidth
)))
val sram = Module(new SRAM(
dataWidth = dataWidth + log2Up(dataWidth / elementWidth) + 1,
sramDepth = sramDepth,
numReadPorts = numPorts,
numWritePorts = numPorts,
numReadWritePorts = 0
))
val addr = Vec(numPorts, new Bundle{
val addrHi = UInt(log2Up(sramDepth).W)
val addrLo = UInt(log2Up(dataWidth / elementWidth).W)})
val writePending = Reg(Vec(numPorts, new WritePendingBundle(
elementWidth = elementWidth,
dataWidth = dataWidth,
sramDepth = sramDepth)))
val tmp = Vec(numPorts, Vec(dataWidth/elementWidth, UInt(elementWidth.W)))
val count = Vec(numPorts, UInt((log2Up(dataWidth / elementWidth) + 1).W))
val forwarding = Vec(numPorts, Bool())
// Combinational Logic
for (i <- 0 until numPorts) {
// Assign the addresses
addr(i).addrHi := io.addr(i)(
log2Up(sramDepth * dataWidth / elementWidth) - 1,
log2Up(dataWidth / elementWidth))
addr(i).addrLo := io.addr(i)(
log2Up(dataWidth / elementWidth) - 1, 0)
// Connections to the sram
sram.io.weW(i) := writePending(i).valid
// Explicit data and count assignments
sram.io.dinW(i) := 0.U
sram.io.dinW(i)(sramDepth - 1, 0) := tmp(i)
sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) :=
count(i) + 1.U + forwarding(i)
sram.io.addrR(i) := addr(i).addrHi
io.dout(i) := sram.io.doutR(i)(dataWidth - 1, 0)
// Defaults
io.resp(i).valid := false.B
io.resp(i).bits.index := 0.U
forwarding(i) := false.B
tmp(i) := sram.io.doutR(i)(dataWidth - 1, 0)
count(i) := sram.io.doutR(i)(
dataWidth + log2Up(dataWidth/elementWidth) + 1 - 1, dataWidth)
sram.io.addrW(i) := writePending(i).addrHi
when (writePending(i).valid) {
for (j <- 0 until dataWidth / elementWidth) {
when (j.U === writePending(i).addrLo) {
tmp(i)(j) := writePending(i).data
} .elsewhen(addr(i).addrHi === writePending(i).addrHi &&
io.we(i) &&
j.U === addr(i).addrLo) {
tmp(i)(j) := io.din(i)
forwarding(i) := true.B
} .otherwise {
tmp(i)(j) := sram.io.doutR(i)((j+1) * elementWidth - 1, j * elementWidth)
}
}
// Generate a response if we've filled up an entry. An entry is
// full if it's count is equal to the number of elementsPerBlock
// or if it's the last count in the last block (this covers the
// case of a partially filled last block).
when (count(i) + 1.U + forwarding(i) === (dataWidth / elementWidth).U ||
(count(i) + 1.U + forwarding(i) === io.lastCount(i) &&
writePending(i).addrHi === io.lastBlock(i))) {
io.resp(i).valid := true.B
io.resp(i).bits.index := writePending(i).addrHi
sram.io.dinW(i)(sramDepth + log2Up(dataWidth/elementWidth) + 1 - 1) := 0.U
}
}
}
// Sequential Logic
for (i <- 0 until numPorts) {
// Assign the pending write data
writePending(i).valid := false.B
when ((io.we(i)) && (forwarding(i) === false.B)) {
writePending(i).valid := true.B
writePending(i).data := io.din(i)
writePending(i).addrHi := addr(i).addrHi
writePending(i).addrLo := addr(i).addrLo
}
}
// Assertions
assert(isPow2(dataWidth / elementWidth),
"dataWidth/elementWidth must be a power of 2")
}
|
ALTER TABLE installation_statistics
ADD COLUMN users_count INTEGER NOT NULL DEFAULT 0,
ADD COLUMN codebases_count INTEGER NOT NULL DEFAULT 0;
|
# Olá,Mundo!
Primeiro repositorio de Git e GitHub
repositótio criado durante uma aula
Está linha eu adicionei diretamente no site.
|
using HKTool.Reflection.Runtime;
namespace HKTool.Reflection;
static class FastReflection
{
public static Dictionary<FieldInfo, RD_SetField> fsetter = new();
public static Dictionary<FieldInfo, RD_GetField> fgetter = new();
public static Dictionary<FieldInfo, Func<object, IntPtr>> frefgetter = new();
public static Dictionary<MethodInfo, FastReflectionDelegate> mcaller = new();
public static RD_GetField GetGetter(FieldInfo field)
{
if (field is null) throw new ArgumentNullException(nameof(field));
if (!fgetter.TryGetValue(field, out var getter))
{
DynamicMethod dm = new DynamicMethod("", MethodAttributes.Static | MethodAttributes.Public,
CallingConventions.Standard, typeof(object), new Type[]{
typeof(object)
}, (Type)field.DeclaringType, true);
var il = dm.GetILGenerator();
if (!field.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
if (field.DeclaringType.IsValueType)
{
il.Emit(OpCodes.Unbox_Any, field.DeclaringType);
}
il.Emit(OpCodes.Ldfld, field);
}
else
{
il.Emit(OpCodes.Ldsfld, field);
}
if (field.FieldType.IsValueType)
{
il.Emit(OpCodes.Box, field.FieldType);
}
il.Emit(OpCodes.Ret);
getter = (RD_GetField)dm.CreateDelegate(typeof(RD_GetField));
fgetter[field] = getter;
}
return getter;
}
public static RD_SetField GetSetter(FieldInfo field)
{
if (field is null) throw new ArgumentNullException(nameof(field));
if (!fsetter.TryGetValue(field, out var setter))
{
DynamicMethod dm = new DynamicMethod("", MethodAttributes.Static | MethodAttributes.Public,
CallingConventions.Standard, typeof(void), new Type[]{
typeof(object),
typeof(object)
}, (Type)field.DeclaringType, true);
var il = dm.GetILGenerator();
if (field.IsStatic)
{
il.Emit(OpCodes.Ldarg_1);
if (field.FieldType.IsValueType) il.Emit(OpCodes.Unbox_Any, field.FieldType);
il.Emit(OpCodes.Stsfld, field);
}
else
{
il.Emit(OpCodes.Ldarg_0);
if (field.DeclaringType.IsValueType)
{
il.Emit(OpCodes.Unbox_Any, field.DeclaringType);
}
il.Emit(OpCodes.Ldarg_1);
if (field.FieldType.IsValueType) il.Emit(OpCodes.Unbox_Any, field.FieldType);
il.Emit(OpCodes.Stfld, field);
}
il.Emit(OpCodes.Ret);
setter = (RD_SetField)dm.CreateDelegate(typeof(RD_SetField));
fsetter[field] = setter;
}
return setter;
}
internal static object CallMethod(object? @this, MethodInfo method, params object?[]? args)
{
if (method is null) throw new ArgumentNullException(nameof(method));
if (!mcaller.TryGetValue(method, out var caller))
{
caller = method.CreateFastDelegate(true);
mcaller[method] = caller;
}
return caller(@this, args ?? new object?[] { null });
}
internal static object GetField(object? @this, FieldInfo field)
{
if (field is null) throw new ArgumentNullException(nameof(field));
try
{
return GetGetter(field)(@this);
}
catch (Exception e)
{
HKToolMod.logger.LogError(e);
return field.GetValue(@this);
}
}
internal static IntPtr GetFieldRef(object? @this, FieldInfo field)
{
if (field is null) throw new ArgumentNullException(nameof(field));
if (frefgetter.TryGetValue(field, out var getter)) return getter.Invoke(@this!);
DynamicMethod dm = new("", MethodAttributes.Static | MethodAttributes.Public,
CallingConventions.Standard, typeof(IntPtr), new Type[]{
typeof(object)
}, (Type)field.DeclaringType, true);
var il = dm.GetILGenerator();
if (!field.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
if (field.DeclaringType.IsValueType)
{
il.Emit(OpCodes.Unbox_Any, field.DeclaringType);
}
il.Emit(OpCodes.Ldflda, field);
}
else
{
il.Emit(OpCodes.Ldsflda, field);
}
//il.Emit(OpCodes.Box, field.FieldType.MakeByRefType());
il.Emit(OpCodes.Ret);
getter = (Func<object, IntPtr>)dm.CreateDelegate(typeof(Func<object, IntPtr>));
frefgetter[field] = getter;
return getter.Invoke(@this!);
}
internal static void SetField(object? @this, FieldInfo field, object? val)
{
if (field is null) throw new ArgumentNullException(nameof(field));
try
{
GetSetter(field)(@this, val);
}
catch (Exception e)
{
HKToolMod.logger.LogError(e);
field.SetValue(@this, val);
}
}
}
|
import { connect } from 'react-redux'
import * as Redux from 'redux'
import { createStructuredSelector } from 'reselect'
import toJS from '../../HoC/toJS'
import { selectSideBarActive, selectSideBarDirection } from '../../selectors/sideBar';
import SideBar from '../../components/SideBar';
import { toggleSideBar } from '../../actions/sideBar';
import { push } from 'react-router-redux';
import { selectUserSettings } from '../../selectors/user';
import { setUser } from '../../actions/user';
const mapStateToProps = createStructuredSelector({
active: selectSideBarActive(),
direction: selectSideBarDirection(),
user: selectUserSettings()
})
const mapDispatchToProps = ( dispatch: any ) => ({
toggleSideBar: (direction:string) => dispatch( toggleSideBar.success( {direction} ) ),
setUser: (user:any) => dispatch( setUser.success( {user} )),
push: ( url: string ) => dispatch( push( url ) ),
}) as any
export default Redux.compose(
connect(mapStateToProps,mapDispatchToProps),
toJS
) (SideBar) as any
|
# lwt-simple-multi-client-server
Lwt の公式にあるサーバー実装
```
dune exec ./main.exe
```
|
import React, { useState, useEffect } from 'react';
import { sha256 } from 'js-sha256';
import { Box, Text } from 'rebass';
import { ThemeProvider } from 'emotion-theming';
import Login from 'components/auth/login';
import { LoginProps } from 'components/auth/auth';
import Dashboard from './dashboard';
import { theme, GlobalStyles } from 'styles';
import Modal from 'components/modal';
import ChangePassword from './change-password';
type Props = {
db: firebase.firestore.Firestore;
};
const Admin: React.FC<Props> = ({ db }) => {
// set defult to true -> development only
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [adminEmail, setAdminEmail] = useState('');
const [showModal, setShowModal] = useState(false);
const [changePassId, setChangePassId] = useState('');
const [isUnauthorized, setIsUnauthorized] = useState(false);
const adminUserDbRef = db.collection('admin-user');
const debug = false;
useEffect(() => {
// skipping login on debug
if (debug) {
setIsAuthenticated(true);
setAdminEmail('[email protected]');
}
}, []);
// password encrypted with sha256!!
const login = async ({ email, password }: LoginProps) => {
// authenticate user first
const adminUser = await adminUserDbRef
.where('email', '==', email)
.where('password', '==', sha256(password))
.get();
const adminUserExists = (await adminUser.size) > 0;
if (await adminUserExists) {
setIsAuthenticated(true);
setAdminEmail(email);
if (password === '123456') {
setShowModal(true);
setChangePassId(adminUser.docs[0].id);
}
} else {
setIsUnauthorized(true);
}
};
const logout = () => {
setIsAuthenticated(false);
};
return (
<ThemeProvider theme={theme}>
<GlobalStyles />
{showModal && (
<Modal center={true}>
<ChangePassword
db={db}
changePassId={changePassId}
closeModal={() => {
setShowModal(false);
}}
/>
</Modal>
)}
{isAuthenticated ? (
<Dashboard db={db} logout={logout} adminEmail={adminEmail} />
) : (
<Modal center={true}>
<Box bg="#fff" p={[5]} width={['80vw', '70vw', '400px']}>
<Login login={login} submitValue="Login as admin" />
{isUnauthorized && (
<Text
variant="formError"
mt={[4]}
sx={{ textAlign: 'center' }}
>
Admin user unauthorized
</Text>
)}
</Box>
</Modal>
)}
</ThemeProvider>
);
};
export { Admin };
|
/*
* Copyright 2021 EPAM Systems
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package deployment_test
import (
"encoding/json"
"fmt"
odahuflowv1alpha1 "github.com/odahu/odahu-flow/packages/operator/api/v1alpha1"
"github.com/odahu/odahu-flow/packages/operator/pkg/apiclient/deployment"
apis "github.com/odahu/odahu-flow/packages/operator/pkg/apis/deployment"
"github.com/odahu/odahu-flow/packages/operator/pkg/config"
"github.com/stretchr/testify/suite"
"net/http"
"net/http/httptest"
"odahu-commons/predictors"
"testing"
)
var (
md = apis.ModelDeployment{
ID: "test-md",
Spec: odahuflowv1alpha1.ModelDeploymentSpec{
Image: "image-name:tag",
Predictor: predictors.OdahuMLServer.ID,
},
}
)
type mdSuite struct {
suite.Suite
testServer *httptest.Server
client deployment.Client
}
func (s *mdSuite) SetupSuite() {
s.testServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/model/deployment/test-md":
if r.Method != http.MethodGet {
notFound(w, r)
return
}
w.WriteHeader(http.StatusOK)
mdBytes, err := json.Marshal(md)
if err != nil {
// Must not be occurred
panic(err)
}
_, err = w.Write(mdBytes)
if err != nil {
// Must not be occurred
panic(err)
}
// Mock endpoint that returns some HTML response (e.g. simulate Nginx error)
case "/api/v1/model/deployment/get-html-response":
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("<html>some error page</html>"))
if err != nil {
// Must not be occurred
panic(err)
}
// Mock endpoint that does not response
case "/api/v1/model/deployment/no-response":
panic(http.ErrAbortHandler)
default:
notFound(w, r)
}
}))
s.client = deployment.NewClient(config.AuthConfig{APIURL: s.testServer.URL})
}
func (s *mdSuite) TearDownSuite() {
s.testServer.Close()
}
func TestMdSuite(t *testing.T) {
suite.Run(t, new(mdSuite))
}
func notFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, err := fmt.Fprintf(w, "%s url not found", r.URL.Path)
if err != nil {
// Must not be occurred
panic(err)
}
}
func (s *mdSuite) TestGetDeployment() {
mdFromClient, err := s.client.GetModelDeployment(md.ID)
s.Assertions.NoError(err)
s.Assertions.Equal(md, *mdFromClient)
}
func (s *mdSuite) TestGetDeployment_NotFound() {
mdFromClient, err := s.client.GetModelDeployment("nonexistent-deployment")
s.Assertions.Nil(mdFromClient)
s.Assertions.Error(err)
s.Assertions.Contains(err.Error(), "not found")
}
func (s *mdSuite) TestGetDeployment_CannotUnmarshal() {
mdFromClient, err := s.client.GetModelDeployment("get-html-response")
s.Assertions.Nil(mdFromClient)
s.Assertions.Error(err)
s.Assertions.Contains(err.Error(), "invalid character")
}
func (s *mdSuite) TestGetDeployment_NoResponse() {
mdFromClient, err := s.client.GetModelDeployment("no-response")
s.Assertions.Nil(mdFromClient)
s.Assertions.Error(err)
s.Assertions.Contains(err.Error(), "EOF")
}
|
#include <exception>
#include <stdexcept>
#include "Time.h"
unsigned int Time::max_year = 3000;
unsigned int Time::min_year = 1970;
string Time::default_format = "%Ex %EX";
Time::Time() {
setTime(0);
}
Time::Time(time_t time) {
setTime(time);
}
Time::Time(tm& time) {
setTime(time);
}
Time::Time
(unsigned int year, unsigned int mon, unsigned int mday,
unsigned int hour, unsigned int min, unsigned int sec)
{
setTime(year, mon, mday, hour, min, sec);
}
void Time::setTime(time_t time) {
if (isValid(time)) {
m_time = time;
} else {
throw std::invalid_argument("time invalid!");
}
}
void Time::setTime(tm& time) {
if (isValid(time)) {
m_time = mktime(&time);
} else {
throw std::invalid_argument("time invalid!");
}
}
void Time::setTime(unsigned int year, unsigned int mon, unsigned int mday,
unsigned int hour, unsigned int min, unsigned int sec) {
if (isValid(year, mon, mday, hour, min, sec)) {
tm time = {0};
time.tm_year = year - 1900;
time.tm_mon = mon - 1;
time.tm_mday = mday;
time.tm_hour = hour;
time.tm_min = min;
time.tm_sec = sec;
m_time = mktime(&time);
} else {
throw std::invalid_argument("time invalid!");
}
}
string Time::getTimeString(const string &format) const {
char temp[100] = {0};
strftime(temp, 100, format.c_str(), localtime(&m_time));
return string(temp);
}
Time Time::now() {
time_t time_stamp;
time(&time_stamp);
return Time(time_stamp);
}
bool Time::isValid(tm& time) {
return isValid(time.tm_year + 1900, time.tm_mon + 1, time.tm_mday
,time.tm_hour, time.tm_min, time.tm_sec);
}
bool Time::isValid
(unsigned int year, unsigned int mon, unsigned int mday,
unsigned int hour, unsigned int min, unsigned int sec)
{
if (year < min_year || year > max_year) {return false;}
if (mon < 1 || mon > 12) {return false;}
unsigned int day_of_month[] = {31,28,31,30,31,30,31,31,30,31,30,31};
if (isLeapYear(year)) {++day_of_month[2-1];}//leap year
if (mday < 1 || mday > day_of_month[mon - 1]) { return false;}
if(hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60) {return false;}
return true;
}
ostream& operator<<(ostream& out, const Time& src) {
out << asctime(localtime(&src.m_time));
return out;
}
istream& operator>>(istream& in, Time& dst) {
time_t time;
in >> time;
dst.setTime(time);
return in;
}
|
var searchData=
[
['widgets',['Widgets',['../chapter18-widget.html',1,'overview']]],
['world',['World',['../chapter7-world.html',1,'overview']]],
['w',['w',['../structchai3d_1_1c_quaternion.html#adbf105b4dd0da86c8fca8ab14a66fee1',1,'chai3d::cQuaternion']]],
['widgets',['Widgets',['../group__widgets.html',1,'']]],
['world',['World',['../group__world.html',1,'']]]
];
|
#ifndef MEL_BALLANDBEAM_HPP
#define MEL_BALLANDBEAM_HPP
#include <MEL/Core/Time.hpp>
#include <MEL/Math/Constants.hpp>
#include <MEL/Math/Functions.hpp>
#include <MEL/Math/Integrator.hpp>
class BallAndBeam {
public:
/// Steps the ball and beam simulation
void step_simulation(mel::Time time, double position_ref, double velocity_ref);
/// Resets the ball and beam inegrators
void reset();
public:
double K_player = 30; ///< stiffness between user and beam [N/m]
double B_player = 1; ///< damping between user and beam [N-s/m]
double g = 9.81; ///< accerlation due to gravity [m/s^2]
double I = 0.025; ///< beam moment of inertia [kg*m^2]
double m = 0.25; ///< ball mass [kg]
double R = 0.03; ///< ball radius [m]
double L = 0.8; ///< beam length [m]
double tau; ///< torque acting on beam [Nm]
double r, rd, rdd; ///< ball state [m, m/s m/s^2]
double q, qd, qdd; ///< beam state [rad, rad/s, rad/s^2]
private:
mel::Integrator rdd2rd; ///< integrates r'' to r'
mel::Integrator rd2r; ///< integrates r' to r
mel::Integrator qdd2qd; ///< integrates q'' to r'
mel::Integrator qd2q; ///< integrates q' to q
};
#endif // MEL_BALLANDBEAM_HPP
|
module DataFactory
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration)
end
class Configuration
attr_reader :channels
attr_accessor :leagues, :url, :password
def initialize
@channels = %w(fixture calendario posiciones goleadores ficha plantelxcampeonato)
@url = 'http://feed.datafactory.la'
@password = '60l4Zz05'
end
end
end
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This test case tests the incremental compilation hash (ICH) implementation
// for let expressions.
// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.
// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph
#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]
// Change Name -----------------------------------------------------------------
#[cfg(cfail1)]
pub fn change_name() {
let _x = 2u64;
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_name() {
let _y = 2u64;
}
// Add Type --------------------------------------------------------------------
#[cfg(cfail1)]
pub fn add_type() {
let _x = 2u32;
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_type() {
let _x: u32 = 2u32;
}
// Change Type -----------------------------------------------------------------
#[cfg(cfail1)]
pub fn change_type() {
let _x: u64 = 2;
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_type() {
let _x: u8 = 2;
}
// Change Mutability of Reference Type -----------------------------------------
#[cfg(cfail1)]
pub fn change_mutability_of_reference_type() {
let _x: &u64;
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_mutability_of_reference_type() {
let _x: &mut u64;
}
// Change Mutability of Slot ---------------------------------------------------
#[cfg(cfail1)]
pub fn change_mutability_of_slot() {
let mut _x: u64 = 0;
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_mutability_of_slot() {
let _x: u64 = 0;
}
// Change Simple Binding to Pattern --------------------------------------------
#[cfg(cfail1)]
pub fn change_simple_binding_to_pattern() {
let _x = (0u8, 'x');
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_simple_binding_to_pattern() {
let (_a, _b) = (0u8, 'x');
}
// Change Name in Pattern ------------------------------------------------------
#[cfg(cfail1)]
pub fn change_name_in_pattern() {
let (_a, _b) = (1u8, 'y');
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_name_in_pattern() {
let (_a, _c) = (1u8, 'y');
}
// Add `ref` in Pattern --------------------------------------------------------
#[cfg(cfail1)]
pub fn add_ref_in_pattern() {
let (_a, _b) = (1u8, 'y');
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_ref_in_pattern() {
let (ref _a, _b) = (1u8, 'y');
}
// Add `&` in Pattern ----------------------------------------------------------
#[cfg(cfail1)]
pub fn add_amp_in_pattern() {
let (_a, _b) = (&1u8, 'y');
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_amp_in_pattern() {
let (&_a, _b) = (&1u8, 'y');
}
// Change Mutability of Binding in Pattern -------------------------------------
#[cfg(cfail1)]
pub fn change_mutability_of_binding_in_pattern() {
let (_a, _b) = (99u8, 'q');
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_mutability_of_binding_in_pattern() {
let (mut _a, _b) = (99u8, 'q');
}
// Add Initializer -------------------------------------------------------------
#[cfg(cfail1)]
pub fn add_initializer() {
let _x: i16;
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_initializer() {
let _x: i16 = 3i16;
}
// Change Initializer ----------------------------------------------------------
#[cfg(cfail1)]
pub fn change_initializer() {
let _x = 4u16;
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_initializer() {
let _x = 5u16;
}
|
我国JF22超高速风洞预计2022年建成
孙红雷说扫黑风暴这戏接对了
男子与亲外甥谈恋爱被骗100余万
女子公厕内拍下男子跪地偷窥全程
汤唯状态
迪丽热巴发长文告别乔晶晶
贵州发现6亿岁海绵宝宝
美国首例新冠死亡病例为2020年1月初
央视网评 饭圈文化该驱邪扶正了
国乒不组队参加今年亚锦赛
刘宪华把香菜让给王一博
塔利班称美延迟撤军将面临严重后果
高铁座位边的踏板别踩
孙兴被软禁
乔任梁父母回应恶评
美国数千只沙币被冲上海滩死亡
高校师生返校前提供48小时核酸证明
迪丽热巴好适合演女明星
汪东城晒吴尊AI女装换脸视频
大江暴揍孙兴
扫黑风暴
胖哥俩在执法人员上门检查前丢弃食材
张艺兴12年前用电脑和韩庚合影
冯提莫素颜状态
丁程鑫发文谈加入快乐家族
跑酷不去重庆的原因
翟潇闻演的失恋好真实
过期食物对人体伤害有多大
再不开学我都把证考完了
阳光玫瑰从每斤300元跌至10元
郑州一男子防车淹用砖支车被压身亡
塔利班宣布特赦阿富汗总统加尼
刘雨昕道歉
杨洋发文告别于途
买来补身的甲鱼比你还虚
买个菜感觉像上了天
杨舒予奥运首秀跑错入场仪式
严浩翔由你榜最年轻夺冠歌手
20年陈皮一斤卖到3000元
杨超越送孙俪披荆斩棘四件套
原来浪漫永不过期
外交部回应美国给立陶宛撑腰
原来光能被画出来
嫌疑人被抓时身着跳出三界外T恤
美国7个月大双胞胎被洪水冲走
你是我的荣耀观后感
欧阳娜娜水手服造型
快递小哥因想休息故意酒驾求被抓
今天的这些0来之不易
赵继伟王君瑞领证
阿富汗被辞退前部长在德国送外卖
借条的正确写法
|
#include <iostream>
#include <sstream>
#include <gtest/gtest.h>
#include <gadgetlib2/pp.hpp>
#include <gadgetlib2/protoboard.hpp>
#include <gadgetlib2/gadget.hpp>
using ::std::cerr;
using ::std::cout;
using ::std::endl;
using ::std::stringstream;
#define EXHAUSTIVE_N 4
namespace PCP_Project {
TEST(ConstraintsLib,R1P_AND_Gadget) {
initPublicParamsFromEdwardsParam();
auto pb = Protoboard::create(R1P);
VariableArray x(3, "x");
Variable y("y");
auto andGadget = AND_Gadget::create(pb, x, y);
andGadget->generateConstraints();
pb->val(x[0]) = 0;
pb->val(x[1]) = 1;
pb->val(x[2]) = 1;
andGadget->generateWitness();
EXPECT_TRUE(pb->val(y) == 0);
EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
pb->val(y) = 1;
EXPECT_FALSE(pb->isSatisfied());
pb->val(x[0]) = 1;
andGadget->generateWitness();
EXPECT_TRUE(pb->val(y) == 1);
EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
pb->val(y) = 0;
EXPECT_FALSE(pb->isSatisfied());
}
TEST(ConstraintsLib,LD2_AND_Gadget) {
auto pb = Protoboard::create(LD2);
VariableArray x(3,"x");
Variable y("y");
auto andGadget = AND_Gadget::create(pb, x, y);
andGadget->generateConstraints();
pb->val(x[0]) = 0;
pb->val(x[1]) = 1;
pb->val(x[2]) = 1;
andGadget->generateWitness();
EXPECT_TRUE(pb->val(y) == 0);
EXPECT_TRUE(pb->isSatisfied());
pb->val(y) = 1;
EXPECT_FALSE(pb->isSatisfied());
pb->val(x[0]) = 1;
andGadget->generateWitness();
EXPECT_TRUE(pb->val(y) == 1);
EXPECT_TRUE(pb->isSatisfied());
pb->val(y) = 0;
EXPECT_FALSE(pb->isSatisfied());
}
void andGadgetExhaustiveTest(ProtoboardPtr pb, size_t n); // Forward declaration
TEST(ConstraintsLib,R1P_ANDGadget_Exhaustive) {
initPublicParamsFromEdwardsParam();
for(int n = 1; n <= EXHAUSTIVE_N; ++n) {
SCOPED_TRACE(FMT("n = %u \n", n));
auto pb = Protoboard::create(R1P);
andGadgetExhaustiveTest(pb, n);
}
}
TEST(ConstraintsLib,LD2_ANDGadget_Exhaustive) {
for(int n = 2; n <= EXHAUSTIVE_N; ++n) {
SCOPED_TRACE(FMT("n = %u \n", n));
auto pb = Protoboard::create(LD2);
andGadgetExhaustiveTest(pb, n);
}
}
TEST(ConstraintsLib,BinaryAND_Gadget) {
auto pb = Protoboard::create(LD2);
Variable input1("input1");
Variable input2("input2");
Variable result("result");
auto andGadget = AND_Gadget::create(pb, input1, input2, result);
andGadget->generateConstraints();
pb->val(input1) = pb->val(input2) = 0;
andGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_EQ(pb->val(result), 0);
pb->val(result) = 1;
ASSERT_FALSE(pb->isSatisfied());
pb->val(result) = 0;
pb->val(input1) = 1;
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
pb->val(input2) = 1;
ASSERT_FALSE(pb->isSatisfied());
andGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_EQ(pb->val(result), 1);
}
void orGadgetExhaustiveTest(ProtoboardPtr pb, size_t n); // Forward declaration
TEST(ConstraintsLib,R1P_ORGadget_Exhaustive) {
initPublicParamsFromEdwardsParam();
for(int n = 1; n <= EXHAUSTIVE_N; ++n) {
SCOPED_TRACE(FMT("n = %u \n", n));
auto pb = Protoboard::create(R1P);
orGadgetExhaustiveTest(pb, n);
}
}
TEST(ConstraintsLib,LD2_ORGadget_Exhaustive) {
for(int n = 2; n <= EXHAUSTIVE_N; ++n) {
SCOPED_TRACE(FMT("n = %u \n", n));
auto pb = Protoboard::create(LD2);
orGadgetExhaustiveTest(pb, n);
}
}
TEST(ConstraintsLib,BinaryOR_Gadget) {
auto pb = Protoboard::create(LD2);
Variable input1("input1");
Variable input2("input2");
Variable result("result");
auto orGadget = OR_Gadget::create(pb, input1, input2, result);
orGadget->generateConstraints();
pb->val(input1) = pb->val(input2) = 0;
orGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_EQ(pb->val(result), 0);
pb->val(result) = 1;
ASSERT_FALSE(pb->isSatisfied());
pb->val(result) = 0;
pb->val(input1) = 1;
ASSERT_FALSE(pb->isSatisfied());
pb->val(result) = 1;
ASSERT_CONSTRAINTS_SATISFIED(pb);
pb->val(input2) = 1;
orGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_EQ(pb->val(result), 1);
}
TEST(ConstraintsLib,R1P_InnerProductGadget_Exhaustive) {
initPublicParamsFromEdwardsParam();
const size_t n = EXHAUSTIVE_N;
auto pb = Protoboard::create(R1P);
VariableArray A(n, "A");
VariableArray B(n, "B");
Variable result("result");
auto g = InnerProduct_Gadget::create(pb, A, B, result);
g->generateConstraints();
for (size_t i = 0; i < 1u<<n; ++i) {
for (size_t j = 0; j < 1u<<n; ++j) {
size_t correct = 0;
for (size_t k = 0; k < n; ++k) {
pb->val(A[k]) = i & (1u<<k) ? 1 : 0;
pb->val(B[k]) = j & (1u<<k) ? 1 : 0;
correct += (i & (1u<<k)) && (j & (1u<<k)) ? 1 : 0;
}
g->generateWitness();
EXPECT_EQ(pb->val(result) , FElem(correct));
EXPECT_TRUE(pb->isSatisfied());
// negative test
pb->val(result) = 100*n+19;
EXPECT_FALSE(pb->isSatisfied());
}
}
}
TEST(ConstraintsLib,LD2_InnerProductGadget_Exhaustive) {
initPublicParamsFromEdwardsParam();
const size_t n = EXHAUSTIVE_N > 1 ? EXHAUSTIVE_N -1 : EXHAUSTIVE_N;
for(int len = 1; len <= n; ++len) {
auto pb = Protoboard::create(LD2);
VariableArray a(len, "a");
VariableArray b(len, "b");
Variable result("result");
auto ipGadget = InnerProduct_Gadget::create(pb, a, b, result);
ipGadget->generateConstraints();
// Generate Inputs & Witnesses
vec_GF2E a_vec;
a_vec.SetLength(len);
for(int h = 0; h < len; ++h) { // iterate over a's elements
for(int j = 0; j < 1u<<n; ++j) { // all possible options for a[h]
GF2X a_h;
for(int coeff = 0; coeff < n; ++coeff) { // set a[h] coefficients
SetCoeff(a_h, coeff, j & 1<<coeff);
}
a_vec[h] = to_GF2E(a_h);
pb->val(a[h]) = to_GF2E(a_h);
vec_GF2E b_vec;
b_vec.SetLength(len);
for(int i = 0; i < len; ++i) {
pb->val(b[i]) = 0;
}
for(int i = 0; i < len; ++i) { // iterate over b's elements
for(int k = 0; k < 1u<<n; ++k) { // all possible options for b[i]
GF2X b_i;
for(int coeff = 0; coeff < n; ++coeff) { // set b[i] coefficients
SetCoeff(b_i, coeff, k & 1<<coeff);
}
b_vec[i] = to_GF2E(b_i);
pb->val(b[i]) = to_GF2E(b_i);
ipGadget->generateWitness();
GF2E resultGF2E;
InnerProduct(resultGF2E, a_vec, b_vec);
::std::stringstream s;
s << endl << "i = " << i << endl
<< "< " << a_vec << " > * < " << b_vec << " > = " << resultGF2E << endl
<< pb->annotation();
SCOPED_TRACE(s.str());
EXPECT_EQ(pb->val(result), FElem(resultGF2E));
EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
// Negative test
pb->val(result) = resultGF2E + to_GF2E(1);
EXPECT_FALSE(pb->isSatisfied());
}
}
}
}
}
}
TEST(ConstraintsLib,R1P_LooseMUX_Gadget_Exhaustive) {
initPublicParamsFromEdwardsParam();
const size_t n = EXHAUSTIVE_N;
auto pb = Protoboard::create(R1P);
VariableArray arr(1<<n, "arr");
Variable index("index");
Variable result("result");
Variable success_flag("success_flag");
auto g = LooseMUX_Gadget::create(pb, arr, index, result, success_flag);
g->generateConstraints();
for (size_t i = 0; i < 1u<<n; ++i) {
pb->val(arr[i]) = (19*i) % (1u<<n);
}
for (int idx = -1; idx <= (1<<n); ++idx) {
pb->val(index) = idx;
g->generateWitness();
if (0 <= idx && idx <= (1<<n) - 1) {
EXPECT_EQ(pb->val(result) , (19*idx) % (1u<<n));
EXPECT_EQ(pb->val(success_flag) , 1);
EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
pb->val(result) -= 1;
EXPECT_FALSE(pb->isSatisfied());
}
else {
EXPECT_EQ(pb->val(success_flag) , 0);
EXPECT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
pb->val(success_flag) = 1;
EXPECT_FALSE(pb->isSatisfied());
}
}
}
// Forward declaration
void packing_Gadget_R1P_ExhaustiveTest(ProtoboardPtr unpackingPB, ProtoboardPtr packingPB,
const int n, VariableArray packed, VariableArray unpacked,
GadgetPtr packingGadget, GadgetPtr unpackingGadget);
TEST(ConstraintsLib,R1P_Packing_Gadgets) {
initPublicParamsFromEdwardsParam();
auto unpackingPB = Protoboard::create(R1P);
auto packingPB = Protoboard::create(R1P);
const int n = EXHAUSTIVE_N;
{ // test CompressionPacking_Gadget
SCOPED_TRACE("testing CompressionPacking_Gadget");
VariableArray packed(1, "packed");
VariableArray unpacked(n, "unpacked");
auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed,
PackingMode::PACK);
auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed,
PackingMode::UNPACK);
packing_Gadget_R1P_ExhaustiveTest(unpackingPB, packingPB, n, packed, unpacked, packingGadget,
unpackingGadget);
}
{ // test IntegerPacking_Gadget
SCOPED_TRACE("testing IntegerPacking_Gadget");
VariableArray packed(1, "packed");
VariableArray unpacked(n, "unpacked");
auto packingGadget = IntegerPacking_Gadget::create(packingPB, unpacked, packed,
PackingMode::PACK);
auto unpackingGadget = IntegerPacking_Gadget::create(unpackingPB, unpacked, packed,
PackingMode::UNPACK);
packing_Gadget_R1P_ExhaustiveTest(unpackingPB, packingPB, n, packed, unpacked, packingGadget,
unpackingGadget);
}
}
TEST(ConstraintsLib,LD2_CompressionPacking_Gadget) {
auto unpackingPB = Protoboard::create(LD2);
auto packingPB = Protoboard::create(LD2);
const int n = EXHAUSTIVE_N;
VariableArray packed(1, "packed");
VariableArray unpacked(n, "unpacked");
auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed,
PackingMode::PACK);
auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed,
PackingMode::UNPACK);
packingGadget->generateConstraints();
unpackingGadget->generateConstraints();
for(int i = 0; i < 1u<<n; ++i) {
::std::vector<int> bits(n);
size_t packedGF2X = 0;
for(int j = 0; j < n; ++j) {
bits[j] = i & 1u<<j ? 1 : 0 ;
packedGF2X |= bits[j]<<j;
packingPB->val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard
}
// set the packed value in the unpacking protoboard
unpackingPB->val(packed[0]) = Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X);
unpackingGadget->generateWitness();
packingGadget->generateWitness();
stringstream s;
s << endl << "i = " << i << ", Packed Value: " << Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X) << endl;
SCOPED_TRACE(s.str());
ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_TRUE(packingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
// check packed value is correct
ASSERT_EQ(packingPB->val(packed[0]), Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X));
for(int j = 0; j < n; ++j) {
// Tests for unpacking gadget
SCOPED_TRACE(FMT("\nValue being packed/unpacked: %u, bits[%u] = %u" , i, j, bits[j]));
ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j] ? 1 : 0); // check bit correctness
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit
ASSERT_FALSE(unpackingPB->isSatisfied());
ASSERT_FALSE(packingPB->isSatisfied());
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit
// special case to test booleanity checks. Cause arithmetic constraints to stay
// satisfied while ruining Booleanity
if (j > 0 && bits[j]==1 && bits[j-1]==0 ) {
packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = getGF2E_X();
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 0;
ASSERT_FALSE(unpackingPB->isSatisfied());
ASSERT_TRUE(packingPB->isSatisfied()); // packing should not enforce Booleanity
// restore correct state
packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 0;
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1;
}
}
}
}
TEST(ConstraintsLib, LD2_CompressionPacking_Gadget_largeNums) {
// Test packing/unpacking for the case of more than 1 packed element.
using ::std::vector;
//initialize the context field
const int packedSize = 2;
const int unpackedSize = packedSize * IRR_DEGREE;
vector<int64_t> packingVal(packedSize);
for(int i = 0; i < packedSize; ++i) {
packingVal[i] = i;
}
packingVal[0] = 42; // The Answer To Life, the Universe and Everything
packingVal[1] = 26-9-1984; // My birthday
auto unpackingPB = Protoboard::create(LD2);
auto packingPB = Protoboard::create(LD2);
VariableArray packed(packedSize, "packed");
VariableArray unpacked(unpackedSize, "unpacked");
auto packingGadget = CompressionPacking_Gadget::create(packingPB, unpacked, packed,
PackingMode::PACK);
auto unpackingGadget = CompressionPacking_Gadget::create(unpackingPB, unpacked, packed,
PackingMode::UNPACK);
packingGadget->generateConstraints();
unpackingGadget->generateConstraints();
vector<int> bits(unpackedSize);
vector<size_t> packedGF2X(packedSize,0);
for(int j = 0; j < unpackedSize; ++j) {
bits[j] = packingVal[j / IRR_DEGREE] & 1ul<<(j % IRR_DEGREE) ? 1 : 0;
packedGF2X[j / IRR_DEGREE] |= bits[j]<<(j % IRR_DEGREE);
packingPB->val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard
}
// set the packed value in the unpacking protoboard
for(int j = 0; j < packedSize; ++j) {
unpackingPB->val(packed[j]) = Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X[j]);
}
unpackingGadget->generateWitness();
packingGadget->generateWitness();
ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_TRUE(packingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
// check packed values are correct
for(int j = 0; j < packedSize; ++j) {
ASSERT_EQ(packingPB->val(packed[j]), Algebra::mapIntegerToFieldElement(0,Algebra::ExtensionDegree,packedGF2X[j]);
}
for(int j = 0; j < unpackedSize; ++j) {
// Tests for unpacking gadget
SCOPED_TRACE(FMT("j = %lu", j));
ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j] ? 1 : 0); // check bit correctness
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit
ASSERT_FALSE(unpackingPB->isSatisfied());
ASSERT_FALSE(packingPB->isSatisfied());
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit
}
}
void equalsConstTest(ProtoboardPtr pb); // Forward declaration
TEST(ConstraintsLib,R1P_EqualsConst_Gadget) {
initPublicParamsFromEdwardsParam();
auto pb = Protoboard::create(R1P);
equalsConstTest(pb);
}
TEST(ConstraintsLib,LD2_EqualsConst_Gadget) {
auto pb = Protoboard::create(LD2);
equalsConstTest(pb);
}
TEST(ConstraintsLib,ConditionalFlag_Gadget) {
initPublicParamsFromEdwardsParam();
auto pb = Protoboard::create(R1P);
FlagVariable flag;
Variable condition("condition");
auto cfGadget = ConditionalFlag_Gadget::create(pb, condition, flag);
cfGadget->generateConstraints();
pb->val(condition) = 1;
cfGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
pb->val(condition) = 42;
cfGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_EQ(pb->val(flag),1);
pb->val(condition) = 0;
ASSERT_FALSE(pb->isSatisfied());
cfGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_EQ(pb->val(flag),0);
pb->val(flag) = 1;
ASSERT_FALSE(pb->isSatisfied());
}
TEST(ConstraintsLib,LogicImplication_Gadget) {
auto pb = Protoboard::create(LD2);
FlagVariable flag;
Variable condition("condition");
auto implyGadget = LogicImplication_Gadget::create(pb, condition, flag);
implyGadget->generateConstraints();
pb->val(condition) = 1;
pb->val(flag) = 0;
ASSERT_FALSE(pb->isSatisfied());
implyGadget->generateWitness();
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_EQ(pb->val(flag), 1);
pb->val(condition) = 0;
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
implyGadget->generateWitness();
ASSERT_EQ(pb->val(flag), 1);
pb->val(flag) = 0;
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
}
void andGadgetExhaustiveTest(ProtoboardPtr pb, size_t n) {
VariableArray inputs(n, "inputs");
Variable output("output");
auto andGadget = AND_Gadget::create(pb, inputs, output);
andGadget->generateConstraints();
for (size_t curInput = 0; curInput < 1u<<n; ++curInput) {
for (size_t maskBit = 0; maskBit < n; ++maskBit) {
pb->val(inputs[maskBit]) = (curInput & (1u<<maskBit)) ? 1 : 0;
}
andGadget->generateWitness();
{
SCOPED_TRACE(FMT("Positive (completeness) test failed. curInput: %u", curInput));
EXPECT_TRUE(pb->isSatisfied());
}
{
SCOPED_TRACE(pb->annotation());
SCOPED_TRACE(FMT("Negative (soundness) test failed. curInput: %u, Constraints "
"are:", curInput));
pb->val(output) = (curInput == ((1u<<n) - 1)) ? 0 : 1;
EXPECT_FALSE(pb->isSatisfied());
}
}
}
void orGadgetExhaustiveTest(ProtoboardPtr pb, size_t n) {
VariableArray inputs(n, "inputs");
Variable output("output");
auto orGadget = OR_Gadget::create(pb, inputs, output);
orGadget->generateConstraints();
for (size_t curInput = 0; curInput < 1u<<n; ++curInput) {
for (size_t maskBit = 0; maskBit < n; ++maskBit) {
pb->val(inputs[maskBit]) = (curInput & (1u<<maskBit)) ? 1 : 0;
}
orGadget->generateWitness();
{
SCOPED_TRACE(FMT("Positive (completeness) test failed. curInput: %u", curInput));
ASSERT_TRUE(pb->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
}
{
SCOPED_TRACE(pb->annotation());
SCOPED_TRACE(FMT("Negative (soundness) test failed. curInput: %u, Constraints "
"are:", curInput));
pb->val(output) = (curInput == 0) ? 1 : 0;
ASSERT_FALSE(pb->isSatisfied());
}
}
}
void packing_Gadget_R1P_ExhaustiveTest(ProtoboardPtr unpackingPB, ProtoboardPtr packingPB,
const int n, VariableArray packed, VariableArray unpacked,
GadgetPtr packingGadget, GadgetPtr unpackingGadget) {
packingGadget->generateConstraints();
unpackingGadget->generateConstraints();
for(int i = 0; i < 1u<<n; ++i) {
::std::vector<int> bits(n);
for(int j = 0; j < n; ++j) {
bits[j] = i & 1u<<j ? 1 : 0 ;
packingPB->val(unpacked[j]) = bits[j]; // set unpacked bits in the packing protoboard
}
unpackingPB->val(packed[0]) = i; // set the packed value in the unpacking protoboard
unpackingGadget->generateWitness();
packingGadget->generateWitness();
ASSERT_TRUE(unpackingPB->isSatisfied(PrintOptions::DBG_PRINT_IF_NOT_SATISFIED));
ASSERT_TRUE(packingPB->isSatisfied());
ASSERT_EQ(packingPB->val(packed[0]), i); // check packed value is correct
for(int j = 0; j < n; ++j) {
// Tests for unpacking gadget
SCOPED_TRACE(FMT("\nValue being packed/unpacked: %u, bits[%u] = %u" , i, j, bits[j]));
ASSERT_EQ(unpackingPB->val(unpacked[j]), bits[j]); // check bit correctness
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1-bits[j]; // flip bit
ASSERT_FALSE(unpackingPB->isSatisfied());
ASSERT_FALSE(packingPB->isSatisfied());
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = bits[j]; // restore bit
// special case to test booleanity checks. Cause arithmetic constraints to stay
// satisfied while ruining Booleanity
if (j > 0 && bits[j]==1 && bits[j-1]==0 ) {
packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 2;
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 0;
ASSERT_FALSE(unpackingPB->isSatisfied());
ASSERT_TRUE(packingPB->isSatisfied()); // packing should not enforce Booleanity
// restore correct state
packingPB->val(unpacked[j-1]) = unpackingPB->val(unpacked[j-1]) = 0;
packingPB->val(unpacked[j]) = unpackingPB->val(unpacked[j]) = 1;
}
}
}
}
void equalsConstTest(ProtoboardPtr pb) {
Variable input("input");
Variable result("result");
auto gadget = EqualsConst_Gadget::create(pb, 0, input, result);
gadget->generateConstraints();
pb->val(input) = 0;
gadget->generateWitness();
// Positive test for input == n
EXPECT_EQ(pb->val(result), 1);
EXPECT_TRUE(pb->isSatisfied());
// Negative test
pb->val(result) = 0;
EXPECT_FALSE(pb->isSatisfied());
// Positive test for input != n
pb->val(input) = 1;
gadget->generateWitness();
EXPECT_EQ(pb->val(result), 0);
EXPECT_TRUE(pb->isSatisfied());
// Negative test
pb->val(input) = 0;
EXPECT_FALSE(pb->isSatisfied());
}
} // namespace PCP_Project
|
from __future__ import division
import autopath
import py
import math
import random
import sets
exclude_files = ["__init__.py", "autopath.py", "conftest.py"]
def include_file(path):
if ("test" in str(path) or "tool" in str(path) or
"documentation" in str(path) or
"_cache" in str(path)):
return False
if path.basename in exclude_files:
return False
return True
def get_mod_from_path(path):
dirs = path.get("dirname")[0].split("/")
pypyindex = dirs.index("pypy")
return ".".join(dirs[pypyindex:] + path.get("purebasename"))
def find_references(path):
refs = []
for line in path.open("r"):
if line.startswith(" "): # ignore local imports to reduce graph size
continue
if "\\" in line: #ignore line continuations
continue
line = line.strip()
line = line.split("#")[0].strip()
if line.startswith("import pypy."): # import pypy.bla.whatever
if " as " not in line:
refs.append((line[7:].strip(), None))
else: # import pypy.bla.whatever as somethingelse
assert line.count(" as ") == 1
line = line.split(" as ")
refs.append((line[0][7:].strip(), line[1].strip()))
elif line.startswith("from ") and "pypy" in line: #from pypy.b import a
line = line[5:]
if " as " not in line:
line = line.split(" import ")
what = line[1].split(",")
for w in what:
refs.append((line[0].strip() + "." + w.strip(), None))
else: # prom pypy.b import a as c
if line.count(" as ") != 1 or "," in line:
print"can't handle this: " + line
continue
line = line.split(" as ")
what = line[0].replace(" import ", ".").replace(" ", "")
refs.append((what, line[1].strip()))
return refs
def get_module(ref, imports):
ref = ref.split(".")
i = len(ref)
while i:
possible_mod = ".".join(ref[:i])
if possible_mod in imports:
return possible_mod
i -= 1
return None
def casteljeau(points, t):
points = points[:]
while len(points) > 1:
for i in range(len(points) - 1):
points[i] = points[i] * (1 - t) + points[i + 1] * t
del points[-1]
return points[0]
def color(t):
points = [0, 0, 1, 0, 0]
casteljeau([0, 0, 1, 0, 0], t) / 0.375
class ModuleGraph(object):
def __init__(self, path):
self.imports = {}
self.clusters = {}
self.mod_to_cluster = {}
for f in path.visit("*.py"):
if include_file(f):
self.imports[get_mod_from_path(f)] = find_references(f)
self.remove_object_refs()
self.remove_double_refs()
self.incoming = {}
for mod in self.imports:
self.incoming[mod] = sets.Set()
for mod, refs in self.imports.iteritems():
for ref in refs:
if ref[0] in self.incoming:
self.incoming[ref[0]].add(mod)
self.remove_single_nodes()
self.topgraph_properties = ["rankdir=LR"]
def remove_object_refs(self):
# reduces cases like import pypy.translator.genc.basetype.CType to
# import pypy.translator.genc.basetype
for mod, refs in self.imports.iteritems():
i = 0
while i < len(refs):
if refs[i][0] in self.imports:
i += 1
else:
nref = get_module(refs[i][0], self.imports)
if nref is None:
print "removing", repr(refs[i])
del refs[i]
else:
refs[i] = (nref, None)
i += 1
def remove_double_refs(self):
# remove several references to the same module
for mod, refs in self.imports.iteritems():
i = 0
seen_refs = sets.Set()
while i < len(refs):
if refs[i] not in seen_refs:
seen_refs.add(refs[i])
i += 1
else:
del refs[i]
def remove_single_nodes(self):
# remove nodes that have no attached edges
rem = []
for mod, refs in self.imports.iteritems():
if len(refs) == 0 and len(self.incoming[mod]) == 0:
rem.append(mod)
for m in rem:
del self.incoming[m]
del self.imports[m]
def create_clusters(self):
self.topgraph_properties.append("compound=true;")
self.clustered = True
hierarchy = [sets.Set() for i in range(6)]
for mod in self.imports:
for i, d in enumerate(mod.split(".")):
hierarchy[i].add(d)
for i in range(6):
if len(hierarchy[i]) != 1:
break
for mod in self.imports:
cluster = mod.split(".")[i]
if i == len(mod.split(".")) - 1:
continue
if cluster not in self.clusters:
self.clusters[cluster] = sets.Set()
self.clusters[cluster].add(mod)
self.mod_to_cluster[mod] = cluster
def remove_tangling_randomly(self):
# remove edges to nodes that have a lot incoming edges randomly
tangled = []
for mod, incoming in self.incoming.iteritems():
if len(incoming) > 10:
tangled.append(mod)
for mod in tangled:
remove = sets.Set()
incoming = self.incoming[mod]
while len(remove) < len(incoming) * 0.80:
remove.add(random.choice(list(incoming)))
for rem in remove:
for i in range(len(self.imports[rem])):
if self.imports[rem][i][1] == mod:
break
del self.imports[rem][i]
incoming.remove(rem)
print "removing", mod, "<-", rem
self.remove_single_nodes()
def dotfile(self, dot):
f = dot.open("w")
f.write("digraph G {\n")
for prop in self.topgraph_properties:
f.write("\t%s\n" % prop)
#write clusters and inter-cluster edges
for cluster, nodes in self.clusters.iteritems():
f.write("\tsubgraph cluster_%s {\n" % cluster)
f.write("\t\tstyle=filled;\n\t\tcolor=lightgrey\n")
for node in nodes:
f.write('\t\t"%s";\n' % node[5:])
for mod, refs in self.imports.iteritems():
for ref in refs:
if mod in nodes and ref[0] in nodes:
f.write('\t\t"%s" -> "%s";\n' % (mod[5:], ref[0][5:]))
f.write("\t}\n")
#write edges between clusters
for mod, refs in self.imports.iteritems():
try:
nodes = self.clusters[self.mod_to_cluster[mod]]
except KeyError:
nodes = sets.Set()
for ref in refs:
if ref[0] not in nodes:
f.write('\t"%s" -> "%s";\n' % (mod[5:], ref[0][5:]))
f.write("}")
f.close()
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
path = py.path.local(sys.argv[1])
else:
path = py.path.local(".")
gr = ModuleGraph(path)
gr.create_clusters()
dot = path.join("import_graph.dot")
gr.dotfile(dot)
|
import React from 'react';
import { Paragraph, Page, ChapterTitle } from 'components';
import PageLayout from 'layouts/PageLayout';
export default () => (
<PageLayout>
<Page>
<ChapterTitle>A new kind in the block</ChapterTitle>
<Paragraph>
During the last few years, media have periodically reported news about
Bitcoin. Sometimes it was about its incredible raise in price, sometimes
about its incredible drop in price and sometimes about how Bitcoin was
allegedly used by the criminals all over the world. Lots of people
labeled Bitcoin as a ponzi scheme, other compared Bitcoin to the tulips
bubble of 1637. Meanwhile, someone else started digging deeper, trying
to understand how to make it possible for people all over the world to
transfer money without a bank. They found a system that was open,
public, censorship-resistant, secure and where innovation could be
developed without asking any permission: the Blockchain technology.
</Paragraph>
<Paragraph>
The Blockchain technology is becoming one of the top strategic
priorities of the most influential companies and business leaders
worldwide, with the promise of reducing costs, enhance trust, minimise
inefficiencies and radically transform business models.
</Paragraph>
</Page>
</PageLayout>
);
|
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class RoleSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('roles')->insert([
['name' => 'Administrador', 'unalterable' => 1],
['name' => 'Técnico', 'unalterable' => 0],
['name' => 'Viabilidade', 'unalterable' => 0],
['name' => 'Operacional', 'unalterable' => 0],
['name' => 'Mapper', 'unalterable' => 0],
['name' => 'Comercial', 'unalterable' => 0],
['name' => 'Avançar todos', 'unalterable' => 0],
['name' => 'Retornar todos', 'unalterable' => 0],
['name' => 'Reporter', 'unalterable' => 0]
]);
}
}
|
package com.icthh.xm.uaa.service;
import com.icthh.xm.commons.lep.LogicExtensionPoint;
import com.icthh.xm.commons.lep.spring.LepService;
import com.icthh.xm.commons.logging.util.MdcUtils;
import com.icthh.xm.commons.tenant.TenantContextHolder;
import com.icthh.xm.commons.tenant.TenantContextUtils;
import com.icthh.xm.uaa.commons.UaaUtils;
import com.icthh.xm.uaa.commons.XmRequestContextHolder;
import com.icthh.xm.uaa.domain.User;
import com.icthh.xm.uaa.service.mail.MailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
@LepService(group = "service.account")
@Transactional
@RequiredArgsConstructor
@Slf4j
public class AccountMailService {
private final TenantContextHolder tenantContextHolder;
private final XmRequestContextHolder xmRequestContextHolder;
private final MailService mailService;
@LogicExtensionPoint("SendMailOnRegistration")
public void sendMailOnRegistration(User user) {
mailService.sendActivationEmail(user,
UaaUtils.getApplicationUrl(xmRequestContextHolder),
TenantContextUtils.getRequiredTenantKey(tenantContextHolder),
MdcUtils.getRid());
}
@LogicExtensionPoint("SendMailOnPasswordReset")
public void sendMailOnPasswordResetFinish(User user) {
mailService.sendPasswordChangedMail(user,
UaaUtils.getApplicationUrl(xmRequestContextHolder),
TenantContextUtils.getRequiredTenantKey(tenantContextHolder),
MdcUtils.getRid());
}
@LogicExtensionPoint("SendMailOnPasswordInit")
public void sendMailOnPasswordInit(User user) {
mailService.sendPasswordResetMail(user,
UaaUtils.getApplicationUrl(xmRequestContextHolder),
TenantContextUtils.getRequiredTenantKey(tenantContextHolder),
MdcUtils.getRid());
}
@LogicExtensionPoint("SendSocialRegistrationValidationEmail")
public void sendSocialRegistrationValidationEmail(User user ,String providerId) {
mailService.sendSocialRegistrationValidationEmail(user, providerId,
UaaUtils.getApplicationUrl(xmRequestContextHolder),
TenantContextUtils.getRequiredTenantKey(tenantContextHolder),
MdcUtils.getRid());
}
}
|
# frozen_string_literal: true
require 'sinatra'
require 'dotenv'
require 'line/bot'
$atis = []
def client
Dotenv.load
@client ||= Line::Bot::Client.new do |config|
config.channel_secret = ENV['LINE_CHANNEL_SECRET']
config.channel_token = ENV['LINE_CHANNEL_TOKEN']
end
end
def get_atis
url = URI.parse(ENV['ATIS_URL'])
res = Net::HTTP.get_response(url)
halt 403, { 'Content-Type' => 'text/plain' }, 'Bad Request' unless res.code != 200
$atis = JSON.parse(res.body)
end
post '/metar/callback' do
body = request.body.read
signature = request.env['HTTP_X_LINE_SIGNATURE']
halt 400, { 'Content-Type' => 'text/plain' }, 'Bad Request' unless client.validate_signature(body, signature)
events = client.parse_events_from(body)
events.each do |event|
case event
when Line::Bot::Event::Message
case event.type
when Line::Bot::Event::MessageType::Text
messages = []
stations = event.message['text'].upcase.split(/[,|\s+]/, 0).reject(&:empty?)
get_atis unless stations.length.zero?
stations.each do |station|
$atis.each_with_index do |x, i|
next unless $atis[i]['callsign'] == station
message = {
type: 'text',
text: x['atisdat']
}
messages.push(message)
end
end
if messages.empty?
message = {
type: 'text',
text: 'ATIS Not Provided'
}
messages.push(message)
end
client.reply_message(event['replyToken'], messages)
end
end
'OK'
end
end
|
import * as express from 'express';
declare const normalizeFilter: (req: express.Request, res: express.Response, next: express.NextFunction) => void;
export default normalizeFilter;
|
namespace GameCreator.Stats
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using GameCreator.Core;
using GameCreator.Variables;
#if UNITY_EDITOR
using UnityEditor;
#endif
[AddComponentMenu("")]
public class ConditionStatusEffect : ICondition
{
public enum Operation
{
HasStatusEffect,
DoesNotHave
}
public TargetGameObject target = new TargetGameObject(TargetGameObject.Target.Player);
public Operation condition = Operation.HasStatusEffect;
[StatusEffectSelector]
public StatusEffectAsset statusEffect;
[Indent] public int minAmount = 1;
// EXECUTABLE: ----------------------------------------------------------------------------
public override bool Check(GameObject target)
{
GameObject targetGO = this.target.GetGameObject(target);
if (!targetGO)
{
Debug.LogError("Condition Status Effect: No target defined");
return false;
}
Stats stats = targetGO.GetComponentInChildren<Stats>();
if (!stats)
{
Debug.LogError("Condition Status Effect: Could not get Stats component in target");
return false;
}
bool hasStatusEffect = stats.HasStatusEffect(this.statusEffect, this.minAmount);
if (this.condition == Operation.HasStatusEffect && hasStatusEffect) return true;
if (this.condition == Operation.DoesNotHave && !hasStatusEffect) return true;
return false;
}
// +--------------------------------------------------------------------------------------+
// | EDITOR |
// +--------------------------------------------------------------------------------------+
#if UNITY_EDITOR
public const string CUSTOM_ICON_PATH = "Assets/Plugins/GameCreator/Stats/Icons/Conditions/";
public static new string NAME = "Stats/Status Effect";
private const string NODE_TITLE = "{0} {1} status effect {2}";
// INSPECTOR METHODS: ---------------------------------------------------------------------
public override string GetNodeTitle()
{
string statName = (!this.statusEffect
? "(none)"
: this.statusEffect.statusEffect.uniqueName
);
string conditionName = (this.condition == Operation.HasStatusEffect
? "Has"
: "Does not have"
);
return string.Format(
NODE_TITLE,
conditionName,
this.target,
statName
);
}
#endif
}
}
|
package xyz.qwewqa.relive.simulator.core.presets.condition
import xyz.qwewqa.relive.simulator.stage.character.School
import xyz.qwewqa.relive.simulator.core.stage.condition.NamedCondition
val SeishoOnlyCondition = schoolCondition(School.Seisho)
val RinmeikanOnlyCondition = schoolCondition(School.Rinmeikan)
val FrontierOnlyCondition = schoolCondition(School.Frontier)
val SiegfeldOnlyCondition = schoolCondition(School.Siegfeld)
val SeiranOnlyCondition = schoolCondition(School.Seiran)
private fun schoolCondition(school: School) = NamedCondition(school.name) {
it.dress.character.school == school
}
|
module.exports = {
version: require('../actions/version'),
hostInformation: require('../actions/hostInfo'),
systemProps: require('../actions/systemProps'),
createVm: require('../actions/create'),
start: require('../actions/start'),
stop: require('../actions/stop'),
save: require('../actions/save'),
clone: require('../actions/clone'),
screenshot: require('../actions/screenshot'),
isRunning: require('../actions/isRunning'),
getRunning: require('../actions/getRunning'),
list: require('../actions/list'),
vmInfo: require('../actions/vmInfo'),
setVmRam: require('../actions/setVmRam'),
setBootOrder: require('../actions/bootOrder'),
rdp: {
enableRdpAuth: require('../actions/rdp/enable'),
setRdpStatus: require('../actions/rdp/setRdpStatus'),
setPort: require('../actions/rdp/setPort'),
addUser: require('../actions/rdp/addUser'),
removeUser: require('../actions/rdp/removeUser'),
listUsers: require('../actions/rdp/listUsers'),
authType: require('../actions/rdp/authType'),
},
snapshots: {
take: require('../actions/snapshots/take'),
restore: require('../actions/snapshots/restore'),
list: require('../actions/snapshots/list'),
delete: require('../actions/snapshots/delete')
},
storage: {
listMounted: require('../actions/storage/listMounted'),
listAllVdi: require('../actions/storage/listAllVdi'),
attachVdi: require('../actions/storage/vdi.attach'),
attachISO: require('../actions/storage/iso.attach'),
detach: require('../actions/storage/detach'),
resizeVdi: require('../actions/storage/vdi.resize'),
createVdi: require('../actions/storage/vdi.create'),
},
metrics: {
query: require('../actions/metrics/query'),
enable: require('../actions/metrics/enable'),
disable: require('../actions/metrics/disable')
}
};
|
from . import (eyerefract,
cable,
unlit_generic,
lightmap_generic,
vertexlit_generic,
worldvertextransition,
unlittwotexture,
lightmapped_4wayblend,
decalmodulate,
refract,
water)
|
"""Top-level package for EVTech."""
from .camera import *
from .geodesy import *
from .dataset import *
from .ray import *
__author__ = """David Nilosek"""
__email__ = '[email protected]'
__version__ = '1.1.0'
|
#!/bin/sh
VER=$1
if [ -z $VER ];
then
VER=latest
fi
echo "VERSION=$VER"
REPO=nmhung1210/mern-stack-docker
TAG_NAME=$REPO:$VER
docker build -t $TAG_NAME . && \
docker push $TAG_NAME
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.