text
stringlengths 27
775k
|
---|
using Shockah.CommonModCode.SMAPI;
namespace Shockah.ProjectFluent
{
internal class FluentTranslationSet<Key>: ITranslationSet<Key>
{
private IFluent<Key> Fluent { get; set; }
public FluentTranslationSet(IFluent<Key> fluent)
{
this.Fluent = fluent;
}
public bool ContainsKey(Key key)
=> Fluent.ContainsKey(key);
public string Get(Key key)
=> Fluent.Get(key);
public string Get(Key key, object? tokens)
=> Fluent.Get(key, tokens);
}
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/miEstilo.css" type="text/css" />
</head>
<body>
<h1> Datos del Trabajador </h1>
<br/>
<br/>
<img src="img/diane.jpg" />
<h4>Clave: <?php echo $clave; ?></h4>
<h4>Nombre: <?php echo $nombre; ?></h4>
<h4>Sueldo: <?php echo $sueldo; ?></h4>
</body>
</html> |
namespace StatsDownload.Email
{
using System;
using System.Collections.Generic;
public class EmailSettingsValidatorProvider : IEmailSettingsValidatorService
{
public string ParseFromAddress(string unsafeFromAddress)
{
if (string.IsNullOrWhiteSpace(unsafeFromAddress))
{
throw new EmailArgumentException("A from email address was not provided");
}
return unsafeFromAddress;
}
public string ParseFromDisplayName(string unsafeFromDisplayName)
{
if (string.IsNullOrWhiteSpace(unsafeFromDisplayName))
{
throw new EmailArgumentException("A from display name was not provided");
}
return unsafeFromDisplayName;
}
public string ParsePassword(string unsafePassword)
{
if (string.IsNullOrWhiteSpace(unsafePassword))
{
throw new EmailArgumentException("A password was not provided");
}
return unsafePassword;
}
public int ParsePort(string unsafePort)
{
int port;
if (!int.TryParse(unsafePort, out port))
{
throw new EmailArgumentException("An integer was not provided");
}
if (port < 1 || port > 65535)
{
throw new EmailArgumentException("The port should be between 1 and 65535, inclusive");
}
return port;
}
public IEnumerable<string> ParseReceivers(string unsafeReceivers)
{
if (string.IsNullOrWhiteSpace(unsafeReceivers))
{
throw new EmailArgumentException("A receivers list was not provided");
}
return unsafeReceivers.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
}
public string ParseSmtpHost(string unsafeSmtpHost)
{
if (string.IsNullOrWhiteSpace(unsafeSmtpHost))
{
throw new EmailArgumentException("A SMTP host was not provided");
}
return unsafeSmtpHost;
}
}
} |
import FoodTypeProps from "../src/shared/types/FoodType";
export const fakeFoodType: FoodTypeProps = {
_id: "fake",
name: "fake food type",
picture: "https://fake.com",
};
export default fakeFoodType; |
package com.rocbillow.core.uikit.extension
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.rocbillow.core.assist.ContextProvider
val @receiver:ColorRes Int.colorInt
get() = ContextCompat.getColor(ContextProvider.context, this) |
#!/bin/bash
emcc cryptonight.c crypto/*.c -O0 \
-s DISABLE_EXCEPTION_CATCHING=1 \
-s BINARYEN_ASYNC_COMPILATION=1 \
-s ALIASING_FUNCTION_POINTERS=0 \
-s ALLOW_MEMORY_GROWTH=1 \
-s VERBOSE=1 \
-s WASM=1 \
-s BINARYEN=1 \
-s NO_EXIT_RUNTIME=1 \
-s ASSERTIONS=1 \
-s SAFE_HEAP=0 \
-s STACK_OVERFLOW_CHECK=0 \
-s BINARYEN_METHOD="'native-wasm'" \
-s BINARYEN_TRAP_MODE="'js'" \
-s EXPORTED_FUNCTIONS="['_cryptonight_hash']" \
-o ./cryptonight.js
|
import * as ProductActions from './product';
import * as MenuActions from './menu';
import * as CartActions from './cart';
export {
ProductActions,
MenuActions,
CartActions,
};
|
using System.Collections.Generic;
namespace PizzaStore.Business.Models
{
public class ProductListModel
{
public IEnumerable<ProductModel> Products { get; set; }
}
}
|
<?php
namespace App\Http\Controllers\Marketers;
use App\Http\Controllers\Controller;
use App\Models\Marketers\Marketer;
use App\Models\Projects\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class MarketerController extends Controller
{
public function list()
{
if(Auth::user()->role=="Super Admin")
{
$data['marketers'] = Marketer::all();
}
else
{
$data['marketers'] = Marketer::where('project_id',Auth::user()->project_id)->get();
}
$data['counter'] = 1;
$data['projects'] = Project::all();
return view('admin.inventory_management.marketers.list',$data);
}
public function store(Request $request)
{
$response = Marketer::saveMarketer($request);
return back()->withStatus(__($response['message']));
}
}
|
using adnumaZ.Data;
using adnumaZ.ViewModels;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
namespace adnumaZ.ViewComponents
{
public class RecentTorrentsViewComponent : ViewComponent
{
private readonly ApplicationDbContext dbContext;
private readonly IMapper mapper;
public RecentTorrentsViewComponent(ApplicationDbContext dbContext, IMapper mapper)
{
this.dbContext = dbContext;
this.mapper = mapper;
}
public IViewComponentResult Invoke()
{
var viewModel = mapper
.Map<IEnumerable<TorrentViewModel>>(
dbContext.Torrents
.Where(x=>x.IsApproved)
.Include(x => x.Uploader)
.OrderByDescending(x => x.CreatedOn)
.Take(5));
return this.View(viewModel);
}
}
}
|
;/*****************************************************************************
; *
; * XVID MPEG-4 VIDEO CODEC
; * - 3dnow 8x8 block-based halfpel interpolation -
; *
; * Copyright(C) 2001 Peter Ross <[email protected]>
; * 2002-2008 Michael Militzer <[email protected]>
; * 2002 Pascal Massimino <[email protected]>
; *
; * This program is free software ; you can redistribute it and/or modify
; * it under the terms of the GNU General Public License as published by
; * the Free Software Foundation ; either version 2 of the License, or
; * (at your option) any later version.
; *
; * This program is distributed in the hope that it will be useful,
; * but WITHOUT ANY WARRANTY ; without even the implied warranty of
; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; * GNU General Public License for more details.
; *
; * You should have received a copy of the GNU General Public License
; * along with this program ; if not, write to the Free Software
; * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
; *
; ****************************************************************************/
%include "nasm.inc"
;=============================================================================
; Read Only data
;=============================================================================
DATA
ALIGN SECTION_ALIGN
mmx_one:
times 8 db 1
;=============================================================================
; Code
;=============================================================================
TEXT
cglobal interpolate8x8_halfpel_h_3dn
cglobal interpolate8x8_halfpel_v_3dn
cglobal interpolate8x8_halfpel_hv_3dn
cglobal interpolate8x4_halfpel_h_3dn
cglobal interpolate8x4_halfpel_v_3dn
cglobal interpolate8x4_halfpel_hv_3dn
;-----------------------------------------------------------------------------
;
; void interpolate8x8_halfpel_h_3dn(uint8_t * const dst,
; const uint8_t * const src,
; const uint32_t stride,
; const uint32_t rounding);
;
;-----------------------------------------------------------------------------
%macro COPY_H_3DN_RND0 0
movq mm0, [_EAX]
pavgusb mm0, [_EAX+1]
movq mm1, [_EAX+TMP1]
pavgusb mm1, [_EAX+TMP1+1]
lea _EAX, [_EAX+2*TMP1]
movq [TMP0], mm0
movq [TMP0+TMP1], mm1
%endmacro
%macro COPY_H_3DN_RND1 0
movq mm0, [_EAX]
movq mm1, [_EAX+TMP1]
movq mm4, mm0
movq mm5, mm1
movq mm2, [_EAX+1]
movq mm3, [_EAX+TMP1+1]
pavgusb mm0, mm2
pxor mm2, mm4
pavgusb mm1, mm3
lea _EAX, [_EAX+2*TMP1]
pxor mm3, mm5
pand mm2, mm7
pand mm3, mm7
psubb mm0, mm2
movq [TMP0], mm0
psubb mm1, mm3
movq [TMP0+TMP1], mm1
%endmacro
ALIGN SECTION_ALIGN
interpolate8x8_halfpel_h_3dn:
mov _EAX, prm4 ; rounding
mov TMP0, prm1 ; Dst
test _EAX, _EAX
mov _EAX, prm2 ; Src
mov TMP1, prm3 ; stride
jnz near .rounding1
COPY_H_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND0
ret
.rounding1:
; we use: (i+j)/2 = ( i+j+1 )/2 - (i^j)&1
movq mm7, [mmx_one]
COPY_H_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND1
ret
ENDFUNC
;-----------------------------------------------------------------------------
;
; void interpolate8x8_halfpel_v_3dn(uint8_t * const dst,
; const uint8_t * const src,
; const uint32_t stride,
; const uint32_t rounding);
;
;-----------------------------------------------------------------------------
%macro COPY_V_3DN_RND0 0
movq mm0, [_EAX]
movq mm1, [_EAX+TMP1]
pavgusb mm0, mm1
pavgusb mm1, [_EAX+2*TMP1]
lea _EAX, [_EAX+2*TMP1]
movq [TMP0], mm0
movq [TMP0+TMP1], mm1
%endmacro
%macro COPY_V_3DN_RND1 0
movq mm0, mm2
movq mm1, [_EAX]
movq mm2, [_EAX+TMP1]
lea _EAX, [_EAX+2*TMP1]
movq mm4, mm0
movq mm5, mm1
pavgusb mm0, mm1
pxor mm4, mm1
pavgusb mm1, mm2
pxor mm5, mm2
pand mm4, mm7 ; lsb's of (i^j)...
pand mm5, mm7 ; lsb's of (i^j)...
psubb mm0, mm4 ; ...are substracted from result of pavgusb
movq [TMP0], mm0
psubb mm1, mm5 ; ...are substracted from result of pavgusb
movq [TMP0+TMP1], mm1
%endmacro
ALIGN SECTION_ALIGN
interpolate8x8_halfpel_v_3dn:
mov _EAX, prm4 ; rounding
mov TMP0, prm1 ; Dst
test _EAX,_EAX
mov _EAX, prm2 ; Src
mov TMP1, prm3 ; stride
; we process 2 line at a time
jnz near .rounding1
COPY_V_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND0
ret
.rounding1:
; we use: (i+j)/2 = ( i+j+1 )/2 - (i^j)&1
movq mm7, [mmx_one]
movq mm2, [_EAX] ; loop invariant
add _EAX, TMP1
COPY_V_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND1
ret
ENDFUNC
;-----------------------------------------------------------------------------
;
; void interpolate8x8_halfpel_hv_3dn(uint8_t * const dst,
; const uint8_t * const src,
; const uint32_t stride,
; const uint32_t rounding);
;
;
;-----------------------------------------------------------------------------
; The trick is to correct the result of 'pavgusb' with some combination of the
; lsb's of the 4 input values i,j,k,l, and their intermediate 'pavgusb' (s and t).
; The boolean relations are:
; (i+j+k+l+3)/4 = (s+t+1)/2 - (ij&kl)&st
; (i+j+k+l+2)/4 = (s+t+1)/2 - (ij|kl)&st
; (i+j+k+l+1)/4 = (s+t+1)/2 - (ij&kl)|st
; (i+j+k+l+0)/4 = (s+t+1)/2 - (ij|kl)|st
; with s=(i+j+1)/2, t=(k+l+1)/2, ij = i^j, kl = k^l, st = s^t.
; Moreover, we process 2 lines at a times, for better overlapping (~15% faster).
%macro COPY_HV_3DN_RND0 0
lea _EAX, [_EAX+TMP1]
movq mm0, [_EAX]
movq mm1, [_EAX+1]
movq mm6, mm0
pavgusb mm0, mm1 ; mm0=(j+k+1)/2. preserved for next step
lea _EAX, [_EAX+TMP1]
pxor mm1, mm6 ; mm1=(j^k). preserved for next step
por mm3, mm1 ; ij |= jk
movq mm6, mm2
pxor mm6, mm0 ; mm6 = s^t
pand mm3, mm6 ; (ij|jk) &= st
pavgusb mm2, mm0 ; mm2 = (s+t+1)/2
pand mm3, mm7 ; mask lsb
psubb mm2, mm3 ; apply.
movq [TMP0], mm2
movq mm2, [_EAX]
movq mm3, [_EAX+1]
movq mm6, mm2
pavgusb mm2, mm3 ; preserved for next iteration
lea TMP0, [TMP0+TMP1]
pxor mm3, mm6 ; preserved for next iteration
por mm1, mm3
movq mm6, mm0
pxor mm6, mm2
pand mm1, mm6
pavgusb mm0, mm2
pand mm1, mm7
psubb mm0, mm1
movq [TMP0], mm0
%endmacro
%macro COPY_HV_3DN_RND1 0
lea _EAX,[_EAX+TMP1]
movq mm0, [_EAX]
movq mm1, [_EAX+1]
movq mm6, mm0
pavgusb mm0, mm1 ; mm0=(j+k+1)/2. preserved for next step
lea _EAX, [_EAX+TMP1]
pxor mm1, mm6 ; mm1=(j^k). preserved for next step
pand mm3, mm1
movq mm6, mm2
pxor mm6, mm0
por mm3, mm6
pavgusb mm2, mm0
pand mm3, mm7
psubb mm2, mm3
movq [TMP0], mm2
movq mm2, [_EAX]
movq mm3, [_EAX+1]
movq mm6, mm2
pavgusb mm2, mm3 ; preserved for next iteration
lea TMP0, [TMP0+TMP1]
pxor mm3, mm6 ; preserved for next iteration
pand mm1, mm3
movq mm6, mm0
pxor mm6, mm2
por mm1, mm6
pavgusb mm0, mm2
pand mm1, mm7
psubb mm0, mm1
movq [TMP0], mm0
%endmacro
ALIGN SECTION_ALIGN
interpolate8x8_halfpel_hv_3dn:
mov _EAX, prm4 ; rounding
mov TMP0, prm1 ; Dst
test _EAX, _EAX
mov _EAX, prm2 ; Src
mov TMP1, prm3 ; stride
movq mm7, [mmx_one]
; loop invariants: mm2=(i+j+1)/2 and mm3= i^j
movq mm2, [_EAX]
movq mm3, [_EAX+1]
movq mm6, mm2
pavgusb mm2, mm3
pxor mm3, mm6 ; mm2/mm3 ready
jnz near .rounding1
COPY_HV_3DN_RND0
add TMP0, TMP1
COPY_HV_3DN_RND0
add TMP0, TMP1
COPY_HV_3DN_RND0
add TMP0, TMP1
COPY_HV_3DN_RND0
ret
.rounding1:
COPY_HV_3DN_RND1
add TMP0, TMP1
COPY_HV_3DN_RND1
add TMP0, TMP1
COPY_HV_3DN_RND1
add TMP0, TMP1
COPY_HV_3DN_RND1
ret
ENDFUNC
;-----------------------------------------------------------------------------
;
; void interpolate8x4_halfpel_h_3dn(uint8_t * const dst,
; const uint8_t * const src,
; const uint32_t stride,
; const uint32_t rounding);
;
;-----------------------------------------------------------------------------
ALIGN SECTION_ALIGN
interpolate8x4_halfpel_h_3dn:
mov _EAX, prm4 ; rounding
mov TMP0, prm1 ; Dst
test _EAX, _EAX
mov _EAX, prm2 ; Src
mov TMP1, prm3 ; stride
jnz near .rounding1
COPY_H_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND0
ret
.rounding1:
; we use: (i+j)/2 = ( i+j+1 )/2 - (i^j)&1
movq mm7, [mmx_one]
COPY_H_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_H_3DN_RND1
ret
ENDFUNC
;-----------------------------------------------------------------------------
;
; void interpolate8x4_halfpel_v_3dn(uint8_t * const dst,
; const uint8_t * const src,
; const uint32_t stride,
; const uint32_t rounding);
;
;-----------------------------------------------------------------------------
ALIGN SECTION_ALIGN
interpolate8x4_halfpel_v_3dn:
mov _EAX, prm4 ; rounding
mov TMP0, prm1 ; Dst
test _EAX,_EAX
mov _EAX, prm2 ; Src
mov TMP1, prm3 ; stride
; we process 2 line at a time
jnz near .rounding1
COPY_V_3DN_RND0
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND0
ret
.rounding1:
; we use: (i+j)/2 = ( i+j+1 )/2 - (i^j)&1
movq mm7, [mmx_one]
movq mm2, [_EAX] ; loop invariant
add _EAX, TMP1
COPY_V_3DN_RND1
lea TMP0, [TMP0+2*TMP1]
COPY_V_3DN_RND1
ret
ENDFUNC
;-----------------------------------------------------------------------------
;
; void interpolate8x4_halfpel_hv_3dn(uint8_t * const dst,
; const uint8_t * const src,
; const uint32_t stride,
; const uint32_t rounding);
;
;
;-----------------------------------------------------------------------------
; The trick is to correct the result of 'pavgusb' with some combination of the
; lsb's of the 4 input values i,j,k,l, and their intermediate 'pavgusb' (s and t).
; The boolean relations are:
; (i+j+k+l+3)/4 = (s+t+1)/2 - (ij&kl)&st
; (i+j+k+l+2)/4 = (s+t+1)/2 - (ij|kl)&st
; (i+j+k+l+1)/4 = (s+t+1)/2 - (ij&kl)|st
; (i+j+k+l+0)/4 = (s+t+1)/2 - (ij|kl)|st
; with s=(i+j+1)/2, t=(k+l+1)/2, ij = i^j, kl = k^l, st = s^t.
ALIGN SECTION_ALIGN
interpolate8x4_halfpel_hv_3dn:
mov _EAX, prm4 ; rounding
mov TMP0, prm1 ; Dst
test _EAX, _EAX
mov _EAX, prm2 ; Src
mov TMP1, prm3 ; stride
movq mm7, [mmx_one]
; loop invariants: mm2=(i+j+1)/2 and mm3= i^j
movq mm2, [_EAX]
movq mm3, [_EAX+1]
movq mm6, mm2
pavgusb mm2, mm3
pxor mm3, mm6 ; mm2/mm3 ready
jnz near .rounding1
COPY_HV_3DN_RND0
add TMP0, TMP1
COPY_HV_3DN_RND0
ret
.rounding1:
COPY_HV_3DN_RND1
add TMP0, TMP1
COPY_HV_3DN_RND1
ret
ENDFUNC
NON_EXEC_STACK
|
package com.whisk.hulk.testing
import com.whisk.docker.testkit.ContainerState
import org.scalatest.FunSuite
import scala.concurrent.Await
import scala.concurrent.duration._
class CockroachTestkitTest extends FunSuite with CockroachTestKit {
test("test container started") {
assert(cockroachContainer.state().isInstanceOf[ContainerState.Ready], "postgres is ready")
assert(cockroachContainer.mappedPortOpt(CockroachAdvertisedPort).isDefined,
"postgres port exposed")
val res = Await.result(hulkClient.get().fetch("select 1"), 5.seconds)
assert(res.rows.nonEmpty, "client should be connected")
}
}
|
---
uid: crmscript_ref_MacroParameter_getIsOptional
title: MacroParameter.getIsOptional()
intellisense: MacroParameter.getIsOptional
sortOrder: 479
keywords: getIsOptional()
so.topic: reference
---
# MacroParameter.getIsOptional()
This function returns true if the value is optional, and false if it is compulsory.
|
PHP Utils
=========
General PHP utilities. Currently only contains a method for deeply merging (TJM\Component\Utils\Arrays::deepMerge()).
|
/*
* usb_messages.h
*
*
* Copyright (c) 2017 Jeremy Garff
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the copyright holder nor the names of its contributors may not
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Jeremy Garff <[email protected]>
*
*/
#ifndef __USB_MESSAGES_H__
#define __USB_MESSAGES_H__
//
// Standard USB message definitions
//
typedef struct usb_request
{
uint8_t request_type;
#define USB_REQ_DIR_MASK 0x80
#define USB_REQ_DIR_DEV_TO_HOST (1 << 7)
#define USB_REQ_DIR_HOST_TO_DEV (0 << 7)
#define USB_REQ_TYPE_MASK 0x60
#define USB_REQ_TYPE_STANDARD (0 << 5)
#define USB_REQ_TYPE_CLASS (1 << 5)
#define USB_REQ_TYPE_VENDOR (2 << 5)
#define USB_REQ_RECP_MASK 0x1f
#define USB_REQ_RECP_STANDARD 0
#define USB_REQ_RECP_INTERFACE 1
#define USB_REQ_RECP_ENDPOINT 2
uint8_t request;
#define USB_REQ_GET_STATUS 0
#define USB_REQ_CLEAR_FEATURE 1
#define USB_REQ_SET_FEATURE 3
#define USB_REQ_ADDRESS 5
#define USB_REQ_GET_DESCRIPTOR 6
#define USB_REQ_SET_DESCRIPTOR 7
#define USB_REQ_GET_CONFIG 8
#define USB_REQ_SET_CONFIG 9
#define USB_REQ_GET_INTERFACE 10
#define USB_REQ_SET_INTERFACE 11
#define USB_REQ_SYNCH_FRAME 12
#define USB_REQ_SET_LINE_CODING 32
#define USB_REQ_SET_CONTROL_LINE_STATE 34
uint8_t value[2];
// Second byte can be the desc type
#define USB_DESC_DEVICE 1
#define USB_DESC_CONFIG 2
#define USB_DESC_STRING 3
uint16_t index;
uint16_t length;
} __attribute__((packed)) usb_request_t;
typedef struct usb_desc_device
{
uint8_t length;
uint8_t type;
#define USB_DESC_TYPE_DEVICE 1
#define USB_DESC_TYPE_HID 0x21
#define USB_DESC_TYPE_HID_REPORT 0x22
#define USB_DESC_TYPE_HID_PHYS 0x23
uint8_t version[2];
uint8_t class;
uint8_t subclass;
uint8_t protocol;
uint8_t max_packet;
uint8_t vendor_id[2];
uint8_t device_id[2];
uint8_t device_version[2];
uint8_t vendor_str_index;
uint8_t product_str_index;
uint8_t serial_str_index;
uint8_t num_configs;
} __attribute__((packed)) usb_desc_device_t;
typedef struct usb_desc_config
{
uint8_t length;
uint8_t type;
#define USB_DESC_TYPE_CONFIG 2
uint16_t total_length;
uint8_t num_interfaces;
uint8_t config_value;
uint8_t string_index;
uint8_t attributes;
uint8_t max_power_ma;
// Additional interfaces would follow
} __attribute__((packed)) usb_desc_config_t;
typedef struct usb_desc_string
{
uint8_t length;
uint8_t type;
#define USB_DESC_TYPE_STRING 3
uint8_t buffer[]; // unicode string
} __attribute__((packed)) usb_desc_string_t;
typedef struct usb_desc_interface
{
uint8_t length;
uint8_t type;
#define USB_DESC_TYPE_INTERFACE 4
uint8_t number;
uint8_t alt_setting;
uint8_t num_endpoints;
uint8_t class;
uint8_t sub_class;
uint8_t protocol;
uint8_t string_index;
} __attribute__((packed)) usb_desc_interface_t;
#define USB_DESC_TYPE_CS_INTERFACE 0x24
typedef struct usb_desc_cdc_header
{
uint8_t length;
uint8_t type;
uint8_t sub_type;
#define USB_DESC_CDC_HEADER_SUBTYPE 0x00
uint16_t bcd_cdc; // 0x10 0x01
} __attribute__((packed)) usb_desc_cdc_header_t;
typedef struct usb_desc_cdc_acm
{
uint8_t length;
uint8_t type;
uint8_t sub_type;
#define USB_DESC_CDC_ACM_SUBTYPE 0x02 // ACM
uint8_t capabilities;
} __attribute__((packed)) usb_desc_cdc_acm_t;
typedef struct usb_desc_cdc_union
{
uint8_t length;
uint8_t type;
uint8_t sub_type;
#define USB_DESC_CDC_UNION_SUBTYPE 0x06
uint8_t master_interface;
uint8_t slave_interface;
} __attribute__((packed)) usb_desc_cdc_union_t;
typedef struct usb_desc_endpoint
{
uint8_t length;
uint8_t type;
#define USB_DESC_TYPE_ENDPOINT 5
uint8_t ep_addr;
#define USB_EP_ADDR_OUT 0x00
#define USB_EP_ADDR_IN 0x80
uint8_t attrs;
#define USB_DESC_EP_ATTR_CONTROL 0
#define USB_DESC_EP_ATTR_ISO 1
#define USB_DESC_EP_ATTR_BULK 2
#define USB_DESC_EP_ATTR_INT 3
uint16_t max_pkt_size;
uint8_t interval;
} __attribute__((packed)) usb_desc_endpoint_t;
#endif /* __USB_MESSAGES_H__ */
|
import Sparkles from 'components/sparkles';
import Social from 'components/social';
import { email } from 'lib/site';
import style from './style.module.css';
function Contact() {
return (
<section className={`${style.contact} -inverted`} id="contact">
<div className={`${style['contact-wrapper']} wrapper`}>
<div className={style['contact-message-wrapper']}>
<p className={style['contact-message']}>Get in touch with us at</p>
<Sparkles>
<a className={style['contact-email']} href={`mailto:${email}`}>
{email}
</a>
</Sparkles>
<p className={style['contact-message']}>
... or through our social media
</p>
</div>
<Social size="l" filter={({ label }) => label !== 'email'} />
</div>
</section>
);
}
export default Contact;
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.IIS.Administration.WebServer.Sites
{
using Core.Utils;
using Web.Administration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using Core;
using AppPools;
using System.IO;
using System.Runtime.InteropServices;
using Newtonsoft.Json.Linq;
using Certificates;
using Core.Http;
using System.Dynamic;
using Files;
using CentralCertificates;
public static class SiteHelper
{
private const string OIDServerAuth = "1.3.6.1.5.5.7.3.1";
private const string SCOPE_KEY = "scope";
private static readonly Fields RefFields = new Fields("name", "id", "status");
private const string sslFlagsAttribute = "sslFlags";
private const string MaxUrlSegmentsAttribute = "maxUrlSegments";
public static Site CreateSite(dynamic model, IFileProvider fileProvider) {
// Ensure necessary information provided
if (model == null) {
throw new ApiArgumentException("model");
}
if (DynamicHelper.Value(model.name) == null) {
throw new ApiArgumentException("name");
}
if (string.IsNullOrEmpty(DynamicHelper.Value(model.physical_path))) {
throw new ApiArgumentException("physical_path");
}
if (model.bindings == null) {
throw new ApiArgumentException("bindings");
}
ServerManager sm = ManagementUnit.ServerManager;
// Create site using Server Manager
Site site = sm.Sites.CreateElement();
// Initialize the new sites physical path. This is only touched during creation
site.Applications.Add("/", string.Empty);
// Initialize new site settings
SetToDefaults(site, sm.SiteDefaults);
// Initialize site Id by obtaining the first available
site.Id = FirstAvailableId();
// Set site settings to those provided
SetSite(site, model, fileProvider);
return site;
}
// REVIEW: Safe to use the id of a site alone? This number can be reused if site is deleted
public static Site GetSite(long id)
{
Site site = ManagementUnit.ServerManager.Sites.Where(s => s.Id == id).FirstOrDefault();
return site;
}
public static IEnumerable<Site> GetSites(ApplicationPool pool) {
if (pool == null) {
throw new ArgumentNullException(nameof(pool));
}
var sites = new List<Site>();
var sm = ManagementUnit.ServerManager;
foreach (var site in sm.Sites) {
foreach (var app in site.Applications) {
if (app.ApplicationPoolName.Equals(pool.Name, StringComparison.OrdinalIgnoreCase)) {
sites.Add(site);
break;
}
}
}
return sites;
}
public static Site UpdateSite(long id, dynamic model, IFileProvider fileProvider)
{
if (model == null) {
throw new ApiArgumentException("model");
}
// Obtain target site via its id number
Site site = GetSite(id);
// Update state of site to those specified in the model
if (site != null) {
SetSite(site, model, fileProvider);
}
return site;
}
public static void DeleteSite(Site site)
{
ManagementUnit.ServerManager.Sites.Remove(site);
}
internal static object ToJsonModel(Site site, Fields fields = null, bool full = true)
{
if (site == null) {
return null;
}
if (fields == null) {
fields = Fields.All;
}
dynamic obj = new ExpandoObject();
var siteId = new SiteId(site.Id);
//
// name
if (fields.Exists("name")) {
obj.name = site.Name;
}
//
// id
obj.id = siteId.Uuid;
//
// physical_path
if (fields.Exists("physical_path")) {
string physicalPath = string.Empty;
Application rootApp = site.Applications["/"];
if (rootApp != null && rootApp.VirtualDirectories["/"] != null) {
physicalPath = rootApp.VirtualDirectories["/"].PhysicalPath;
}
obj.physical_path = physicalPath;
}
//
// key
if (fields.Exists("key")) {
obj.key = siteId.Id;
}
//
// status
if (fields.Exists("status")) {
// Prepare state
Status state = Status.Unknown;
try {
state = StatusExtensions.FromObjectState(site.State);
}
catch (COMException) {
// Problem getting state of site. Possible reasons:
// 1. Site's application pool was deleted.
// 2. Site was just created and the status is not accessible yet.
}
obj.status = Enum.GetName(typeof(Status), state).ToLower();
}
//
// server_auto_start
if (fields.Exists("server_auto_start")) {
obj.server_auto_start = site.ServerAutoStart;
}
//
// enabled_protocols
if (fields.Exists("enabled_protocols")) {
Application rootApp = site.Applications["/"];
obj.enabled_protocols = rootApp == null ? string.Empty : rootApp.EnabledProtocols;
}
//
// limits
if (fields.Exists("limits")) {
dynamic limits = new ExpandoObject();
limits.connection_timeout = site.Limits.ConnectionTimeout.TotalSeconds;
limits.max_bandwidth = site.Limits.MaxBandwidth;
limits.max_connections = site.Limits.MaxConnections;
if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute)) {
limits.max_url_segments = site.Limits.MaxUrlSegments;
}
obj.limits = limits;
}
//
// bindings
if (fields.Exists("bindings")) {
var bindings = new List<object>();
foreach (Binding b in site.Bindings) {
bindings.Add(ToJsonModel(b));
}
obj.bindings = bindings;
}
//
// application_pool
if (fields.Exists("application_pool")) {
Application rootApp = site.Applications["/"];
var pool = rootApp != null ? AppPoolHelper.GetAppPool(rootApp.ApplicationPoolName) : null;
obj.application_pool = (pool == null) ? null : AppPoolHelper.ToJsonModelRef(pool, fields.Filter("application_pool"));
}
return Core.Environment.Hal.Apply(Defines.Resource.Guid, obj, full);
}
public static object ToJsonModelRef(Site site, Fields fields = null)
{
if (fields == null || !fields.HasFields) {
return ToJsonModel(site, RefFields, false);
}
else {
return ToJsonModel(site, fields, false);
}
}
public static string GetLocation(string id) {
if (string.IsNullOrEmpty(id)) {
throw new ArgumentNullException(nameof(id));
}
return $"/{Defines.PATH}/{id}";
}
public static Site ResolveSite(dynamic model = null)
{
Site site = null;
string scope = null;
string siteUuid = null;
// Resolve from model
if (model != null) {
//
// website.id
if (model.website != null) {
if (!(model.website is JObject)) {
throw new ApiArgumentException("website");
}
siteUuid = DynamicHelper.Value(model.website.id);
}
//
// scope
if (model.scope != null) {
scope = DynamicHelper.Value(model.scope);
}
}
var context = HttpHelper.Current;
//
// Resolve {site_id} from query string
if (siteUuid == null) {
siteUuid = context.Request.Query[Defines.IDENTIFIER];
}
if (!string.IsNullOrEmpty(siteUuid)) {
SiteId siteId = new SiteId(siteUuid);
site = SiteHelper.GetSite(new SiteId(siteUuid).Id);
if (site == null) {
throw new NotFoundException("site");
}
return site;
}
//
// Resolve {scope} from query string
if (scope == null) {
scope = context.Request.Query[SCOPE_KEY];
}
if (!string.IsNullOrEmpty(scope)) {
int index = scope.IndexOf('/');
string siteName = index >= 0 ? scope.Substring(0, index) : scope;
site = ManagementUnit.Current.ServerManager.Sites.FirstOrDefault(s => s.Name.Equals(siteName, StringComparison.OrdinalIgnoreCase));
// Scope points to non existant site
if (site == null) {
throw new ScopeNotFoundException(scope);
}
}
return site;
}
public static string ResolvePath(dynamic model = null)
{
string scope = null;
if (model != null) {
//
// scope
if (model.scope != null) {
scope = DynamicHelper.Value(model.scope);
}
}
var context = HttpHelper.Current;
//
// Resolve {scope} from query string
if (scope == null) {
scope = context.Request.Query[SCOPE_KEY];
}
if (scope == string.Empty) {
return scope;
}
if (scope != null) {
int index = scope.IndexOf('/');
return index >= 0 ? scope.Substring(index) : "/";
}
//
// Scope isn't specified, resolve from site root
Site site = ResolveSite(model);
return (site != null) ? "/" : null;
}
private static Site SetToDefaults(Site site, SiteDefaults defaults)
{
site.ServerAutoStart = defaults.ServerAutoStart;
// Limits
site.Limits.ConnectionTimeout = defaults.Limits.ConnectionTimeout;
site.Limits.MaxBandwidth = defaults.Limits.MaxBandwidth;
site.Limits.MaxConnections = defaults.Limits.MaxConnections;
if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute)) {
site.Limits.MaxUrlSegments = defaults.Limits.MaxUrlSegments;
}
// TraceFailedRequestLogging
site.TraceFailedRequestsLogging.Enabled = defaults.TraceFailedRequestsLogging.Enabled;
site.TraceFailedRequestsLogging.Directory = defaults.TraceFailedRequestsLogging.Directory;
site.TraceFailedRequestsLogging.MaxLogFiles = defaults.TraceFailedRequestsLogging.MaxLogFiles;
return site;
}
private static Site SetSite(Site site, dynamic model, IFileProvider fileProvider)
{
Debug.Assert(site != null);
Debug.Assert((bool)(model != null));
//
// Name
DynamicHelper.If((object)model.name, v => { site.Name = v; });
//
// Server Auto Start
site.ServerAutoStart = DynamicHelper.To<bool>(model.server_auto_start) ?? site.ServerAutoStart;
//
// Key
long? key = DynamicHelper.To<long>(model.key);
if (key.HasValue) {
if (ManagementUnit.ServerManager.Sites.Any(s => s.Id == key.Value && site.Id != key.Value)) {
throw new AlreadyExistsException("key");
}
site.Id = key.Value;
}
//
// Physical Path
string physicalPath = DynamicHelper.Value(model.physical_path);
if (physicalPath != null) {
physicalPath = physicalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
var expanded = System.Environment.ExpandEnvironmentVariables(physicalPath);
if (!PathUtil.IsFullPath(expanded)) {
throw new ApiArgumentException("physical_path");
}
if (!fileProvider.IsAccessAllowed(expanded, FileAccess.Read)) {
throw new ForbiddenArgumentException("physical_path", physicalPath);
}
if (!Directory.Exists(expanded)) {
throw new NotFoundException("physical_path");
}
var rootApp = site.Applications["/"];
if (rootApp != null) {
var rootVDir = rootApp.VirtualDirectories["/"];
if (rootVDir != null) {
rootVDir.PhysicalPath = physicalPath;
}
}
}
//
// Enabled Protocols
string enabledProtocols = DynamicHelper.Value(model.enabled_protocols);
if (enabledProtocols != null) {
var rootApp = site.Applications["/"];
if (rootApp != null) {
rootApp.EnabledProtocols = enabledProtocols;
}
}
//
// Limits
if (model.limits != null) {
dynamic limits = model.limits;
site.Limits.MaxBandwidth = DynamicHelper.To(limits.max_bandwidth, 0, uint.MaxValue) ?? site.Limits.MaxBandwidth;
site.Limits.MaxConnections = DynamicHelper.To(limits.max_connections, 0, uint.MaxValue) ?? site.Limits.MaxConnections;
if (site.Limits.Schema.HasAttribute(MaxUrlSegmentsAttribute)) {
site.Limits.MaxUrlSegments = DynamicHelper.To(limits.max_url_segments, 0, 16383) ?? site.Limits.MaxUrlSegments;
}
long? connectionTimeout = DynamicHelper.To(limits.connection_timeout, 0, ushort.MaxValue);
site.Limits.ConnectionTimeout = (connectionTimeout != null) ? TimeSpan.FromSeconds(connectionTimeout.Value) : site.Limits.ConnectionTimeout;
}
//
// Bindings
if (model.bindings != null) {
IEnumerable<dynamic> bindings = (IEnumerable<dynamic>)model.bindings;
// If the user passes an object for the bindings property rather than an array we will hit an exception when we try to access any property in
// the foreach loop.
// This means that the bindings collection won't be deleted, so the bindings are safe from harm.
List<Binding> newBindings = new List<Binding>();
// Iterate over the bindings to create a new binding list
foreach (dynamic b in bindings) {
Binding binding = site.Bindings.CreateElement();
SetBinding(binding, b);
foreach (Binding addedBinding in newBindings) {
if (addedBinding.Protocol.Equals(binding.Protocol, StringComparison.OrdinalIgnoreCase) &&
addedBinding.BindingInformation.Equals(binding.BindingInformation, StringComparison.OrdinalIgnoreCase)) {
throw new AlreadyExistsException("binding");
}
}
// Add to bindings list
newBindings.Add(binding);
}
// All bindings have been verified and added to the list
// Clear the old list, and add the new
site.Bindings.Clear();
newBindings.ForEach(binding => site.Bindings.Add(binding));
}
//
// App Pool
if (model.application_pool != null) {
// Extract the uuid from the application_pool object provided in model
string appPoolUuid = DynamicHelper.Value(model.application_pool.id);
// It is an error to provide an application pool object without specifying its id property
if (appPoolUuid == null) {
throw new ApiArgumentException("application_pool.id");
}
// Create application pool id object from uuid provided, use this to obtain the application pool
AppPoolId appPoolId = AppPoolId.CreateFromUuid(appPoolUuid);
ApplicationPool pool = AppPoolHelper.GetAppPool(appPoolId.Name);
Application rootApp = site.Applications["/"];
if (rootApp == null) {
throw new ApiArgumentException("application_pool", "Root application does not exist.");
}
// REVIEW: Should we create the root application if it doesn't exist and they specify an application pool?
// We decided not to do this for physical_path.
// Application pool for a site is extracted from the site's root application
rootApp.ApplicationPoolName = pool.Name;
}
return site;
}
private static void SetBinding(Binding binding, dynamic obj) {
string protocol = DynamicHelper.Value(obj.protocol);
string bindingInformation = DynamicHelper.Value(obj.binding_information);
bool? requireSni = DynamicHelper.To<bool>(obj.require_sni);
if (protocol == null) {
throw new ApiArgumentException("binding.protocol");
}
binding.Protocol = protocol;
bool isHttp = protocol.Equals("http") || protocol.Equals("https");
if (isHttp) {
//
// HTTP Binding information provides port, ip address, and hostname
UInt16 port;
string hostname;
IPAddress ipAddress = null;
if (bindingInformation == null) {
var ip = DynamicHelper.Value(obj.ip_address);
if (ip == "*") {
ipAddress = IPAddress.Any;
}
else if (!IPAddress.TryParse(ip, out ipAddress)) {
throw new ApiArgumentException("binding.ip_address");
}
UInt16? p = (UInt16?)DynamicHelper.To(obj.port, 1, UInt16.MaxValue);
if (p == null) {
throw new ApiArgumentException("binding.port");
}
port = p.Value;
hostname = DynamicHelper.Value(obj.hostname) ?? string.Empty;
}
else {
var parts = bindingInformation.Split(':');
if (parts.Length != 3) {
throw new ApiArgumentException("binding.binding_information");
}
if (parts[0] == "*") {
ipAddress = IPAddress.Any;
}
else if (!IPAddress.TryParse(parts[0], out ipAddress)) {
throw new ApiArgumentException("binding.binding_information");
}
if (!UInt16.TryParse(parts[1], out port)) {
throw new ApiArgumentException("binding.binding_information");
}
hostname = parts[2];
}
binding.Protocol = protocol;
// HTTPS
if (protocol.Equals("https")) {
if (string.IsNullOrEmpty(hostname) && requireSni.HasValue && requireSni.Value) {
throw new ApiArgumentException("binding.require_sni");
}
if (obj.certificate == null || !(obj.certificate is JObject)) {
throw new ApiArgumentException("binding.certificate");
}
dynamic certificate = obj.certificate;
string uuid = DynamicHelper.Value(certificate.id);
if (string.IsNullOrEmpty(uuid)) {
throw new ApiArgumentException("binding.certificate.id");
}
CertificateId id = new CertificateId(uuid);
ICertificateStore store = CertificateStoreProviderAccessor.Instance?.Stores
.FirstOrDefault(s => s.Name.Equals(id.StoreName, StringComparison.OrdinalIgnoreCase));
ICertificate cert = null;
if (store != null) {
cert = store.GetCertificate(id.Id).Result;
}
if (cert == null) {
throw new NotFoundException("binding.certificate");
}
if (!cert.PurposesOID.Contains(OIDServerAuth)) {
throw new ApiArgumentException("binding.certificate", "Certificate does not support server authentication");
}
//
// Windows builtin store
if (store is IWindowsCertificateStore) {
// The specified certificate must be in the store with a private key or else there will be an exception when we commit
if (cert == null) {
throw new NotFoundException("binding.certificate");
}
if (!cert.HasPrivateKey) {
throw new ApiArgumentException("binding.certificate", "Certificate must have a private key");
}
List<byte> bytes = new List<byte>();
// Decode the hex string of the certificate hash into bytes
for (int i = 0; i < id.Id.Length; i += 2) {
bytes.Add(Convert.ToByte(id.Id.Substring(i, 2), 16));
}
binding.CertificateStoreName = id.StoreName;
binding.CertificateHash = bytes.ToArray();
}
//
// IIS Central Certificate store
else if (store is ICentralCertificateStore) {
string name = Path.GetFileNameWithoutExtension(cert.Alias);
if (string.IsNullOrEmpty(hostname) || !hostname.Replace('*', '_').Equals(name)) {
throw new ApiArgumentException("binding.hostname", "Hostname must match certificate file name for central certificate store");
}
binding.SslFlags |= SslFlags.CentralCertStore;
}
if (requireSni.HasValue) {
if (!binding.Schema.HasAttribute(sslFlagsAttribute)) {
// throw on IIS 7.5 which does not have SNI support
throw new ApiArgumentException("binding.require_sni", "SNI not supported on this machine");
}
if (requireSni.Value) {
binding.SslFlags |= SslFlags.Sni;
}
else {
binding.SslFlags &= ~SslFlags.Sni;
}
}
}
var ipModel = ipAddress.Equals(IPAddress.Any) ? "*" : ipAddress.ToString();
binding.BindingInformation = $"{ipModel}:{port}:{hostname}";
}
else {
//
// Custom protocol
if (string.IsNullOrEmpty(bindingInformation)) {
throw new ApiArgumentException("binding.binding_information");
}
binding.BindingInformation = bindingInformation;
}
}
private static object ToJsonModel(Binding binding)
{
dynamic obj = new ExpandoObject();
obj.protocol = binding.Protocol;
obj.binding_information = binding.BindingInformation;
bool isHttp = binding.Protocol.Equals("http") || binding.Protocol.Equals("https");
if (isHttp) {
string ipAddress = null;
int? port = null;
if (binding.EndPoint != null && binding.EndPoint.Address != null) {
port = binding.EndPoint.Port;
if (binding.EndPoint.Address != null) {
ipAddress = binding.EndPoint.Address.Equals(IPAddress.Any) ? "*" : binding.EndPoint.Address.ToString();
}
}
obj.ip_address = ipAddress;
obj.port = port;
obj.hostname = binding.Host;
//
// HTTPS
if (binding.Protocol.Equals("https")) {
ICertificateStore store = null;
// Windows store
if (binding.CertificateStoreName != null) {
string thumbprint = binding.CertificateHash == null ? null : BitConverter.ToString(binding.CertificateHash)?.Replace("-", string.Empty);
store = CertificateStoreProviderAccessor.Instance?.Stores
.FirstOrDefault(s => s.Name.Equals(binding.CertificateStoreName, StringComparison.OrdinalIgnoreCase));
// Certificate
if (store != null) {
obj.certificate = CertificateHelper.ToJsonModelRef(GetCertificate(() => store.GetCertificate(thumbprint).Result));
}
}
// IIS Central Certificate Store
else if (binding.Schema.HasAttribute(sslFlagsAttribute) && binding.SslFlags.HasFlag(SslFlags.CentralCertStore) && !string.IsNullOrEmpty(binding.Host)) {
ICentralCertificateStore centralStore = null;
if (PathUtil.IsValidFileName(binding.Host)) {
centralStore = CertificateStoreProviderAccessor.Instance?.Stores.FirstOrDefault(s => s is ICentralCertificateStore) as ICentralCertificateStore;
}
// Certificate
if (centralStore != null) {
obj.certificate = CertificateHelper.ToJsonModelRef(GetCertificate(() => centralStore.GetCertificateByHostName(binding.Host.Replace('*', '_')).Result));
}
}
//
// Ssl Flags
if (binding.Schema.HasAttribute(sslFlagsAttribute)) {
obj.require_sni = binding.SslFlags.HasFlag(SslFlags.Sni);
}
}
}
return obj;
}
private static long FirstAvailableId()
{
ServerManager sm = ManagementUnit.ServerManager;
for (long id = 1; id <= long.MaxValue; id++) {
if (!sm.Sites.Any(site => site.Id == id)) {
return id;
}
}
throw new Exception("No available Id");
}
private static ICertificate GetCertificate(Func<ICertificate> retreiver)
{
try {
return retreiver();
}
catch (AggregateException) {
return null;
}
}
}
}
|
#!/bin/sh
#
PATH=/bin:/usr/bin:/usr/local/bin:.; export PATH
#
. mux.config
#
# You'll want to use gzip if you have it. If you want really good
# compression, try 'gzip --best'. If you don't have gzip, use 'compress'.
# ZIP=gzip
#
DBDATE=`date +%m%d-%H%M`
#
if [ "$1" -a -r "$1" ]; then
echo "Using flatfile from $1, renaming to $DATA/$GAMENAME.$DBDATE"
mv $1 $DATA/$GAMENAME.$DBDATE
elif [ -r $DATA/$NEW_DB ]; then
$BIN/netmux -d$DATA/$GDBM_DB -i$DATA/$NEW_DB -o$DATA/$GAMENAME.$DBDATE -u
elif [ -r $DATA/$INPUT_DB ]; then
echo "No recent checkpoint db. Using older db."
$BIN/netmux -d$DATA/$GDBM_DB -i$DATA/$INPUT_DB -o$DATA/$GAMENAME.$DBDATE -u
elif [ -r $DATA/$SAVE_DB ]; then
echo "No input db. Using backup db."
$BIN/netmux -d$DATA/$GDBM_DB -i$DATA/$SAVE_DB -o$DATA/$GAMENAME.$DBDATE -u
else
echo "No dbs. Backup attempt failed."
fi
cd $DATA
if [ -r $GAMENAME.$DBDATE ]; then
FILES=$GAMENAME.$DBDATE
else
echo "No flatfile found. Aborting."
exit
fi
if [ -r comsys.db ]; then
cp comsys.db comsys.db.$DBDATE
FILES="$FILES comsys.db.$DBDATE"
else
echo "Warning: no comsys.db found."
fi
if [ -r mail.db ]; then
cp mail.db mail.db.$DBDATE
FILES="$FILES mail.db.$DBDATE"
else
echo "Warning: no mail.db found."
fi
# FILES=$GAMENAME.$DBDATE comsys.db.$DBDATE mail.db.$DBDATE
echo "Compressing and removing files: $FILES"
tar czf dump.$DBDATE.tgz $FILES && rm -f $FILES &
|
namespace Polity
{
public class Product
{
public ProductType Type { get; set; }
public double Amount { get; set; }
public override string ToString() => Type.Name + " (" + Amount + ")";
public Product() { }
public Product(ProductType type, double amount)
{
Type = type;
Amount = amount;
}
}
}
|
#!/usr/bin/env bash
. env.sh
echo
### Fail to create because of missing tokens.
mantra-oracle create $CONFIG $ADDRESS_0 $PAYMENT_0 $DATUM_0 2>/dev/null
assert_failure "01a No creation without tokens."
### Fail to create because of incorrect signing key.
mantra-oracle create $CONFIG $ADDRESS_1 $PAYMENT_0 $DATUM_0 2>/dev/null
assert_failure "01b No creation with bad key."
### Create.
mantra-oracle create $CONFIG $ADDRESS_1 $PAYMENT_1 $DATUM_0
assert_success "01c Creation."
### Record transaction.
echo "Run query.sh to find the resulting transaction and enter that as TXID_2 in local.sh."
|
describe BookmarksController do
# initialize any recurring objects
let(:bookmark) { build(:bookmark) }
let(:student) { build(:student, id: 1) }
let(:instructor) { build(:instructor, id: 2) }
let(:ta) { build(:teaching_assistant, id: 3) }
# for student
describe '#action_allowed?' do
context 'when params action pertains to student minus edit, update, destroy' do
before(:each) do
@session = {user: student}
stub_current_user(student, student.role.name, student.role)
@request.session[:user] = student
end
let(:controller) { BookmarksController.new }
it 'allows list action for student' do
controller.params = {action: 'list'}
expect(controller.action_allowed?).to eq("Student")
end
it 'allows new action for student' do
controller.params = {action: 'new'}
expect(controller.action_allowed?).to eq("Student")
end
it 'allows save_bookmark_rating_score action for student' do
controller.params = {action: 'save_bookmark_rating_score'}
expect(controller.action_allowed?).to eq("Student")
end
it 'allows create action for student' do
controller.params = {action: 'create'}
expect(controller.action_allowed?).to eq("Student")
end
end
end
# for instructor
describe '#action_allowed?' do
before(:each) do
@session = {user: instructor}
stub_current_user(instructor, instructor.role.name, instructor.role)
@request.session[:user] = instructor
end
it 'allows list action for instructor' do
controller.params = {action: 'list'}
expect(controller.action_allowed?).to eq("Instructor")
end
it 'not allow list action for instructor' do
controller.params = {action: 'list'}
expect(controller.action_allowed?).not_to eq("Student")
end
end
# for teaching assistant
describe '#action_allowed?' do
before(:each) do
@session = {user: instructor}
stub_current_user(ta, ta.role.name, ta.role)
@request.session[:user] = ta
end
it 'allows list action for ta' do
controller.params = {action: 'list'}
expect(controller.action_allowed?).to eq("Teaching Assistant")
end
it 'not allow list action for ta' do
controller.params = {action: 'list'}
expect(controller.action_allowed?).not_to eq("Student")
end
end
# for special cases of edit, update, destroy params actions
describe '#action_allowed?' do
context 'when edit, update, destroy params action pertains to student' do
before(:each) do
allow(Bookmark).to receive(:find).with(1).and_return(bookmark)
@session = {user: student}
@request.session[:user] = student
end
it 'allows edit action' do
controller.params = {id: '1', action: 'edit'}
expect(controller.action_allowed?).to eq("Student")
end
it 'allows update action' do
controller.params = {id: '1', action: 'update'}
expect(controller.action_allowed?).to eq("Student")
end
it 'allows destroy action' do
controller.params = {id: '1', action: 'destroy'}
expect(controller.action_allowed?).to eq("Student")
end
end
end
describe '#specific_average_score' do
context 'check corner cases for specific_average_score' do
let(:controller) { BookmarksController.new }
it 'score is null' do
nullBookmark = nil
expect(controller.specific_average_score(nullBookmark)).to eq('-')
end
end
end
describe '#total_average_score' do
context 'check corner cases for total_average_score' do
let(:controller) { BookmarksController.new }
it 'score is null' do
nullBookmark = nil
expect(controller.total_average_score(nullBookmark)).to eq('-')
end
end
end
end
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module UCap.Domain.Const where
import UCap.Domain.Classes
import Data.InfSet (InfSet)
import qualified Data.InfSet as IS
import Data.Aeson
import Data.Biapplicative
import GHC.Generics
{-| t'ConstE' wraps an effect domain (@e@), adding an effect that
replaces the current state with a given value.
@
'eFun' ('ConstE' s) = 'Data.Function.const' s = (\\_ -> s)
@
Effects from the wrapped domain can be used with 'ModifyE'.
@
'eFun' ('ModifyE' e) s = 'eFun' e s
@
-}
data ConstE e s
= ConstE s
| ModifyE e
deriving (Show,Eq,Ord,Generic)
instance (ToJSON e, ToJSON s) => ToJSON (ConstE e s) where
toEncoding = genericToEncoding defaultOptions
instance (FromJSON e, FromJSON s) => FromJSON (ConstE e s)
instance (EffectDom e, EDState e ~ s) => Semigroup (ConstE e s) where
_ <> ConstE s = ConstE s
ModifyE e1 <> ModifyE e2 = ModifyE (e1 <> e2)
ConstE s <> ModifyE e = ConstE (eFun e s)
instance (EffectDom e, EDState e ~ s) => Monoid (ConstE e s) where
mempty = ModifyE mempty
instance (EffectDom e, EDState e ~ s) => EffectDom (ConstE e s) where
type EDState (ConstE e s) = s
eFun (ConstE s) = const s
eFun (ModifyE e) = eFun e
type family ConstE' e where
ConstE' e = ConstE e (EDState e)
data ConstC c s
= ConstC { setVals :: InfSet s, lowerC :: c }
deriving (Eq,Ord,Generic)
type family ConstC' c where
ConstC' c = ConstC c (CState c)
instance (Ord s, Show c, Show s, BMeet c, Monoid c) => Show (ConstC c s) where
show c | uniC <=? c = "uniC"
show c | c <=? idC = "idC"
show (ConstC s c) | IS.isEmpty s = show c
| otherwise = "ConstC(" ++ show s ++ "," ++ show c ++ ")"
instance (ToJSON c, ToJSON s) => ToJSON (ConstC c s)
instance (Ord s, ToJSON c, ToJSONKey c, ToJSON s, ToJSONKey s) => ToJSONKey (ConstC c s)
instance (Ord s, FromJSON c, FromJSON s) => FromJSON (ConstC c s)
instance (Ord s, FromJSON c, FromJSONKey c, FromJSON s, ToJSONKey s) => FromJSONKey (ConstC c s)
instance (Ord s, Semigroup c) => Semigroup (ConstC c s) where
ConstC s1 c1 <> ConstC s2 c2 =
ConstC (IS.union s1 s2) (c1 <> c2)
instance (Ord s, Monoid c) => Monoid (ConstC c s) where
mempty = ConstC IS.empty mempty
instance (Ord s, Meet c) => Meet (ConstC c s) where
meet (ConstC s1 c1) (ConstC s2 c2) =
ConstC (s1 `IS.intersection` s2) (c1 `meet` c2)
ConstC s1 c1 <=? ConstC s2 c2 = (s1 `IS.isSubsetOf` s2) && (c1 <=? c2)
instance (Ord s, BMeet c) => BMeet (ConstC c s) where
meetId = ConstC IS.universal meetId
instance (Ord s, Split c) => Split (ConstC c s) where
split (ConstC s1 c1) (ConstC s2 c2)
| s2 <=? s1 = failToEither $ ConstC s1 <<$$>> splitWF c1 c2
| otherwise = failToEither $
ConstC <<$$>> DidFail (s2 `IS.difference` s1)
<<*>> splitWF c1 c2
instance (Ord s, Meet c, Cap c, Split c, CState c ~ s) => Cap (ConstC c s) where
type CEffect (ConstC c s) = ConstE (CEffect c) s
mincap (ConstE s) = ConstC (IS.singleton s) mempty
mincap (ModifyE e) = ConstC IS.empty (mincap e)
undo (ConstE _) = idC
undo (ModifyE e) = modifyC (undo e)
weaken (ConstC s1 c1) (ConstC s2 c2)
| s2 <=? s1 = ModifyE <$> weaken c1 c2
weaken _ _ = Nothing
constC :: (Ord s, Monoid c) => [s] -> ConstC c s
constC ss = ConstC (IS.fromList ss) mempty
constC' :: (Monoid c) => InfSet s -> ConstC c s
constC' s = ConstC s mempty
constAny :: (Monoid c) => ConstC c s
constAny = ConstC IS.universal mempty
modifyC :: c -> ConstC c s
modifyC c = ConstC IS.empty c
|
<?php
session_start();
/*$a1 = 10;
$a2 = 5;
$a3 = $a1 * $a2;
echo $a3.', ';
if ($a3 == 50) {
echo "50";
} else if ($a3 > 50) {
echo "0";
} else {
†
echo "100";
}
$q1 = true;
$q2 = false;
*/
$ios = array();
if (isset($_POST["ua"])) {
$white = rand(1, 9);
echo $white.'<br>';
if ($white == 2 or $white == 5) {
echo 'У меня всё получилось';
}
echo '<hr>';
for ($i==1; $i<$white; $i++) {
echo $i.'<br>';
$ios[$i][] = rand(99, 999);
$ios[$i][] = rand(99, 999);
}
foreach ($ios as $key => $value) {
echo $value[0]. " - ".$value[1]."<br>";
}
}
//$_SESSION["ya"] = 1;
//echo "<pre>";
//print_r($ios);
//echo "</pre>";
?>
<form action="" method="POST">
<input type="text" name="ua">
<button type="submit" name="ea">Отправить</button>
</form>
|
function FormulaDataService($http, $rootScope, LoginService, URL, EVENTS) {
function _on_mathml_received() {
$rootScope.$broadcast(EVENTS.MATHML_RECEIVED);
}
function _on_formula_categories_received() {
$rootScope.$broadcast(EVENTS.FORMULA_CATEGORIES_RECEIVED);
}
function _on_formula_received() {
$rootScope.$broadcast(EVENTS.FORMULA_RECEIVED);
}
function _on_formula_created() {
$rootScope.$broadcast(EVENTS.FORMULA_CREATED);
}
function _on_formula_updated() {
$rootScope.$broadcast(EVENTS.FORMULA_UPDATED);
}
function _on_formula_deleted() {
$rootScope.$broadcast(EVENTS.FORMULA_DELETED);
}
function _on_formula_search_received() {
$rootScope.$broadcast(EVENTS.FORMULA_SEARCH_RECEIVED);
}
function _on_error(response) {
if (response.status > 0) {
console.error(response);
}
}
function _update_formula_categories(newData) {
formulaCategories = newData;
}
function _update_formulas(newData) {
formulas = newData;
}
function _update_updated_formula(newData) {
updatedFormula = newData;
}
function _update_mathml_formula(newData) {
formulaMathml = newData;
}
function _update_formula_results(newData) {
formulaResults = newData;
}
function _update_deleted_formula(newData) {
deletedFormula = newData;
}
let formulaMathml = null;
let formulaCategories = null;
let formulas = null;
let formulaResults = null;
let deletedFormula = null;
let updatedFormula = null;
this.getFormulaCategories = function() {
return formulaCategories;
}
this.getMathmlFormula = function() {
return formulaMathml;
}
this.getDeletedFormula = function() {
return deletedFormula;
}
this.getFormulas = function() {
return formulas;
}
this.getUpdatedFormula = function() {
return updatedFormula;
}
this.getFormulaResults = function() {
return formulaResults;
}
this.retrieveFormulaCategories = function() {
if (formulaCategories) { _on_formula_categories_received(); }
return $http.get(URL.GET_FORMULA_CATEGORIES, {
ignoreLoadingBar: true
}).then(
function success(response) {
_update_formula_categories(response.data);
_on_formula_categories_received();
},
function error(response) {
_on_error(response);
});
}
this.retrieveMathml = function(data) {
let formulaData = {
"formula": data
}
return $http.post(URL.CHECK_MATHML, JSON.stringify(formulaData), {
ignoreLoadingBar: true
})
.then(
function success(response) {
_update_mathml_formula(response.data);
_on_mathml_received();
},
function error(response) {
_on_error(response);
});
}
this.retrieveFormulas = function() {
return $http.get(URL.GET_FORMULAS, {
ignoreLoadingBar: true
}).then(
function success(response) {
_update_formulas(response.data);
_on_formula_received();
},
function error(response) {
_on_error(response);
});
}
this.createFormula = function(data) {
let formulaData = {
"formula": data,
"username": "admin",
"password": "123456"
}
return $http.post(URL.CREATE_UPDATE_FORMULA, JSON.stringify(formulaData))
.then(function success(response) {
console.log(response);
_on_formula_created();
}, function error(response) {
_on_error(response);
});
}
this.updateFormula = function(data) {
let formulaData = {
"formula": data,
"username": "admin",
"password": "123456"
}
return $http.patch(URL.CREATE_UPDATE_FORMULA, JSON.stringify(formulaData))
.then(function success(response) {
_update_updated_formula(response.data);
_on_formula_updated();
}, function error(response) {
_on_error(response);
});
}
this.deleteFormula = function(data) {
let formulaData = {
"formula": data,
"username": "admin",
"password": "123456"
}
return $http.post(URL.DELETE_FORMULA, JSON.stringify(formulaData))
.then(function success(response) {
if (!!response.data) {
_update_deleted_formula(response.data);
}
console.log(response);
_on_formula_deleted();
}, function error(response) {
_on_error(response);
});
}
this.reindexFormula = function(data) {
let postData = {
"username": "admin",
"password": "123456",
};
return $http({
method: 'POST',
url: URL.REINDEX_FORMULA,
data: JSON.stringify(postData),
headers: data.headers,
ignoreLoadingBar: true
}).then(function success(response) {
console.log(response)
},
function error(response) {
_on_error(response);
});
}
this.searchFormula = function(query) {
let startTime = new Date();
return $http.get(URL.SEARCH_FORMULA + encodeURIComponent(query), {
ignoreLoadingBar: true
})
.then(function success(response) {
let endTime = new Date();
// console.log(response.data);
// console.log("Time elapsed: " + (endTime - startTime));
_update_formula_results(response.data);
_on_formula_search_received();
}, function error(response) {
_on_error(response)
});
}
}
export default ['$http', '$rootScope', 'LoginService', 'URL', 'EVENTS', FormulaDataService]; |
package uk.sky.cqlmigrate;
import org.junit.Before;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.internal.verification.VerificationModeFactory.times;
@SuppressWarnings("unchecked")
public class RetryTaskTest {
private RetryTask retryTask;
private Callable<Boolean> aTask;
@Before
public void setup() {
aTask = (Callable<Boolean>) mock(Callable.class);
retryTask = RetryTask.attempt(aTask)
.withPollingInterval(Duration.ofSeconds(10))
.withTimeout(Duration.ofSeconds(10));
}
@Test
public void shouldReturnValueIfPredicateIsSuccessful() throws Throwable {
//given
String expectedResult = "Success";
given(aTask.call()).willReturn(true);
//when
String result = retryTask.untilSuccess().thenReturn(() -> "Success");
//then
assertThat(result).isEqualTo(expectedResult);
}
@Test
@SuppressWarnings("unchecked")
public void shouldCompleteIfPredicateIsSuccessful() throws Throwable {
//given
given(aTask.call()).willReturn(true);
retryTask = RetryTask.attempt(aTask)
.withPollingInterval(Duration.ofSeconds(10))
.withTimeout(Duration.ofSeconds(10));
//when
retryTask.execute();
//then
verify(aTask).call();
}
@Test
@SuppressWarnings("unchecked")
public void shouldRetryAsManyTimesAsNecessaryUntilSuccess() throws Throwable {
//given
given(aTask.call()).willReturn(false, false, true);
RetryTask retryTask = RetryTask.attempt(aTask)
.withPollingInterval(Duration.ofMillis(5))
.withTimeout(Duration.ofSeconds(10));
//when
retryTask.untilSuccess();
//then
verify(aTask, times(3)).call();
}
@Test
@SuppressWarnings("unchecked")
public void shouldWaitConfiguredPollingIntervalBeforeRetrying() throws Throwable {
//given
given(aTask.call()).willReturn(false, false, true);
RetryTask retryTask = RetryTask.attempt(aTask)
.withPollingInterval(Duration.ofMillis(5))
.withTimeout(Duration.ofSeconds(10));
Instant approximateStartTime = Instant.now();
//when
retryTask.untilSuccess();
Instant approximateEndTime = Instant.now();
//then
assertThat(Duration.between(approximateStartTime, approximateEndTime)).isGreaterThanOrEqualTo(Duration.ofMillis(5 * 2));
}
@Test
public void shouldTimeoutIfElapsedTimeGoesBeyondConfiguredValue() throws Throwable {
//given
Callable<Boolean> aTask = () -> {
Thread.sleep(3);
return false;
};
RetryTask retryTask = RetryTask.attempt(aTask)
.withPollingInterval(Duration.ofMillis(5))
.withTimeout(Duration.ofMillis(6));
//when
Throwable throwable = catchThrowable(retryTask::execute);
//then
assertThat(throwable)
.isInstanceOf(TimeoutException.class)
.hasMessageStartingWith("Timed out after waiting ")
.hasMessageEndingWith(" ms, with timeout 6 ms");
}
@Test
@SuppressWarnings("unchecked")
public void shouldThrowInterruptedExceptionIfInterruptedWhileWaitingThePollingInterval() throws Throwable {
//given
given(aTask.call()).willReturn(false, true);
RetryTask retryTask = RetryTask.attempt(aTask)
.withPollingInterval(Duration.ofMillis(5))
.withTimeout(Duration.ofMillis(6));
Thread.currentThread().interrupt();
//when
Throwable throwable = catchThrowable(retryTask::execute);
//then
assertThat(throwable).isInstanceOf(InterruptedException.class);
}
@Test
public void shouldWrapCheckedExceptionsFromExecutionInRuntimeException() throws Throwable {
//given
Callable<Boolean> aTask = () -> { throw new FileNotFoundException("Dummy checked exception"); };
RetryTask retryTask = RetryTask.attempt(aTask)
.withPollingInterval(Duration.ofMillis(5))
.withTimeout(Duration.ofMillis(6));
//when
Throwable throwable = catchThrowable(retryTask::execute);
//then
assertThat(throwable)
.isInstanceOf(RuntimeException.class)
.hasCauseInstanceOf(FileNotFoundException.class);
}
@Test
public void checksThatTimeoutIsSet() throws Throwable {
//given
RetryTask retryTask = RetryTask.attempt(() -> true).withPollingInterval(Duration.ofHours(1));
//when
Throwable throwable = catchThrowable(retryTask::execute);
//then
assertThat(throwable)
.isInstanceOf(IllegalStateException.class)
.hasMessage("timeout has not been configured");
}
@Test
public void checksThatPollingIntervalIsSet() throws Throwable {
//given
RetryTask retryTask = RetryTask.attempt(() -> true).withTimeout(Duration.ofHours(1));
//when
Throwable throwable = catchThrowable(retryTask::execute);
//then
assertThat(throwable)
.isInstanceOf(IllegalStateException.class)
.hasMessage("polling interval has not been configured");
}
} |
<?php
if (!defined('THINK_PATH')) exit();
$config = require './config.php';
$HTTP_HOST = "http://" . $_SERVER['HTTP_HOST'];
$HOST_DIR = dirname($_SERVER['PHP_SELF']);
if ($HOST_DIR != '/') {
$HTTP_HOST = $HTTP_HOST . $HOST_DIR;
}
$mail_config['config']['smtp_server'] = 'mail.yx1758.com';
$mail_config['config']['smtp_port'] = '25';
$mail_config['config']['smtp_user'] = '[email protected]';
$mail_config['config']['smtp_password'] = 'ZTdiYKol';
$partner_login_types = array('sina', 't', 'qq', 'reren', 'msn');
$array = array(
'URL_CASE_INSENSITIVE' => true,
'URL_MODEL' => 1,
'URL_HTML_SUFFIX' => '.html',
'HTTP_HOST' => $HTTP_HOST,
'COOKIE_DOMAIN' => 'www.peixun.com', //cookie的有效域名
'COOKIE_PATH' => '/Home', //保存路径
//'COOKIE_PREFIX' => 'test_', //cookie的前缀
'JS_REGEXP_USER_NAME' => '\/\^\[\\w\\d\\.@_]{4,16}\$\/i',
'JS_REGEXP_PASSWORD' => '\/\^\\w\{6,12\}\$\/i',
'PARTNER_LOGIN_TYPES' => $partner_login_types,
'LAYOUT_ON' => true,
'TMPL_STRIP_SPACE' => false,
'VAR_PAGE' => 'p',
'TMPL_EXCEPTION_FILE' => APP_PATH . '/Tpl/Theme/Public/exception.html',
'EMAIL_CONFIG' => $mail_config,#邮件发送配制
'PAGE_RECORDS_NUMBER' => '20',//分页,每页的记录数
'DB_FIELD_CACHE' => false,
'HTML_CACHE_ON' => false,
'APP_DEBUG' => true,
'SESSION_AUTO_START' => true,
'APP_AUTOLOAD_PATH' => '@.TagLib,@.ORG',
'APP_DEBUG' => true,
'URL_CASE_INSENSITIVE' => true,
'SHOW_PAGE_TRACE' => false,
'DATA_CACHE_TYPE' => 'file',
'APP_AUTOLOAD_PATH' => '@.TagLib,@.ORG',
'TMPL_SWITCH_ON' => true,
'TMPL_DETECT_THEME' => true,
'DEFAULT_THEME' => 'default',
'PAY_KEY' => 's@#d*&w8uy^s2ayo.pay',
//上传配置
'UPLOAD_PATH' => 'Uploads/',//文件上传路径
'UPLOAD_IMAGE_MAX_SIZE' => 5242880,//2Mb,允许上传图片的最大尺寸(单位byte)
'UPLOAD_FILE_MAX_SIZE' => 5242880,//5Mb,允许上传文件的最大尺寸(单位byte)
'ITEM_THUMB' => array(
array(
'100',
'100'
),
array(
'232',
'232'
),
array(
'430',
'430'
),
array(
'800',
'800'
)
), //商品缩略图设置
'ITEM_UPLOAD_DIR' => '/Uploads/Item/', //商品图片上传目录
'ITEM_UPLOAD_SIZE' => 5,//商品上传图片大小限制2M
'ATTACHMENTS_UPLOAD_DIR' => '/Uploads/Attachments/',
// 'HTML_CACHE_ON'=>true,
// 'HTML_CACHE_RULES'=> array(
// 'index:index'=>array('Index/index',3600, ''),
// 'index:newsCenter'=>array('Index/newsCenter',3600, ''),
// //'Index:index'=>array('Index/{:action}','600'),
// ),
);
//第三方登录配置参数
$oauthConfig = array(
'qq' => array(
'APIURL' => 'https://graph.qq.com/shuoshuo/add_topic',
'AUTHORIZE_URL' => 'https://graph.qq.com/oauth2.0/authorize',
'ACCESS_TOKEN_URL' => 'https://graph.qq.com/oauth2.0/token',
'OPENID_TOKEN_URL' => 'https://graph.qq.com/oauth2.0/me',
'GET_USERINFO_URL' => 'https://graph.qq.com/user/get_user_info',
'APPID' => '100299306',
'SECRET' => '699bb49dea940a9d2a53e39c4291ef0e',
'SCOPE' => 'get_user_info,add_topic'
),
'sina' => array(
'APIURL' => 'https://api.weibo.com/2/statuses/update.json',
'AUTHORIZE_URL' => 'https://api.weibo.com/oauth2/authorize',
'ACCESS_TOKEN_URL' => 'https://api.weibo.com/oauth2/access_token',
'GET_USERINFO_URL' => 'https://api.weibo.com/2/users/show.json',
'APPID' => '3627684483',
'SECRET' => '67ebe64f2d8c1d199d2174789992770e'
),
'renren' => array(
'APIURL' => 'feed.publishFeed',
'AUTHORIZE_URL' => 'https://graph.renren.com/oauth/authorize',
'ACCESS_TOKEN_URL' => 'http://graph.renren.com/oauth/token',//人人网可以得到昵称跟图片
'APPID' => '210438',
'APPKEY' => '34adfb82d12443dd924eeba8784c7f83',
'SECRET' => 'ef39db2485854404801218601cc14eef',
'SCOPE' => 'publish_feed'
),
'qqweibo' => array(
'APIURL' => 'https://open.t.qq.com/api/t/add',
'AUTHORIZE_URL' => 'https://open.t.qq.com/cgi-bin/oauth2/authorize',
'ACCESS_TOKEN_URL' => 'https://open.t.qq.com/cgi-bin/oauth2/access_token',
'GET_USERINFO_URL' => 'https://open.t.qq.com/api/user/other_info',
'APPID' => '801226208',
'SECRET' => 'b488d9c75f006f0a70d2ea2fced794ed'
),
'douban' => array(
'APIURL' => 'https://api.douban.com/shuo/v2/statuses/',
'AUTHORIZE_URL' => 'https://www.douban.com/service/auth2/auth',
'ACCESS_TOKEN_URL' => 'https://www.douban.com/service/auth2/token',
'GET_USERINFO_URL' => 'https://api.douban.com/v2/user/',//后面拼接UID:67798716
'APPID' => '03d9267692374e4a0b8b7363b6a5eade',
'SECRET' => '873577fb495c04e0',
'SCOPE' => 'shuo_basic_w'
)
);
return array_merge($config, $array, $oauthConfig);
?> |
@testset "SimpleCovariance" begin
v = simple()
@test sprint(show, v) == "Simple covariance estimator"
end
@testset "RobustCovariance" begin
v = robust()
@test sprint(show, v) == "Heteroskedasticity-robust covariance estimator"
end
@testset "ClusterCovariance" begin
@test_throws MethodError cluster()
c1 = cluster(:a)
@test names(c1) == (:a,)
@test length(c1) == 1
c2 = cluster(:a, :b)
@test names(c2) == (:a, :b)
@test length(c2) == 2
@test sprint(show, c1) == "Cluster-robust covariance estimator"
@test sprint(show, MIME("text/plain"), c1) == """
1-way cluster-robust covariance estimator:
a"""
@test sprint(show, MIME("text/plain"), c2) == """
2-way cluster-robust covariance estimator:
a
b"""
N = 10
a1 = collect(1:N)
g1 = group(a1)
c1 = cluster((:a,), (g1,))
@test nclusters(c1) == (a=N,)
end
|
using LambdaSharp.App.EventBus;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Test.LambdaSharp.App.EventBus.EventPatternMatcherTests {
public class IsMatch {
//--- Methods ---
[Fact]
public void Empty_event_is_not_matched() {
// arrange
var evt = JObject.Parse(@"{}");
var pattern = JObject.Parse(@"{
""Foo"": [ ""Bar"" ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeFalse();
}
[Fact]
public void Event_with_literal_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ ""Bar"" ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_list_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": [ ""Bar"" ]
}");
var pattern = JObject.Parse(@"{
""Foo"": [ ""Bar"" ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_empty_is_not_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": [ ]
}");
var pattern = JObject.Parse(@"{
""Foo"": [ ""Bar"" ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeFalse();
}
[Fact]
public void Event_with_prefix_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""prefix"": ""B"" } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_prefix_is_not_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""prefix"": ""F"" } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeFalse();
}
[Fact]
public void Event_with_anything_but_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""anything-but"": { ""prefix"": ""F"" } } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_anything_but_is_not_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""anything-but"": { ""prefix"": ""B"" } } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeFalse();
}
[Fact]
public void Event_with_numeric_one_operation_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": 42
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""numeric"": [ "">="", 40 ] } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_numeric_two_operation_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": 42
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""numeric"": [ "">="", 40, ""<"", 404 ] } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_numeric_one_operation_type_mismatch_is_not_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""numeric"": [ "">="", 40 ] } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeFalse();
}
[Fact]
public void Event_with_cidr_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""192.168.1.42""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""cidr"": ""192.168.1.1/24"" } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_cidr_out_of_range_is_not_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""192.168.16.42""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""cidr"": ""192.168.1.1/24"" } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeFalse();
}
[Fact]
public void Event_with_cidr_mismatch_is_not_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""cidr"": ""192.168.1.1/24"" } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeFalse();
}
[Fact]
public void Event_with_exists_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": ""Bar""
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""exists"": true } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_not_exists_is_matched() {
// arrange
var evt = JObject.Parse(@"{}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""exists"": false } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_not_exists_on_non_leaf_node_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": {
""Bar"": ""ABC""
}
}");
var pattern = JObject.Parse(@"{
""Foo"": [ { ""exists"": false } ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_nested_literal_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": {
""Bar"": ""ABC""
}
}");
var pattern = JObject.Parse(@"{
""Foo"": {
""Bar"": [ ""ABC"" ]
}
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_nested_prefix_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": {
""Bar"": ""ABC""
}
}");
var pattern = JObject.Parse(@"{
""Foo"": {
""Bar"": [ { ""prefix"": ""A"" } ]
}
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
[Fact]
public void Event_with_multiple_is_matched() {
// arrange
var evt = JObject.Parse(@"{
""Foo"": {
""Bar"": ""ABC""
},
""Bar"": 42
}");
var pattern = JObject.Parse(@"{
""Foo"": {
""Bar"": [ { ""prefix"": ""A"" } ]
},
""Bar"": [ 40, 41, 42 ]
}");
// act
var isMatch = EventPatternMatcher.IsMatch(evt, pattern);
// assert
isMatch.Should().BeTrue();
}
}
}
|
ALTER TABLE Users
ADD COLUMN `isSuperMentor` TINYINT(1) DEFAULT '0',
ADD COLUMN `isMentor` TINYINT(1) DEFAULT '0';
|
// To parse this JSON data, do
//
// final postModel = postModelFromMap(jsonString);
import 'dart:convert';
class PostModel {
PostModel(
{required this.tipo,
this.id,
this.descripcion,
this.titulo,
this.autor,
this.link,
required this.tematicas});
String tipo;
String? id;
String? descripcion;
String? titulo;
String? autor;
String? link;
List<String> tematicas;
factory PostModel.fromJson(String str) => PostModel.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory PostModel.fromMap(Map<String, dynamic> json) => PostModel(
tipo: json["tipo"],
id: json["id"],
descripcion: json["descripcion"],
titulo: json["titulo"],
autor: json["autor"],
link: json["link"],
tematicas: List<String>.from(json["tematicas"].map((x) => x)));
Map<String, dynamic> toMap() => {
"tipo": tipo,
"id": id,
"descripcion": descripcion,
"titulo": titulo,
"autor": autor,
"link": link,
"tematicas": List<dynamic>.from(tematicas.map((x) => x))
};
}
|
using System;
using Xamarin.Forms;
namespace SNSUI.Extensions
{
/// <summary>
/// The BaseTypeCell contains Text, TextEnd, Sub, Icon, and Checkbox(IsCheckVisible).
/// </summary>
/// <remarks>
/// The BaseTypeCell is an abstract class inherited from a cell.<br>
/// The Type1Cell class is used to inherit this class.<br>
/// Properties are used equally and are only at slightly different positions.<br>
/// Each property is displayed in the specified position.<br>
/// The specified position is shown below.<br>
/// <br>
/// Type1Cell
/// <table border=2 style="text-align:center;border-collapse:collapse;">
/// <tr>
/// <th height = 100 width=200 rowspan="2">Icon</th>
/// <th width = 150> Text </th>
/// <th width = 150>TextEnd</th>
/// <th width = 200 rowspan="2">CheckBox</th>
/// </tr>
/// <tr>
/// <th colspan = "2" > Sub </th>
/// </tr>
/// </table>
/// <br>
/// Type2Cell
/// <table border=2 style="text-align:center;border-collapse:collapse;">
/// <tr>
/// <th height = 100 width=200 rowspan="2">Icon</th>
/// <th colspan = "2" > Sub </th>
/// <th width=200 rowspan="2">CheckBox</th>
/// </tr>
/// <tr>
/// <th width = 150> Text </th>
/// <th width=150>TextEnd</th>
/// </tr>
/// </table>
/// </remarks>
public abstract class BaseTypeCell : Cell
{
/// <summary>
/// BindableProperty. Identifies the Text bindable property.
/// </summary>
public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(BaseTypeCell), default(string));
/// <summary>
/// BindableProperty. Identifies the TextEnd bindable property.
/// </summary>
public static readonly BindableProperty TextEndProperty = BindableProperty.Create("TextEnd", typeof(string), typeof(BaseTypeCell), default(string));
/// <summary>
/// BindableProperty. Identifies the Sub bindable property.
/// </summary>
public static readonly BindableProperty SubProperty = BindableProperty.Create("Sub", typeof(string), typeof(TextCell), default(string));
/// <summary>
/// BindableProperty. Identifies the Icon bindable property.
/// </summary>
public static readonly BindableProperty IconProperty = BindableProperty.Create("Icon", typeof(ImageSource), typeof(BaseTypeCell), null,
propertyChanged: (bindable, oldvalue, newvalue) => ((BaseTypeCell)bindable).OnSourcePropertyChanged((ImageSource)oldvalue, (ImageSource)newvalue));
/// <summary>
/// BindableProperty. Identifies the IsChecked bindable property.
/// </summary>
public static readonly BindableProperty IsCheckedProperty = BindableProperty.Create("IsChecked", typeof(bool), typeof(BaseTypeCell), false,
propertyChanged: (obj, oldValue, newValue) =>
{
var baseTypeCell = (BaseTypeCell)obj;
baseTypeCell.Toggled?.Invoke(obj, new ToggledEventArgs((bool)newValue));
}, defaultBindingMode: BindingMode.TwoWay);
/// <summary>
/// BindableProperty. Identifies the IsCheckVisible bindable property.
/// </summary>
public static readonly BindableProperty IsCheckVisibleProperty = BindableProperty.Create("IsCheckVisible", typeof(bool), typeof(BaseTypeCell), false);
/// <summary>
/// BindableProperty. Identifies the IconWidth bindable property.
/// </summary>
public static readonly BindableProperty IconWidthProperty = BindableProperty.Create("IconWidth", typeof(int), typeof(BaseTypeCell), 0);
/// <summary>
/// BindableProperty. Identifies the IconHeight bindable property.
/// </summary>
public static readonly BindableProperty IconHeightProperty = BindableProperty.Create("IconHeight", typeof(int), typeof(BaseTypeCell), 0);
/// <summary>
/// The BaseTypeCell's constructor.
/// </summary>
public BaseTypeCell()
{
Disappearing += (sender, e) =>
{
Icon?.Cancel();
};
}
/// <summary>
/// Gets or sets the Text displayed as the content of the item.
/// </summary>
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
/// <summary>
/// Gets or sets the TextEnd displayed as the content of the item.
/// </summary>
public string TextEnd
{
get { return (string)GetValue(TextEndProperty); }
set { SetValue(TextEndProperty, value); }
}
/// <summary>
/// Gets or sets the Sub displayed as the content of the item.
/// </summary>
public string Sub
{
get { return (string)GetValue(SubProperty); }
set { SetValue(SubProperty, value); }
}
/// <summary>
/// Gets or sets the Image on the left side of the item.
/// </summary>
[TypeConverter(typeof(ImageSourceConverter))]
public ImageSource Icon
{
get { return (ImageSource)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
/// <summary>
/// True or False is used to indicate whether the checkbox is displayed on the right side of the item.
/// </summary>
public bool IsCheckVisible
{
get { return (bool)GetValue(IsCheckVisibleProperty); }
set { SetValue(IsCheckVisibleProperty, value); }
}
/// <summary>
/// True or False is used to indicate whether the checkbox has been toggled.
/// </summary>
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
/// <summary>
/// Gets or sets the Icon's width.
/// </summary>
public int IconWidth
{
get { return (int)GetValue(IconWidthProperty); }
set { SetValue(IconWidthProperty, value); }
}
/// <summary>
/// Gets or sets the Icon's height.
/// </summary>
public int IconHeight
{
get { return (int)GetValue(IconHeightProperty); }
set { SetValue(IconHeightProperty, value); }
}
/// <summary>
/// The event is raised when the checkbox is toggled.
/// </summary>
public event EventHandler<ToggledEventArgs> Toggled;
void OnSourcePropertyChanged(ImageSource oldvalue, ImageSource newvalue)
{
if (newvalue != null)
{
SetInheritedBindingContext(newvalue, BindingContext);
}
}
}
}
|
import React, { useState } from 'react'
import './App.css';
import Interval from './components/Interval'
import Average from './components/Average'
import Sum from './components/Sum'
import Draw from './components/Draw'
function App() {
const [min, setMin] = useState(10)
const [max, setMax] = useState(20)
return (
<div className="App">
<h1>React-Redux exercise (simple)</h1>
<div className="line">
<Interval min={min} max={max}
onMinChanged={setMin} onMaxChanged={setMax}>
</Interval>
</div>
<div className="line">
<Average min={min} max={max}></Average>
<Sum min={min} max={max}></Sum>
<Draw min={min} max={max}></Draw>
</div>
</div>
);
}
export default App;
|
use anyhow::{anyhow, Result};
use std::sync::Arc;
use vulkano::{
buffer::{BufferUsage, CpuAccessibleBuffer, CpuBufferPool, TypedBufferAccess},
command_buffer::{AutoCommandBufferBuilder, CommandBufferUsage::OneTimeSubmit},
command_buffer::{CopyBufferImageError, SubpassContents},
descriptor_set::{persistent::PersistentDescriptorSet, DescriptorSetError},
device::{Device, Queue},
format::Format::R8G8B8A8_UNORM,
image::view::ImageView,
image::{view::ImageViewCreationError, AttachmentImage, ImageCreationError, ImageUsage},
pipeline::{
viewport::Viewport, GraphicsPipeline, GraphicsPipelineCreationError, PipelineBindPoint,
},
render_pass::{Framebuffer, FramebufferCreationError, RenderPass, Subpass},
sync::GpuFuture,
OomError,
};
mod vs {
vulkano_shaders::shader! {
ty: "vertex",
src: "#version 450
layout(location = 0) in vec2 position;
void main() {
gl_Position = vec4(position, 0, 1);
}"
}
}
mod fs {
vulkano_shaders::shader! {
ty: "fragment",
path: "shaders/yuyv2rgb.frag",
}
}
#[derive(Default, Debug, Clone)]
struct Vertex {
position: [f32; 2],
}
vulkano::impl_vertex!(Vertex, position);
#[derive(thiserror::Error, Debug)]
pub enum ConverterError {
#[error("something went wrong: {0}")]
Anyhow(#[from] anyhow::Error),
#[error("{0}")]
VkOom(#[from] OomError),
#[error("{0}")]
GraphicsPipelineCreationError(#[from] GraphicsPipelineCreationError),
#[error("{0}")]
ImageCreationError(#[from] ImageCreationError),
#[error("{0}")]
ImageViewCreationError(#[from] ImageViewCreationError),
#[error("{0}")]
DescriptorSetError(#[from] DescriptorSetError),
#[error("{0}")]
CopyBufferImageError(#[from] CopyBufferImageError),
#[error("{0}")]
FramebufferCreationError(#[from] FramebufferCreationError),
}
pub struct GpuYuyvConverter {
device: Arc<Device>,
render_pass: Arc<RenderPass>,
pipeline: Arc<GraphicsPipeline>,
src: Arc<AttachmentImage>,
desc_set: Arc<PersistentDescriptorSet>,
}
/// XXX: We can use VK_KHR_sampler_ycbcr_conversion for this, but I don't
/// know if it's widely supported. And the image format we need (G8B8G8R8_422_UNORM)
/// seems to have even less support than the extension itself.
impl GpuYuyvConverter {
pub fn new(device: Arc<Device>, w: u32, h: u32) -> Result<Self> {
if w % 2 != 0 {
return Err(anyhow!("Width can't be odd"));
}
let vs = vs::Shader::load(device.clone())?;
let fs = fs::Shader::load(device.clone())?;
let render_pass = Arc::new(
vulkano::single_pass_renderpass!(device.clone(),
attachments: {
color: {
load: DontCare,
store: Store,
format: vulkano::format::Format::R8G8B8A8_UNORM,
samples: 1,
}
},
pass: {
color: [color],
depth_stencil: {}
}
)
.unwrap(),
);
let pipeline = Arc::new(
GraphicsPipeline::start()
.vertex_input_single_buffer::<Vertex>()
.vertex_shader(vs.main_entry_point(), ())
.triangle_strip()
.viewports([Viewport {
origin: [0.0, 0.0],
dimensions: [w as f32, h as f32],
depth_range: -1.0..1.0,
}])
.fragment_shader(fs.main_entry_point(), ())
.render_pass(Subpass::from(render_pass.clone(), 0).unwrap())
.build(device.clone())?,
);
let src = AttachmentImage::with_usage(
device.clone(),
[w / 2, h], // 1 pixel of YUYV = 2 pixels of RGB
R8G8B8A8_UNORM,
ImageUsage {
transfer_source: false,
transfer_destination: true,
sampled: true,
storage: false,
color_attachment: true,
depth_stencil_attachment: false,
transient_attachment: false,
input_attachment: false,
},
)?;
let desc_set_layout = pipeline.layout().descriptor_set_layouts().get(0).unwrap();
let mut desc_set_builder = PersistentDescriptorSet::start(desc_set_layout.clone());
use vulkano::sampler::{Filter, MipmapMode, Sampler, SamplerAddressMode};
let sampler = Sampler::new(
device.clone(),
Filter::Linear,
Filter::Linear,
MipmapMode::Nearest,
SamplerAddressMode::ClampToEdge,
SamplerAddressMode::ClampToEdge,
SamplerAddressMode::ClampToEdge,
0.0,
1.0,
0.0,
0.0,
)?;
desc_set_builder.add_sampled_image(ImageView::new(src.clone())?, sampler)?;
let desc_set = Arc::new(desc_set_builder.build()?);
Ok(Self {
src,
render_pass,
pipeline,
device,
desc_set,
})
}
/// receives a buffer containing a YUYV image, upload it to GPU,
/// and convert it to RGBA8.
///
/// Returns a GPU future representing the operation, and an image.
/// You must make sure the previous conversion is completed before
/// calling this function again.
pub fn yuyv_buffer_to_vulkan_image(
&self,
buf: &[u8],
after: impl GpuFuture,
queue: Arc<Queue>,
buffer: &CpuBufferPool<u8>,
output: Arc<AttachmentImage>,
) -> Result<impl GpuFuture> {
use vulkano::device::DeviceOwned;
if queue.device() != &self.device || buffer.device() != &self.device {
return Err(anyhow!("Device mismatch"));
}
if let Some(queue) = after.queue() {
if !queue.is_same(&queue) {
return Err(anyhow!("Queue mismatch"));
}
}
// Submit the source image to GPU
let subbuffer = buffer
.chunk(buf.iter().copied())
.map_err(|e| ConverterError::Anyhow(e.into()))?;
let mut cmdbuf =
AutoCommandBufferBuilder::primary(self.device.clone(), queue.family(), OneTimeSubmit)?;
cmdbuf.copy_buffer_to_image(subbuffer, self.src.clone())?;
// Build a pipeline to do yuyv -> rgb
let vertex_buffer = CpuAccessibleBuffer::<[Vertex]>::from_iter(
self.device.clone(),
BufferUsage::vertex_buffer(),
false,
[
Vertex {
position: [-1.0, -1.0],
},
Vertex {
position: [-1.0, 1.0],
},
Vertex {
position: [1.0, -1.0],
},
Vertex {
position: [1.0, 1.0],
},
]
.iter()
.cloned(),
)
.unwrap();
let framebuffer = Arc::new(
Framebuffer::start(self.render_pass.clone())
.add(ImageView::new(output)?)?
.build()?,
);
cmdbuf
.begin_render_pass(
framebuffer,
SubpassContents::Inline,
[vulkano::format::ClearValue::None],
)
.map_err(|e| ConverterError::Anyhow(e.into()))?
.bind_pipeline_graphics(self.pipeline.clone())
.bind_descriptor_sets(
PipelineBindPoint::Graphics,
self.pipeline.layout().clone(),
0,
self.desc_set.clone(),
)
.bind_vertex_buffers(0, vertex_buffer.clone())
.draw(vertex_buffer.len() as u32, 1, 0, 0)
.map_err(|e| ConverterError::Anyhow(e.into()))?
.end_render_pass()
.map_err(|e| ConverterError::Anyhow(e.into()))?;
Ok(after.then_execute(
queue,
cmdbuf
.build()
.map_err(|e| ConverterError::Anyhow(e.into()))?,
)?)
}
}
|
-module(capi_handler_encoder).
-include_lib("damsel/include/dmsl_payment_processing_thrift.hrl").
-include_lib("damsel/include/dmsl_merch_stat_thrift.hrl").
-export([encode_contact_info/1]).
-export([encode_client_info/1]).
-export([encode_cash/1]).
-export([encode_cash/2]).
-export([encode_currency/1]).
-export([encode_invoice_cart/1]).
-export([encode_invoice_cart/2]).
-export([encode_invoice_bank_account/1]).
-export([encode_stat_request/1]).
-export([encode_invoice_context/1]).
-export([encode_payment_context/1]).
-export([encode_invoice_line_meta/1]).
-export([encode_residence/1]).
-export([encode_content/2]).
-export([encode_stat_request/2]).
-export_type([encode_data/0]).
-type request_data() :: capi_handler:request_data().
-type encode_data() :: tuple().
-spec encode_contact_info(request_data()) -> encode_data().
encode_contact_info(ContactInfo) ->
#domain_ContactInfo{
phone_number = genlib_map:get(<<"phoneNumber">>, ContactInfo),
email = genlib_map:get(<<"email">>, ContactInfo)
}.
-spec encode_client_info(request_data()) -> encode_data().
encode_client_info(ClientInfo) ->
#domain_ClientInfo{
fingerprint = maps:get(<<"fingerprint">>, ClientInfo),
ip_address = maps:get(<<"ip">>, ClientInfo)
}.
-spec encode_residence(binary() | undefined) -> atom().
encode_residence(undefined) ->
undefined;
encode_residence(Residence) when is_binary(Residence) ->
case capi_domain:encode_enum('CountryCode', string:lowercase(Residence)) of
{ok, EncodedResidence} -> EncodedResidence;
{error, _} -> throw({encode_residence, invalid_residence})
end.
-spec encode_cash(request_data()) -> encode_data().
encode_cash(Params) ->
Amount = genlib_map:get(<<"amount">>, Params),
Currency = genlib_map:get(<<"currency">>, Params),
encode_cash(Amount, Currency).
-spec encode_cash(integer(), binary()) -> encode_data().
encode_cash(Amount, Currency) ->
#domain_Cash{
amount = Amount,
currency = encode_currency(Currency)
}.
-spec encode_currency(binary()) -> encode_data().
encode_currency(SymbolicCode) ->
#domain_CurrencyRef{symbolic_code = SymbolicCode}.
-spec encode_invoice_cart(request_data()) -> encode_data().
encode_invoice_cart(Params) ->
Cart = genlib_map:get(<<"cart">>, Params),
Currency = genlib_map:get(<<"currency">>, Params),
encode_invoice_cart(Cart, Currency).
-spec encode_invoice_cart(list(), binary()) -> encode_data().
encode_invoice_cart(Cart, Currency) when Cart =/= undefined, Cart =/= [] ->
#domain_InvoiceCart{
lines = [encode_invoice_line(Line, Currency) || Line <- Cart]
};
encode_invoice_cart([], _) ->
throw(invoice_cart_empty);
encode_invoice_cart(undefined, _) ->
undefined.
encode_invoice_line(Line, Currency) ->
Metadata = encode_invoice_line_meta(Line),
Price = encode_cash(genlib_map:get(<<"price">>, Line), Currency),
#domain_InvoiceLine{
product = genlib_map:get(<<"product">>, Line),
quantity = genlib_map:get(<<"quantity">>, Line),
price = Price,
metadata = Metadata
}.
-spec encode_invoice_line_meta(request_data()) -> #{binary() => {str, _}}.
-define(DEFAULT_INVOICE_LINE_META, #{}).
encode_invoice_line_meta(Line) ->
case genlib_map:get(<<"taxMode">>, Line) of
TaxMode when TaxMode =/= undefined ->
TM = encode_invoice_line_tax_mode(TaxMode),
#{<<"TaxMode">> => {str, TM}};
undefined ->
?DEFAULT_INVOICE_LINE_META
end.
encode_invoice_line_tax_mode(#{<<"type">> := <<"InvoiceLineTaxVAT">>} = TaxMode) ->
genlib_map:get(<<"rate">>, TaxMode).
-spec encode_invoice_bank_account(request_data()) -> dmsl_domain_thrift:'InvoiceBankAccount'() | undefined.
encode_invoice_bank_account(Params) ->
do_encode_invoice_bank_account(genlib_map:get(<<"bankAccount">>, Params)).
do_encode_invoice_bank_account(#{<<"accountType">> := <<"InvoiceRussianBankAccount">>} = Account) ->
{russian, #domain_InvoiceRussianBankAccount{
account = maps:get(<<"account">>, Account),
bank_bik = maps:get(<<"bankBik">>, Account)
}};
do_encode_invoice_bank_account(undefined) ->
undefined.
-define(DEFAULT_INVOICE_META, #{}).
-spec encode_invoice_context(request_data()) -> encode_data().
encode_invoice_context(Params) ->
encode_invoice_context(Params, ?DEFAULT_INVOICE_META).
encode_invoice_context(Params, DefaultMeta) ->
Context = genlib_map:get(<<"metadata">>, Params, DefaultMeta),
encode_content(json, Context).
-spec encode_payment_context(request_data()) -> encode_data() | undefined.
encode_payment_context(#{<<"metadata">> := Context}) ->
encode_content(json, Context);
encode_payment_context(#{}) ->
undefined.
-spec encode_content(json, term()) -> encode_data().
encode_content(json, Data) ->
#'Content'{
type = <<"application/json">>,
data = jsx:encode(Data)
}.
-spec encode_stat_request(map() | binary()) -> encode_data().
encode_stat_request(Dsl) ->
encode_stat_request(Dsl, undefined).
-spec encode_stat_request(map() | binary(), binary() | undefined) -> encode_data().
encode_stat_request(Dsl, ContinuationToken) when is_map(Dsl) ->
encode_stat_request(jsx:encode(Dsl), ContinuationToken);
encode_stat_request(Dsl, ContinuationToken) when is_binary(Dsl) ->
#merchstat_StatRequest{
dsl = Dsl,
continuation_token = ContinuationToken
}.
|
package chooongg.box.core.activity
import androidx.annotation.StyleRes
@Target(AnnotationTarget.CLASS)
annotation class Theme(@StyleRes val value: Int)
|
namespace ExtensionsForOneDrive
{
public class CloseLoginWindow
{
public CloseLoginWindow(bool continueProcessing)
{
this.ContinueProcessing = continueProcessing;
}
public bool ContinueProcessing { get; private set; }
}
}
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'debug.dart';
/// Whether the gesture was accepted or rejected.
enum GestureDisposition {
/// This gesture was accepted as the interpretation of the user's input.
accepted,
/// This gesture was rejected as the interpretation of the user's input.
rejected,
}
/// Represents an object participating in an arena.
///
/// Receives callbacks from the GestureArena to notify the object when it wins
/// or loses a gesture negotiation. Exactly one of [acceptGesture] or
/// [rejectGesture] will be called for each arena this member was added to,
/// regardless of what caused the arena to be resolved. For example, if a
/// member resolves the arena itself, that member still receives an
/// [acceptGesture] callback.
abstract class GestureArenaMember {
/// Called when this member wins the arena for the given pointer id.
void acceptGesture(int pointer);
/// Called when this member loses the arena for the given pointer id.
void rejectGesture(int pointer);
}
/// An interface to pass information to an arena.
///
/// A given [GestureArenaMember] can have multiple entries in multiple arenas
/// with different pointer ids.
class GestureArenaEntry {
GestureArenaEntry._(this._arena, this._pointer, this._member);
final GestureArenaManager _arena;
final int _pointer;
final GestureArenaMember _member;
/// Call this member to claim victory (with accepted) or admit defeat (with rejected).
///
/// It's fine to attempt to resolve a gesture recognizer for an arena that is
/// already resolved.
void resolve(GestureDisposition disposition) {
_arena._resolve(_pointer, _member, disposition);
}
}
class _GestureArena {
final List<GestureArenaMember> members = <GestureArenaMember>[];
bool isOpen = true;
bool isHeld = false;
bool hasPendingSweep = false;
/// If a member attempts to win while the arena is still open, it becomes the
/// "eager winner". We look for an eager winner when closing the arena to new
/// participants, and if there is one, we resolve the arena in its favor at
/// that time.
GestureArenaMember eagerWinner;
void add(GestureArenaMember member) {
assert(isOpen);
members.add(member);
}
@override
String toString() {
final StringBuffer buffer = StringBuffer();
if (members.isEmpty) {
buffer.write('<empty>');
} else {
buffer.write(members.map<String>((GestureArenaMember member) {
if (member == eagerWinner)
return '$member (eager winner)';
return '$member';
}).join(', '));
}
if (isOpen)
buffer.write(' [open]');
if (isHeld)
buffer.write(' [held]');
if (hasPendingSweep)
buffer.write(' [hasPendingSweep]');
return buffer.toString();
}
}
/// The first member to accept or the last member to not reject wins.
///
/// See <https://flutter.dev/gestures/#gesture-disambiguation> for more
/// information about the role this class plays in the gesture system.
///
/// To debug problems with gestures, consider using
/// [debugPrintGestureArenaDiagnostics].
class GestureArenaManager {
final Map<int, _GestureArena> _arenas = <int, _GestureArena>{};
/// Adds a new member (e.g., gesture recognizer) to the arena.
GestureArenaEntry add(int pointer, GestureArenaMember member) {
final _GestureArena state = _arenas.putIfAbsent(pointer, () {
assert(_debugLogDiagnostic(pointer, '★ Opening new gesture arena.'));
return _GestureArena();
});
state.add(member);
assert(_debugLogDiagnostic(pointer, 'Adding: $member'));
return GestureArenaEntry._(this, pointer, member);
}
/// Prevents new members from entering the arena.
///
/// Called after the framework has finished dispatching the pointer down event.
void close(int pointer) {
final _GestureArena state = _arenas[pointer];
if (state == null)
return; // This arena either never existed or has been resolved.
state.isOpen = false;
assert(_debugLogDiagnostic(pointer, 'Closing', state));
_tryToResolveArena(pointer, state);
}
/// Forces resolution of the arena, giving the win to the first member.
///
/// Sweep is typically after all the other processing for a [PointerUpEvent]
/// have taken place. It ensures that multiple passive gestures do not cause a
/// stalemate that prevents the user from interacting with the app.
///
/// Recognizers that wish to delay resolving an arena past [PointerUpEvent]
/// should call [hold] to delay sweep until [release] is called.
///
/// See also:
///
/// * [hold]
/// * [release]
void sweep(int pointer) {
final _GestureArena state = _arenas[pointer];
if (state == null)
return; // This arena either never existed or has been resolved.
assert(!state.isOpen);
if (state.isHeld) {
state.hasPendingSweep = true;
assert(_debugLogDiagnostic(pointer, 'Delaying sweep', state));
return; // This arena is being held for a long-lived member.
}
assert(_debugLogDiagnostic(pointer, 'Sweeping', state));
_arenas.remove(pointer);
if (state.members.isNotEmpty) {
// First member wins.
assert(_debugLogDiagnostic(pointer, 'Winner: ${state.members.first}'));
state.members.first.acceptGesture(pointer);
// Give all the other members the bad news.
for (int i = 1; i < state.members.length; i++)
state.members[i].rejectGesture(pointer);
}
}
/// Prevents the arena from being swept.
///
/// Typically, a winner is chosen in an arena after all the other
/// [PointerUpEvent] processing by [sweep]. If a recognizer wishes to delay
/// resolving an arena past [PointerUpEvent], the recognizer can [hold] the
/// arena open using this function. To release such a hold and let the arena
/// resolve, call [release].
///
/// See also:
///
/// * [sweep]
/// * [release]
void hold(int pointer) {
final _GestureArena state = _arenas[pointer];
if (state == null)
return; // This arena either never existed or has been resolved.
state.isHeld = true;
assert(_debugLogDiagnostic(pointer, 'Holding', state));
}
/// Releases a hold, allowing the arena to be swept.
///
/// If a sweep was attempted on a held arena, the sweep will be done
/// on release.
///
/// See also:
///
/// * [sweep]
/// * [hold]
void release(int pointer) {
final _GestureArena state = _arenas[pointer];
if (state == null)
return; // This arena either never existed or has been resolved.
state.isHeld = false;
assert(_debugLogDiagnostic(pointer, 'Releasing', state));
if (state.hasPendingSweep)
sweep(pointer);
}
/// Reject or accept a gesture recognizer.
///
/// This is called by calling [GestureArenaEntry.resolve] on the object returned from [add].
void _resolve(int pointer, GestureArenaMember member, GestureDisposition disposition) {
final _GestureArena state = _arenas[pointer];
if (state == null)
return; // This arena has already resolved.
assert(_debugLogDiagnostic(pointer, '${ disposition == GestureDisposition.accepted ? "Accepting" : "Rejecting" }: $member'));
assert(state.members.contains(member));
if (disposition == GestureDisposition.rejected) {
state.members.remove(member);
member.rejectGesture(pointer);
if (!state.isOpen)
_tryToResolveArena(pointer, state);
} else {
assert(disposition == GestureDisposition.accepted);
if (state.isOpen) {
state.eagerWinner ??= member;
} else {
assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member'));
_resolveInFavorOf(pointer, state, member);
}
}
}
void _tryToResolveArena(int pointer, _GestureArena state) {
assert(_arenas[pointer] == state);
assert(!state.isOpen);
if (state.members.length == 1) {
scheduleMicrotask(() => _resolveByDefault(pointer, state));
} else if (state.members.isEmpty) {
_arenas.remove(pointer);
assert(_debugLogDiagnostic(pointer, 'Arena empty.'));
} else if (state.eagerWinner != null) {
assert(_debugLogDiagnostic(pointer, 'Eager winner: ${state.eagerWinner}'));
_resolveInFavorOf(pointer, state, state.eagerWinner);
}
}
void _resolveByDefault(int pointer, _GestureArena state) {
if (!_arenas.containsKey(pointer))
return; // Already resolved earlier.
assert(_arenas[pointer] == state);
assert(!state.isOpen);
final List<GestureArenaMember> members = state.members;
assert(members.length == 1);
_arenas.remove(pointer);
assert(_debugLogDiagnostic(pointer, 'Default winner: ${state.members.first}'));
state.members.first.acceptGesture(pointer);
}
void _resolveInFavorOf(int pointer, _GestureArena state, GestureArenaMember member) {
assert(state == _arenas[pointer]);
assert(state != null);
assert(state.eagerWinner == null || state.eagerWinner == member);
assert(!state.isOpen);
_arenas.remove(pointer);
for (GestureArenaMember rejectedMember in state.members) {
if (rejectedMember != member)
rejectedMember.rejectGesture(pointer);
}
member.acceptGesture(pointer);
}
bool _debugLogDiagnostic(int pointer, String message, [ _GestureArena state ]) {
assert(() {
if (debugPrintGestureArenaDiagnostics) {
final int count = state != null ? state.members.length : null;
final String s = count != 1 ? 's' : '';
debugPrint('Gesture arena ${pointer.toString().padRight(4)} ❙ $message${ count != null ? " with $count member$s." : ""}');
}
return true;
}());
return true;
}
}
|
package org.mostlylikeable.gradle.kotlin.dsl
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.dsl.DependencyHandler
fun DependencyHandler.annotationProcessor(dependency: String)
: Unit = addInternal("annotationProcessor", dependency)
fun DependencyHandler.annotationProcessor(dependency: String, configuration: ExternalModuleDependency.() -> Unit)
: Unit = addInternal("annotationProcessor", dependency, configuration)
fun DependencyHandler.compileOnly(dependency: String)
: Unit = addInternal("compileOnly", dependency)
fun DependencyHandler.compileOnly(dependency: String, action: ExternalModuleDependency.() -> Unit)
: Unit = addInternal("compileOnly", dependency, action)
fun DependencyHandler.implementation(dependency: String)
: Unit = addInternal("implementation", dependency)
fun DependencyHandler.implementation(dependency: String, action: ExternalModuleDependency.() -> Unit)
: Unit = addInternal("implementation", dependency, action)
fun DependencyHandler.testAnnotationProcessor(dependency: String)
: Unit = addInternal("testAnnotationProcessor", dependency)
fun DependencyHandler.testAnnotationProcessor(dependency: String, action: ExternalModuleDependency.() -> Unit)
: Unit = addInternal("testAnnotationProcessor", dependency, action)
fun DependencyHandler.testCompileOnly(dependency: String)
: Unit = addInternal("testCompileOnly", dependency)
fun DependencyHandler.testCompileOnly(dependency: String, action: ExternalModuleDependency.() -> Unit)
: Unit = addInternal("testCompileOnly", dependency, action)
fun DependencyHandler.testImplementation(dependency: String)
: Unit = addInternal("testImplementation", dependency)
fun DependencyHandler.testImplementation(dependency: String, configuration: ExternalModuleDependency.() -> Unit)
: Unit = addInternal("testImplementation", dependency, configuration)
private fun DependencyHandler.addInternal(
configurationName: String,
dependencyNotation: String,
configuration: (ExternalModuleDependency.() -> Unit)? = null
) {
add(configurationName, dependencyNotation)
.apply { configuration?.invoke(this as ExternalModuleDependency) }
}
|
module diag_dom_utility
contains
subroutine to_diag_dom(n,m,A,out_status)
!This routime checks if a given matriz A can be converted to diagonally
!dominant form, and in case that is true, it makes the conversion and returns
!the diagonally dominant matrix.
!
!For the matrix to be convertible, two conditions must be satisfied:
! #1 The largest elements (in abs value) of each row must all belong to
! different columns, so the can be placed at the main diagonal by
! changing rows or columns.
! #2 The largest element of each row must be 'dominant', that is, must be
! grater than the sum of the abs value of all other elements in the
! same row.
!
!If both conditions are met the routine returns out_status=.TRUE. and the
!modified matrix in array A.
!If any of the conditions is not met, the routine returns out_status=.FALSE.
!and the original matriz in array A.
implicit none
!Declaration of arguments
integer(2), intent(in) :: n,m
integer(2), intent(inout) :: A(n,m)
logical, intent(out) :: out_status
!Declaration of internal variables
integer(2) :: i
integer(2) :: m_index(n), sum_row(n)
logical :: max_are_dominant, max_in_dif_col
!Find the position of the largest element (in abs value)
!for each row.
!Read about MAXLOC function at: https://gcc.gnu.org/onlinedocs/gcc-4.4.3/gfortran/MAXLOC.html
m_index=maxloc(abs(A),dim=2)
!Check if the largest element of each row is in a different column
!then, after rearranging rows it will be possible to place the those
!elements in the main diagonal of the matrix.
max_in_dif_col=all_different(m_index)
!Compute the summation of all elements in each row.
!Substracting the value of the row's maximum we get the sum of all other elements
!Substracting the value of the row's maximum again, if the maximums are dominant
!we get an array with all negative values.
sum_row=0
do i=1,n
sum_row(i)=sum(abs(A(i,:)))-2*abs(A(i,m_index(i)))
enddo
!Check if all values are negative. If that is the case we set
!max_are_dominant to true because the matriz mets the first conditions
!to be convertible to diagonally dominant form
if (all(sum_row<0)) max_are_dominant=.true.
if ((max_are_dominant).and.(max_in_dif_col)) then
call convert_to_diag_dom(A, m_index)
out_status=.true.
else
out_status=.false.
endif
end subroutine
logical function all_different(arr)
!This function returns TRUE if all elements of array 'arr'
!are different to each other. If not, it returns FALSE.
implicit none
!Declaration of arguments
integer(2), intent(in) :: arr(:) !<----This is an automatic array not
!a dynamic array (allocatable)
!Ask Google about it or go to consulta
!Declaration of internal variables
integer(2) :: i
all_different=.true.
!Read about intrisinc function SIZE at:
!https://gcc.gnu.org/onlinedocs/gcc-4.4.3/gfortran/SIZE.html#SIZE
do i=1,size(arr)-1
!Read about intrisinc function ANY at:
!https://gcc.gnu.org/onlinedocs/gcc-4.4.3/gfortran/ANY.html#ANY
if (any(arr(i)==arr(i+1:size(arr)))) then
all_different=.false.
exit
endif
enddo
end function
subroutine convert_to_diag_dom(M,m_index)
!This routine places each row in the correspondig place.
implicit none
integer(2), intent(in) :: m_index(:)
integer(2), intent(inout) :: M(:,:)
integer(2) :: i
integer(2) :: aux(size(M,1),size(M,2))
do i=1,size(M,1)
aux(m_index(i),:)=M(i,:)
enddo
M=aux
end subroutine convert_to_diag_dom
end module diag_dom_utility
program test_ddomin
use diag_dom_utility
implicit none
integer(2) :: i,n,m
integer(2), allocatable :: A(:,:) !This is a dynamic array (allocatable)
logical :: ddiag_status
open(unit=10,file='datos.in',status='old')
read(10,*) n,m
allocate(A(n,m))
do i=1,n
read(10,*) A(i,:)
write(*,*) A(i,:)
enddo
close(10)
call to_diag_dom(n,m,A,ddiag_status)
print *, "---------------------------------"
if (ddiag_status) then
do i=1,size(A,1)
print *, A(i,:)
enddo
else
print *, " "
print *, "The matrix cannot be converted to diagonally dominant form"
endif
end program
|
unit dtinyatoi;
// Tiny atoi() replacement. rlyeh, public domain | wtrmrkrlyeh
// Ported to pascal by Doj
{$MODE FPC}
{$MODESWITCH DEFAULTPARAMETERS}
{$MODESWITCH OUT}
{$MODESWITCH RESULT}
interface
function tinyatoi(S: PAnsiChar): PtrInt;
implementation
function tinyatoi(S: PAnsiChar): PtrInt;
var
v, n: PtrInt;
begin
v := 0;
n := 1;
if s <> nil then begin
while s^ = '-' do begin
n := - n;
Inc(s);
end;
while (s^ >= '0') and (s^ <= '9') do begin
v := (10 * v) + (Ord(s^) - Ord('0'));
Inc(s);
end;
end;
Exit(n * v);
end;
//
// begin
// Assert(1230 = tinyatoi('01230'));
// Assert(-1230 = tinyatoi('-01230'));
// Assert(1230 = tinyatoi('--01230'));
// Assert(-1230 = tinyatoi('---01230'));
// end;
//
end.
|
import Pet from '../models/pet.model';
import SeedHelper from '../../core/helpers/seed.helper';
import moment from 'moment';
export default function () {
return SeedHelper.cleanAndCreate(Pet, 'Pet',
[
{
_id: "580d84ee3731f70996579a65",
name: 'Doggy',
availableFrom: moment().add(-5, 'days'),
attributes: {
age: 10,
specie: 'dog',
breed: 'terrier'
},
},
{
_id: "57a42ccb8bc7e0b30a2b18e8",
name: 'Catty',
availableFrom: moment().add(30, 'days'),
attributes: {
age: 5,
specie: 'cat',
},
},
]);
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hefezopf.Contracts.Communication
{
/// <summary>
/// This service provide a fast way to communicate.
/// </summary>
[System.ServiceModel.ServiceContract(Namespace = ContractConsts.Namespace)]
public interface IHZTransportContract
{
/// <summary>
/// Execute one action.
/// </summary>
/// <param name="request">The request jsonfied.</param>
/// <returns>The responce jsonfied.</returns>
[System.ServiceModel.OperationContract]
string Execute(string request);
/// <summary>
/// Execute many actions.
/// </summary>
/// <param name="requests">A list of request jsonfied.</param>
/// <returns>A list of responces jsonfied.</returns>
[System.ServiceModel.OperationContract]
string[] ExecuteMany(string[] requests);
/// <summary>
/// Execute one action queued.
/// </summary>
/// <param name="request">The request jsonfied.</param>
/// <returns>The responce jsonfied.</returns>
[System.ServiceModel.OperationContract]
string ExecuteQueue(string request);
}
}
|
#if UNITY_EDITOR
using UnityEditor;
namespace Svelto.Tasks.Internal
{
#if UNITY_2017_2_OR_NEWER
[InitializeOnLoad]
class StopThreadsInEditor
{
static StopThreadsInEditor()
{
EditorApplication.playModeStateChanged += Update;
}
static void Update(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingPlayMode
&& StandardSchedulers.multiThreadScheduler != null
&& StandardSchedulers.multiThreadScheduler.isKilled == false)
StandardSchedulers.multiThreadScheduler.Dispose();
}
}
#else
[InitializeOnLoad]
class StopThreadsInEditor
{
static StopThreadsInEditor()
{
EditorApplication.playmodeStateChanged += Update;
}
static void Update()
{
if (EditorApplication.isPlayingOrWillChangePlaymode == false
&& StandardSchedulers.multiThreadScheduler != null
&& StandardSchedulers.multiThreadScheduler.isKilled == false)
StandardSchedulers.multiThreadScheduler.Dispose();
}
}
#endif
}
#endif |
#include "system/System.hpp"
#include "wrappers.hpp"
using namespace cpb;
template<class T>
void wrap_registry(py::module& m, char const* name) {
py::class_<T>(m, name)
.def_property_readonly("name_map", &T::name_map)
.def(py::pickle([](T const& r) {
return py::dict("energies"_a=r.get_energies(), "names"_a=r.get_names());
}, [](py::dict d) {
return new T(d["energies"].cast<std::vector<MatrixXcd>>(),
d["names"].cast<std::vector<std::string>>());
}));
}
void wrap_system(py::module& m) {
wrap_registry<SiteRegistry>(m, "SiteRegistry");
wrap_registry<HoppingRegistry>(m, "HoppingRegistry");
py::class_<CartesianArray>(m, "CartesianArray")
.def_property_readonly("x", [](CartesianArray const& a) { return arrayref(a.x); })
.def_property_readonly("y", [](CartesianArray const& a) { return arrayref(a.y); })
.def_property_readonly("z", [](CartesianArray const& a) { return arrayref(a.z); })
.def(py::pickle([](CartesianArray const& a) {
return py::make_tuple(arrayref(a.x), arrayref(a.y), arrayref(a.z));
}, [](py::tuple t) {
using T = ArrayXf;
return new CartesianArray(t[0].cast<T>(), t[1].cast<T>(), t[2].cast<T>());
}));
py::class_<CompressedSublattices>(m, "CompressedSublattices")
.def("decompressed", [](CompressedSublattices const& c) { return c.decompressed(); })
.def_property_readonly("alias_ids", &CompressedSublattices::alias_ids)
.def_property_readonly("site_counts", &CompressedSublattices::site_counts)
.def_property_readonly("orbital_counts", &CompressedSublattices::orbital_counts)
.def(py::pickle([](CompressedSublattices const& c) {
return py::dict("alias_ids"_a=c.alias_ids(), "site_counts"_a=c.site_counts(),
"orbital_counts"_a=c.orbital_counts());
}, [](py::dict d) {
return new CompressedSublattices(d["alias_ids"].cast<ArrayXi>(),
d["site_counts"].cast<ArrayXi>(),
d["orbital_counts"].cast<ArrayXi>());
}));
py::class_<HoppingBlocks>(m, "HoppingBlocks")
.def_property_readonly("nnz", &HoppingBlocks::nnz)
.def("count_neighbors", &HoppingBlocks::count_neighbors)
.def("tocsr", [](HoppingBlocks const& hb) {
auto type = py::module::import("pybinding.support.alias").attr("AliasCSRMatrix");
return type(hb.tocsr(), "mapping"_a=hb.get_name_map());
})
.def("tocoo", [](py::object self) { return self.attr("tocsr")().attr("tocoo")(); })
.def("__getitem__", [](py::object self, py::object item) {
auto const structure = py::module::import("pybinding.support.structure");
return structure.attr("Hoppings")(
structure.attr("_slice_csr_matrix")(self.attr("tocsr")(), item)
);
})
.def(py::pickle([](HoppingBlocks const& hb) {
return py::dict("num_sites"_a=hb.get_num_sites(), "data"_a=hb.get_serialized_blocks(),
"name_map"_a=hb.get_name_map());
}, [](py::dict d) {
return new HoppingBlocks(d["num_sites"].cast<idx_t>(),
d["data"].cast<HoppingBlocks::SerializedBlocks>(),
d["name_map"].cast<NameMap>());
}));
using Boundary = System::Boundary;
py::class_<Boundary>(m, "Boundary")
.def_readonly("hoppings", &Boundary::hopping_blocks)
.def_readonly("shift", &Boundary::shift)
.def("__getitem__", [](py::object self, py::object item) {
auto type = py::module::import("pybinding.support.structure").attr("Boundary");
return type(self.attr("shift"), self.attr("hoppings")[item]);
})
.def(py::pickle([](Boundary const& b) {
return py::make_tuple(b.hopping_blocks, b.shift);
}, [](py::tuple t) {
return new Boundary{t[0].cast<decltype(Boundary::hopping_blocks)>(),
t[1].cast<decltype(Boundary::shift)>()};
}));
py::class_<System, std::shared_ptr<System>>(m, "System")
.def("find_nearest", &System::find_nearest, "position"_a, "sublattice"_a="")
.def("to_hamiltonian_indices", &System::to_hamiltonian_indices)
.def_readonly("site_registry", &System::site_registry)
.def_readonly("hopping_registry", &System::hopping_registry)
.def_readonly("positions", &System::positions)
.def_readonly("compressed_sublattices", &System::compressed_sublattices)
.def_readonly("hopping_blocks", &System::hopping_blocks)
.def_readonly("boundaries", &System::boundaries)
.def_property_readonly("hamiltonian_size", &System::hamiltonian_size)
.def_property_readonly("expanded_positions", &System::expanded_positions)
.def(py::pickle([](System const& s) {
return py::dict("site_registry"_a=s.site_registry,
"hopping_registry"_a=s.hopping_registry,
"positions"_a=s.positions,
"compressed_sublattices"_a=s.compressed_sublattices,
"hopping_blocks"_a=s.hopping_blocks,
"boundaries"_a=s.boundaries);
}, [](py::dict d) {
auto s = [&]{
if (d.contains("lattice")) {
auto const lattice = d["lattice"].cast<Lattice>();
return new System(lattice.site_registry(), lattice.hopping_registry());
} else {
return new System(d["site_registry"].cast<SiteRegistry>(),
d["hopping_registry"].cast<HoppingRegistry>());
}
}();
s->positions = d["positions"].cast<decltype(s->positions)>();
s->compressed_sublattices =
d["compressed_sublattices"].cast<decltype(s->compressed_sublattices)>();
s->hopping_blocks = d["hopping_blocks"].cast<decltype(s->hopping_blocks)>();
s->boundaries = d["boundaries"].cast<decltype(s->boundaries)>();
return s;
}));
}
|
<?php declare(strict_types=1);
/**
* BBB On Demand PHP VM Library
*
* Copyright (c) BBB On Demand
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace BBBondemand\Test;
use BBBondemand\Endpoint;
use BBBondemand\UrlBuilder;
use BBBondemand\Vm;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
class VmTest extends TestCase {
private $vm;
/**
* @var UrlBuilder
*/
private $urlBuilder;
public function setUp(): void {
parent::setUp();
$conf = Sut::vmConf();
$baseApiUrl = $conf['baseApiUrl'];
$customerId = $conf['customerId'];
$this->urlBuilder = new UrlBuilder($customerId, $baseApiUrl);
$this->vm = new Vm($conf['customerApiToken'], $this->urlBuilder);
startServer();
// todo Now we are testing real service, replace the HttpClient with the stub.
// $this->vm->setHttpClient($this->mkHttpClientStub());
}
public function tearDown(): void {
parent::tearDown();
Server::stop();
}
public function testHttp_Send_ReturnsErrorForInvalidUrl() {
$baseApiUrl = Sut::vmConf('baseApiUrl');
$result = $this->vm->send('GET', $baseApiUrl . '/non-existing/url');
$this->checkErrorResult($result, 403, '[ERR:' . Vm::INVALID_REQUEST . '] Forbidden');
}
public function testHttp_Send_SuccessResult() {
$url = ($this->urlBuilder)(Endpoint::LIST_REGIONS);
$result = $this->vm->send('GET', $url);
$this->checkSuccessResult($result);
}
public function testInstances_GetInstances() {
$instances = $this->vm->getInstances();
$this->checkSuccessResult($instances);
$this->assertIsArray($instances['data']);
}
public function dataInstances_GetInstance_ServerSideChecks() {
/*
todo
yield [
"instance name can't be blank",
'',
];*/
yield [
'Invalid instance name: must be in lower case',
'fooBar',
];
yield [
'Invalid instance name: the length must be between 19 and 22',
'foobar',
];
yield [
'Unable to find this instance',
'testtesttesttesttest',
];
}
/**
* @param string $expectedMessage
* @param string $instanceId
* @dataProvider dataInstances_GetInstance_ServerSideChecks
*/
public function testInstances_GetInstance_ServerSideChecks(string $expectedMessage, string $instanceId) {
$url = ($this->urlBuilder)(Endpoint::GET_INSTANCE, ['instanceID' => $instanceId]);
$result = $this->vm->send('GET', $url);
$this->checkErrorResult($result, 400, $expectedMessage);
}
public function testInstances_StartInstance_UsingStubServer() {
$expectedResponseData = [
'startInstanceData' => 'ok',
];
$this->expectResponse(Endpoint::START_INSTANCE, $expectedResponseData);
$instanceId = 'testtesttesttesttest';
$result = $this->vm->startInstance($instanceId);
$this->checkSuccessResult($result);
$this->assertSame($expectedResponseData, $result['data']);
// todo: check http method
}
public function testCanUseClosureAsUrlBuilder() {
$expectedResponse = $this->mkSuccessResponse([
'startInstanceData' => 'ok',
]);
$expectedResponseJson = $this->toJson($expectedResponse);
[$client, $responseHandler] = $this->mkClientStub($expectedResponseJson);
$this->vm->setHttpClient($client);
$instanceId = 'testtesttesttesttest';
$urlBuilder = function () use (&$urlBuilderArgs) {
$urlBuilderArgs = func_get_args();
return 'http://localhost';
};
$this->vm->setUrlBuilder($urlBuilder);
$result = $this->vm->startInstance($instanceId);
$this->assertIsArray($urlBuilderArgs);
$this->assertNotEmpty($urlBuilderArgs);
$this->assertSame($expectedResponse, $result);
}
public function testInstances_StartInstance_UsingClientStub() {
$expectedResponse = $this->mkSuccessResponse([
'startInstanceData' => 'ok',
]);
$expectedResponseJson = $this->toJson($expectedResponse);
[$client, $responseHandler] = $this->mkClientStub($expectedResponseJson);
$this->vm->setHttpClient($client);
$instanceId = 'testtesttesttesttest';
$result = $this->vm->startInstance($instanceId);
$this->assertSame($expectedResponse, $result);
$lastRequest = $responseHandler->getLastRequest();
$this->assertSame('POST', $lastRequest->getMethod());
$this->assertSame($this->vm->getUrlBuilder()(Endpoint::START_INSTANCE), $lastRequest->getUri()->__toString());
}
public function testInstances_StopInstance_UsingStubServer() {
$expectedResponseData = [
'stopInstance' => 'ok',
];
$this->expectResponse(Endpoint::STOP_INSTANCE, $expectedResponseData);
$instanceId = 'testtesttesttesttest';
$result = $this->vm->stopInstance($instanceId);
$this->checkSuccessResult($result);
$this->assertSame($expectedResponseData, $result['data']);
// todo: check http method
}
public function dataInstances_GetInstance_ClientSideChecks() {
yield [
"Invalid instance name: can't be blank",
'',
];
yield [
'Invalid instance name: must be in lower case',
'fooBar',
];
yield [
'Invalid instance name: the length must be between 19 and 22',
'foobar',
];
}
/**
* @param string $expectedMessage
* @param string $instanceId
* @dataProvider dataInstances_GetInstance_ClientSideChecks
*/
public function testInstances_GetInstance_ClientSideChecks(string $expectedMessage, string $instanceId) {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage($expectedMessage);
$this->vm->getInstance($instanceId);
}
public function testRegions_GetRegions() {
$result = $this->vm->getRegions();
$this->checkSuccessResult($result);
$this->assertIsArray($result['data']);
$assertNotEmptyString = function ($val) {
$this->assertIsString($val);
$this->assertNotEmpty($val);
};
foreach ($result['data'] as $key => $val) {
$this->assertMatchesRegularExpression('~^[-0-9a-z]+$~si', $key);
$this->assertCount(3, $val);
$assertNotEmptyString($val['Name']);
$assertNotEmptyString($val['Town']);
$assertNotEmptyString($val['Continent']);
}
}
public function testRecordings_GetRecordings() {
$result = $this->vm->getRecordings();
$this->checkSuccessResult($result);
$this->checkEmptyResult($result, true);
$this->markTestIncomplete();
}
public function testRecordings_GetRecording_NonExistingRecording() {
$result = $this->vm->getRecording("testtesttesttesttesttesttesttesttesttesttesttesttestte");
$this->checkErrorResult($result, 400, 'Recording not found');
}
public function dataRecordings_GetRecording_ClientSideChecks() {
yield [
"Invalid recording ID: can't be blank",
'',
];
yield [
"Invalid recording ID: must be in lower case",
'someIdOfRecording',
];
yield [
"Invalid recording ID: the length must be exactly 54",
'someidofrecording',
];
}
/**
*
* @dataProvider dataRecordings_GetRecording_ClientSideChecks
* @param string $expectedMessage
* @param string $recordingId
*/
public function testRecordings_GetRecording_ClientSideChecks(string $expectedMessage, string $recordingId) {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage($expectedMessage);
$this->vm->getRecording($recordingId);
}
public function dataRecordings_GetRecording_ServerSideChecks() {
/* todo
yield [
"recording ID can't be blank",
'',
];
*/
yield [
"Invalid recording ID: must be in lower case",
'someIdOfRecording',
];
yield [
"Invalid recording ID: the length must be exactly 54",
'someidofrecording',
];
}
/**
* @dataProvider dataRecordings_GetRecording_ServerSideChecks
* @param string $expectedMessage
* @param string $recordingId
*/
public function testRecordings_GetRecording_ServerSideChecks(string $expectedMessage, string $recordingId) {
$url = ($this->urlBuilder)(Endpoint::GET_RECORDING, ['recordingID' => $recordingId]);
$result = $this->vm->send('GET', $url);
$this->checkErrorResult($result, 400, $expectedMessage);
}
public function testRecordings_GetRecording_ValidRecordingId() {
$this->markTestIncomplete();
}
public function testMeetings_GetMeetings() {
$result = $this->vm->getMeetings();
$this->checkSuccessResult($result);
$this->markTestIncomplete();
}
/**
* Makes common checks for the successful result
* @param array $result
* @return array
*/
private function checkSuccessResult(array $result): array {
$this->assertSame(200, $this->vm->getLastResponse()->getStatusCode());
$this->assertCount(2, $result);
$this->assertSame(Vm::SUCCESS_STATUS, $result['status']);
$this->assertIsArray($result['data']);
$this->assertNotEmpty($result['data']);
return $result;
}
/**
* E.g. of the error result:
* array(3) {
* ["status"]=> string(5) "error"
* ["data"]=> NULL
* ["message"]=> string(19) "Recording not found"
* }
* @param array $result
* @param int $expectedStatusCode
* @return array
*/
private function checkErrorResult(array $result, int $expectedStatusCode, string $expectedMessage): array {
$this->assertSame($expectedStatusCode, $this->vm->getLastResponse()->getStatusCode());
$this->assertCount(3, $result);
$this->assertNull($result['data']);
$this->assertSame(Vm::ERR_STATUS, $result['status']);
$this->assertSame($expectedMessage, $result['message']);
return $result;
}
private function checkEmptyResult($result, bool $dataIsCollection) {
if ($dataIsCollection) {
$this->assertIsArray($result['data']);
} else {
$this->assertNull($result['data']);
}
}
private function expectResponse(string $endpoint, array $expectedResponseData) {
$expectedResponse = $this->mkSuccessResponse($expectedResponseData);
Server::enqueueResponse($this->toJson($expectedResponse));
$urlBuilder = $this->createStub(UrlBuilder::class);
$urlBuilder->method('__invoke')
->willReturn(Server::$url . $endpoint);
$this->vm->setUrlBuilder($urlBuilder);
}
private function mkSuccessResponse($responseData): array {
return [
'status' => Vm::SUCCESS_STATUS,
'data' => $responseData,
];
}
private function toJson($val): string {
return json_encode($val, JSON_UNESCAPED_SLASHES);
}
private function mkClientStub(string $expectedResponse): array {
// Create a mock and queue two responses.
$responseHandler = new MockHandler([
new Response(200, ['X-Foo' => 'Bar'], $expectedResponse),
new Response(202, ['Content-Length' => strlen($expectedResponse)]),
//new RequestException('Error Communicating with Server', new Request('GET', 'test'))
]);
$handlerStack = HandlerStack::create($responseHandler);
$client = new Client(['handler' => $handlerStack]);
return [$client, $responseHandler];
}
} |
// pages/checkin/checkin_content/checkin_content.js
// TODO: 日历上显示所有已打卡的日期
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
cur: '', // 当前名称
cur_id: 0, // 当前id
uid: "3", // 用户ID
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
calendarConfig: {
/**
* 初始化日历时指定默认选中日期,如:'2018-3-6' 或 '2018-03-06'
* 初始化时不默认选中当天,则将该值配置为false。
*/
multi: true, // 是否开启多选,
highlightToday: true, // 是否高亮显示当天,区别于选中样式(初始化时当天高亮并不代表已选中当天)
takeoverTap: true, // 是否完全接管日期点击事件(日期不会选中),配合 onTapDay() 使用
disablePastDay: false, // 是否禁选当天之前的日期
disableLaterDay: true, // 是否禁选当天之后的日期
firstDayOfWeek: 'Mon', // 每周第一天为周一还是周日,默认按周日开始
onlyShowCurrentMonth: false, // 日历面板是否只显示本月日期
hideHeadOnWeekMode: false, // 周视图模式是否隐藏日历头部
showHandlerOnWeekMode: true // 周视图模式是否显示日历头部操作栏,hideHeadOnWeekMode 优先级高于此配置
},
today: {
'day': '',
'month': '',
'year': '',
'week': ''
},
checkinItem: {
plannedDays: 'NaN1', //计划天数
checkinDays: 'NaN2', //打卡天数
missedDays: 'NaN3', //错过天数
totalCheckedDays: 'NaN4', //总计打卡天数
curConsecutiveDays: 'NaN5', //当前连续时长
maxConsecutiveDays: 'NaN6', //最大连续时长
createDay: 'NaN7', //建立时间
checkinProgess: "0" //当前进度
},
icon_url: {
'icon_delete': '../../../images/icon/icon_delete.png',
'icon_edit': '../../../images/icon/icon_edit.png',
},
//status字段代表此项状态,为true时代表创建并显示,为false时代表对其进行删除或屏蔽
clocks: [{
id: '1232131',
name: '跑步',
image: '../../images/clock/1.png',
background: '#d6c6de',
days: 1,
checked: false,
status: true,
},
{
id: '1232132',
name: '早起',
image: '../../images/clock/2.png',
background: '#5626e530',
days: 2,
checked: true,
status: true,
},
{
id: '1232133',
name: '跑步',
image: '../../images/clock/3.png',
background: '#d6c6de',
days: 1,
checked: true,
status: true,
},
{
id: '1232134',
name: '跑步',
image: '../../images/clock/4.png',
background: '#d6c6de',
days: 1,
checked: false,
status: true,
},
{
id: '1232135',
name: '跑步',
image: '../../images/clock/5.png',
background: '#d6c6de',
days: 1,
checked: false,
status: true,
}
]
},
//事件处理函数
bindViewTap: function() {
wx.navigateTo({
url: '../logs/logs'
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
console.log("message: ", options)
this.setData({
cur: options.content,
cur_id: options.id,
today: app.globalData.today
})
// 日历:禁止选择日期
//console.log(this.calendar)
// 获取此打卡项数据
var that = this;
wx.request({
url: "https://172.19.241.77:443/project/checkin/getCheckinByID",
method: "POST",
dataType: 'JSON',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
checkin_id: this.data.cur_id
},
success: function(res) {
console.log("getcheckinbyID: ",res.data);
var item = JSON.parse(res.data);
// 计算打卡进度百分比
var pc = 100;
if (parseInt(item.historyday)+1 == 0){
pc = 0;
}else{
if (item.totalcheckinday == null || item.historyday == null){
pc = 100;
}else{
var a = item.totalcheckinday;
var b = parseInt(item.historyday) + 1;
pc = a/b * 100;
console.log("百分比:",pc)
}
}
// historyday 返回的值少1
var pd = (item.historyday == null) ? item.totalcheckinday : parseInt(item.historyday)+1;
var md = (item.missday == null) ? 0 : (item.missday < 0 ? 0 : item.missday);
var obj = {
plannedDays: pd, //计划天数
checkinDays: item.totalcheckinday, //打卡天数
missedDays: md, //错过天数
totalCheckedDays: item.totalcheckinday, //总计打卡天数
curConsecutiveDays: item.stick_days, //当前连续时长
maxConsecutiveDays: item.stick_days, //最大连续时长
createDay: item.created_at, //建立时间
checkinProgess: pc, //当前进度
}
that.setData({
checkinItem: obj,
})
}
})
// 获取该打卡项的创建日期,/checkin/getCheckinByID中并没有返回此字段,需要另外进行查找
wx.request({
url: "https://172.19.241.77:443/project/checkin/getCheckinsAllByUser",
method: "POST",
dataType: 'JSON',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
user_id: that.data.uid
},
success: function (res) {
//console.log("JSON: ",JSON.parse(res.data));
var lists = JSON.parse(res.data);
for(var i = 0; i < lists.length; i++){
var id_i = lists[i].id;
if (id_i == that.data.cur_id){
that.setData({
"checkinItem.createDay": lists[i].created_at
})
break;
}
}
}
})
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse) {
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
},
getUserInfo: function(e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
//TODO:在这里加载个人数据?
},
/**
* 选择日期后执行的事件
* currentSelect 当前点击的日期
* allSelectedDays 选择的所有日期(当mulit为true时,allSelectedDays有值)
*/
afterTapDay(e) {
console.log('afterTapDay', e.detail); // => { currentSelect: {}, allSelectedDays: [] }
},
/**
* 当日历滑动时触发(适用于周/月视图)
* 可在滑动时按需在该方法内获取当前日历的一些数据
*/
onSwipe(e) {
console.log('onSwipe', e.detail);
const dates = this.calendar.getCalendarDates();
},
/**
* 当改变月份时触发
* => current 当前年月 / next 切换后的年月
*/
whenChangeMonth(e) {
console.log('whenChangeMonth', e.detail);
// => { current: { month: 3, ... }, next: { month: 4, ... }}
},
/**
* 周视图下当改变周时触发
* => current 当前周信息 / next 切换后周信息
*/
whenChangeWeek(e) {
console.log('whenChangeWeek', e.detail);
// {
// current: { currentYM: {year: 2019, month: 1 }, dates: [{}] },
// next: { currentYM: {year: 2019, month: 1}, dates: [{}] },
// directionType: 'next_week'
// }
},
/**
* 日期点击事件(此事件会完全接管点击事件),需自定义配置 takeoverTap 值为真才能生效
* currentSelect 当前点击的日期
*/
onTapDay(e) {
console.log('onTapDay', e.detail); // => { year: 2019, month: 12, day: 3, ...}
},
/**
* 日历初次渲染完成后触发事件,如设置事件标记
*/
afterCalendarRender(e) {
/* 多选所有的已打卡日期 */
// 请求获取数据库此打卡项的所有打卡日期
var checkinList = new Array();
var that = this;
var arr_month = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var int_month = arr_month.indexOf(app.globalData.today.month) + 1;
var time_str = app.globalData.today.year + "-" + int_month;
console.log(time_str);
wx.request({
url: "https://172.19.241.77:443/project/checkin/getMonthCheckin",
method: "POST",
dataType: 'JSON',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
//id: that.data.cur_id
user_id: that.data.uid,
this_month: time_str,
},
success: function(res) {
var tmpList = JSON.parse(res.data);
// 进行深度拷贝
var ll = new Array();
var i = 0;
for (i = 0; i < tmpList.length; i++) {
if (tmpList[i].checkin_id == that.data.cur_id) {
let split1 = tmpList[i].checkin_date.trim().split(" ")[0];
let split2 = split1.trim().split("-");
var obj = {
year: split2[0],
month: split2[1],
day: split2[2],
}
checkinList.push(obj);
}
}
console.log("checkinlist1", checkinList)
that.calendar.setSelectedDays(checkinList)
}
})
},
//按下删除图标
onClickDelete: function(e) {
console.log("按下了删除图标");
var that = this;
var pages = getCurrentPages(); //得到界面栈
var currPage = pages[pages.length - 1]; //当前页面
var prevPage = pages[pages.length - 2]; //上一个页面
wx.showModal({
title: '确定删除',
content: '是否确定删除该打卡项?',
success: function(res) {
if (res.confirm) {
// 删除此打卡项
wx.request({
url: "https://172.19.241.77:443/project/checkin/deleteCheckin",
method: "POST",
dataType: 'JSON',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
id: that.data.cur_id
},
success: function(res) {
console.log(res.data);
// 父层界面进行刷新
prevPage.getDatabaseData();
wx.navigateBack({
delta: 1
});
}
})
}
}
})
},
//按下编辑图标
onClickEdit: function(e) {
console.log("按下了编辑图标");
},
}) |
package com.coenvk.android.zycle.adapter
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView
import com.coenvk.android.zycle.ktx.inflate
import com.coenvk.android.zycle.viewholder.ViewHolder
internal sealed class ViewAdapter : Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return ViewHolder(parent.inflate(layoutInflater!!, viewType))
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) = Unit
override fun getLayoutRes(viewType: Int): Int {
return viewType
}
}
private class MultiViewAdapter(private vararg val layouts: Int) : ViewAdapter() {
constructor(layouts: List<Int>) : this(*layouts.toIntArray())
override fun getItemCount(): Int {
return layouts.size
}
override fun getItemViewType(position: Int): Int {
return layouts[position]
}
}
private class SingleViewAdapter(@LayoutRes private val layoutRes: Int) : ViewAdapter() {
override fun getItemCount(): Int = 1
override fun getItemViewType(position: Int): Int = layoutRes
}
internal fun viewAdapterOf(vararg layouts: Int): Adapter {
return when {
layouts.isEmpty() -> EmptyAdapter
layouts.size == 1 -> SingleViewAdapter(layouts[0])
else -> MultiViewAdapter(*layouts)
}
}
internal fun viewAdapterOf(layouts: List<Int>): Adapter {
return when {
layouts.isEmpty() -> EmptyAdapter
layouts.size == 1 -> SingleViewAdapter(layouts[0])
else -> MultiViewAdapter(layouts)
}
} |
module Activecube
module CubeDefinition
class DefinitionError < ::StandardError
end
class NamedHash < Hash
def initialize cube, entry_class
@cube = cube
@entry_class = entry_class
end
def [] key
v = super key
v.nil? ? nil : @entry_class.new(@cube, key, v.new)
end
end
attr_reader :dimensions, :metrics, :selectors, :models, :options
def inspect
name +
(@dimensions && " Dimensions: #{@dimensions.keys.join(',')}")+
(@metrics && " Metrics: #{@metrics.keys.join(',')}")+
(@selectors && " Selectors: #{@selectors.keys.join(',')}")+
(@models && " Models: #{@models.map(&:name).join(',')}")
end
private
def dimension data
store_definition_map! 'dimension', (@dimensions ||= NamedHash.new(self, Query::Slice) ), data
end
def metric data
store_definition_map! 'metric', (@metrics ||= NamedHash.new(self, Query::Measure)), data
end
def selector data
store_definition_map! 'filter', (@selectors ||= NamedHash.new(self, Query::Selector)), data
end
def table *args
store_definition_array! 'model', (@models ||= []), [*args].flatten.map{|t| t }
end
def option *args
store_definition_array! 'option', (@options ||= []), [*args].flatten.map{|t| t }
end
def dim_column column_name
Class.new(Activecube::Dimension) do
column column_name
end
end
def metric_column column_name
Class.new(Activecube::Metric) do
include Activecube::Common::Metrics
column column_name
modifier :calculate
define_method :expression do |model, arel_table, measure, cube_query|
if calculate = measure.modifier(:calculate)
self.send(calculate.args.first, model, arel_table, measure, cube_query)
else
sum(model, arel_table, measure, cube_query)
end
end
end
end
def select_column column_name
Class.new(Activecube::Selector) do
column column_name
end
end
def store_definition_map! name, map, data
data.each_pair do |key, class_def|
raise DefinitionError, "#{key} already defined for #{name}" if map.has_key?(key)
map[key] = class_def
end
end
def store_definition_array! name, array, data
values = data & array
raise DefinitionError, "#{values.join(',')} already defined for #{name}" unless values.empty?
array.concat data
end
end
end |
if (Test-Path .\chess-results.csv) {
Remove-Item .\chess-results.csv
}
python .\play_chess.py --search-depth 1 --max-children 1 --max-turns 999
python .\play_chess.py --search-depth 1 --max-children 5 --max-turns 999
python .\play_chess.py --search-depth 1 --max-children 10 --max-turns 999
python .\play_chess.py --search-depth 1 --max-children 15 --max-turns 999
python .\play_chess.py --search-depth 1 --max-children 20 --max-turns 999
python .\play_chess.py --search-depth 2 --max-children 1 --max-turns 999
python .\play_chess.py --search-depth 2 --max-children 5 --max-turns 999
python .\play_chess.py --search-depth 2 --max-children 10 --max-turns 999
python .\play_chess.py --search-depth 2 --max-children 15 --max-turns 999
python .\play_chess.py --search-depth 2 --max-children 20 --max-turns 999
python .\play_chess.py --search-depth 3 --max-children 1 --max-turns 999
python .\play_chess.py --search-depth 3 --max-children 5 --max-turns 999
python .\play_chess.py --search-depth 3 --max-children 10 --max-turns 999
python .\play_chess.py --search-depth 3 --max-children 15 --max-turns 999
python .\play_chess.py --search-depth 3 --max-children 20 --max-turns 999
python .\play_chess.py --search-depth 4 --max-children 1 --max-turns 999
python .\play_chess.py --search-depth 4 --max-children 5 --max-turns 999
python .\play_chess.py --search-depth 4 --max-children 10 --max-turns 999
python .\play_chess.py --search-depth 4 --max-children 15 --max-turns 999
python .\play_chess.py --search-depth 4 --max-children 20 --max-turns 999
python .\play_chess.py --search-depth 5 --max-children 1 --max-turns 999
python .\play_chess.py --search-depth 5 --max-children 5 --max-turns 999
python .\play_chess.py --search-depth 5 --max-children 10 --max-turns 999
python .\play_chess.py --search-depth 5 --max-children 15 --max-turns 999
python .\play_chess.py --search-depth 5 --max-children 20 --max-turns 999 |
require 'csv'
instructor_ids = Instructable.pluck(:user_id).uniq.compact
instructors = User.where(id: instructor_ids)
CSV.open('instructors_contacts.csv', 'wb') do |csv|
csv << ['InstructorName', 'ProfileEmail', 'AlternateEmail', 'Facebook', 'Twitter', 'WebPage']
instructors.each do |instructor|
methods = instructor.instructor_profile_contacts
profile_email = ''
alternate_email = ''
facebook = ''
twitter = ''
web_page = ''
methods.each do |method|
next if method.address.blank?
case method.protocol
when 'profile email'
if method.address == '1'
profile_email = instructor.email
end
when 'alternate email'
alternate_email = method.address
when 'facebook'
facebook = method.address
when 'twitter'
twitter = method.address
when 'web page'
web_page = method.address
end
end
csv << [ instructor.best_name, profile_email, alternate_email, facebook, twitter, web_page ]
end
end
|
# DON'T EDIT ME!
class Board
attr_reader :rows
def self.blank_grid
Array.new(3) { Array.new(3) }
end
def initialize(rows = self.class.blank_grid)
@rows = rows
end
def [](pos)
row, col = pos[0], pos[1]
@rows[row][col]
end
def []=(pos, mark)
raise "mark already placed there!" unless empty?(pos)
row, col = pos[0], pos[1]
@rows[row][col] = mark
end
def cols
cols = [[], [], []]
@rows.each do |row|
row.each_with_index do |mark, col_idx|
cols[col_idx] << mark
end
end
cols
end
def diagonals
down_diag = [[0, 0], [1, 1], [2, 2]]
up_diag = [[0, 2], [1, 1], [2, 0]]
[down_diag, up_diag].map do |diag|
# Note the `row, col` inside the block; this unpacks, or
# "destructures" the argument. Read more here:
# http://tony.pitluga.com/2011/08/08/destructuring-with-ruby.html
diag.map { |row, col| @rows[row][col] }
end
end
def dup
duped_rows = rows.map(&:dup)
self.class.new(duped_rows)
end
def empty?(pos)
self[pos].nil?
end
def tied?
return false if won?
# no empty space?
@rows.all? { |row| row.none? { |el| el.nil? }}
end
def over?
# don't use Ruby's `or` operator; always prefer `||`
won? || tied?
end
def winner
(rows + cols + diagonals).each do |triple|
return :x if triple == [:x, :x, :x]
return :o if triple == [:o, :o, :o]
end
nil
end
def won?
!winner.nil?
end
end
# Notice how the Board has the basic rules of the game, but no logic
# for actually prompting the user for moves. This is a rigorous
# decomposition of the "game state" into its own pure object
# unconcerned with how moves are processed.
class TicTacToe
class IllegalMoveError < RuntimeError
end
attr_reader :board, :players, :turn
def initialize(player1, player2)
@board = Board.new
@players = { :x => player1, :o => player2 }
@turn = :x
end
def run
until self.board.over?
play_turn
end
if self.board.won?
winning_player = self.players[self.board.winner]
puts "#{winning_player.name} won the game!"
else
puts "No one wins!"
end
end
def show
# not very pretty printing!
self.board.rows.each { |row| p row }
end
private
def place_mark(pos, mark)
if self.board.empty?(pos)
self.board[pos] = mark
true
else
false
end
end
def play_turn
loop do
current_player = self.players[self.turn]
pos = current_player.move(self, self.turn)
break if place_mark(pos, self.turn)
end
# swap next whose turn it will be next
@turn = ((self.turn == :x) ? :o : :x)
end
end
class HumanPlayer
attr_reader :name
def initialize(name)
@name = name
end
def move(game, mark)
game.show
while true
puts "#{@name}: please select your space"
row, col = gets.chomp.split(",").map(&:to_i)
if HumanPlayer.valid_coord?(row, col)
return [row, col]
else
puts "Invalid coordinate!"
end
end
end
private
def self.valid_coord?(row, col)
[row, col].all? { |coord| (0..2).include?(coord) }
end
end
class ComputerPlayer
attr_reader :name
def initialize
@name = "Tandy 400"
end
def move(game, mark)
winner_move(game, mark) || random_move(game)
end
private
def winner_move(game, mark)
(0..2).each do |row|
(0..2).each do |col|
board = game.board.dup
pos = [row, col]
next unless board.empty?(pos)
board[pos] = mark
return pos if board.winner == mark
end
end
# no winning move
nil
end
def random_move(game)
board = game.board
while true
range = (0..2).to_a
pos = [range.sample, range.sample]
return pos if board.empty?(pos)
end
end
end
if __FILE__ == $PROGRAM_NAME
puts "Play the dumb computer!"
hp = HumanPlayer.new("Ned")
cp = ComputerPlayer.new
TicTacToe.new(hp, cp).run
end
|
# -*- shell-script -*-
# gdb-like "next" (step through) commmand.
#
# Copyright (C) 2008, 2010, 2015, 2016 Rocky Bernstein [email protected]
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to
# the Free Software Foundation, 59 Temple Place, Suite 330, Boston,
# MA 02111 USA.
# Sets whether or not to display command to be executed in debugger prompt.
# If yes, always show. If auto, show only if the same line is to be run
# but the command is different.
_Dbg_help_add next \
"**next** [*count*]
Single step an statement skipping functions. This is sometimes called
'step over' or 'step through'.
If *count* is given, stepping occurs that many times before
stopping. Otherwise *count* is one. *count* an be an arithmetic
expression.
Functions and source'd files are not traced. This is in contrast to
**step**.
See also:
---------
**skip**." 1
# Next command
# $1 is command next+, next-, or next
# $2 is an optional additional count.
_Dbg_do_next() {
_Dbg_last_cmd='next'
_Dbg_inside_skip=0
_Dbg_next_skip_common 0 $@
return $?
}
_Dbg_alias_add 'n' 'next'
|
const { build } = require('esbuild')
build({
entryPoints: [
'./src/extension.ts',
'./src/webview/form.ts',
],
platform: 'node',
external: ['vscode'],
outdir: 'build',
tsconfig: './tsconfig.json',
bundle: true,
watch: true,
...(process.env.NODE_ENV === 'production' ? {
watch: false
} : {})
}) |
# Sod
Encryption util; two flavours: Sodium (preferred), or Sugar.
## Getting Started
```bash
$ composer require ssitu/sod
```
## How to
```php
use SSITU\Sod\Sod;
require_once '/path/to/vendor/autoload.php';
// Sod config:
$sodConfig["cryptKey"] = '703af4dd03ebe11e35167157a8a697d8a2cb545a907a38289f8a7ba19432a342';
$sodConfig["flavour"] = "Sugar"; # prefer "Sodium" if installed
// Sod init:
$Sod = new Sod($sodConfig);
// or:
# $Sod->setCryptKey(string $key);
# $Sod->setFlavour(string $flavour);
// For a quick check:
$Sod->hasCryptKey();
// To test if Sodium is installed:
var_dump($Sod->isLibSodiumOn());
// Encrypt:
$Sod->encrypt(string $message);
// Decrypt:
$Sod->decrypt(string $message);
// If something went wrong:
$Sod->getLogs();
```
## Contributing
Sure! You can take a loot at [CONTRIBUTING](CONTRIBUTING.md).
## License
This project is under the MIT License; cf. [LICENSE](LICENSE) for details. |
# -*- coding: utf-8 -*-
root = File.dirname(__FILE__) + '/..'
$:.unshift File.join(root, 'lib')
require 'reblog_bot'
job_type :reblog_bot, 'cd :path && bundle exec ruby reblog_bot.rb :task :output'
@config = ReblogBot::Environment.instance.config
@config[:accounts].each do |name, account|
log_name = "log/#{name}.log"
every 12.hours do
reblog_bot "followback #{name}", :output => log_name
end
next unless account[:every]
every instance_eval(account[:every]) do
reblog_bot "reblog #{name}", :output => log_name
end
end
|
# AMP-Toolbox Cache List
Lists known AMP Caches, as available at `https://cdn.ampproject.org/caches.json`.
By default, it uses a one-behind strategy to fetch the caches. This can be customised by
passing a custom fetch strategy to the constructor.
## Usage
```javascript
const Caches = require('amp-toolbox-cache-list');
const caches = new Caches();
// Lists known AMP Caches
const caches = await caches.list();
// Retrieves a specific AMP cache
const googleAmpCache = await caches.get('google');
```
|
using System.ComponentModel.DataAnnotations;
namespace GeraFin.Models.ViewModels.Admin
{
public class AdminUserViewModel
{
[Required(ErrorMessage = "User Name Required")]
public string UserName { get; set; }
[Required(ErrorMessage = "User Email Required")]
[EmailAddress(ErrorMessage = "Email Address Invalid")]
public string Email { get; set; }
public string Password { get; set; }
[Required(ErrorMessage = "User Phone Number Required")]
public string Phone { get; set; }
public string VerificationCode { get; set; }
public int Verify { get; set; }
public string AccountCreatingTime { get; set; }
public int State { get; set; }
}
}
|
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'components/rounded_button.dart';
class splashScreen extends StatefulWidget {
const splashScreen({Key? key}) : super(key: key);
@override
_splashScreenState createState() => _splashScreenState();
}
class _splashScreenState extends State<splashScreen> {
Future<void> initializeFirebase(BuildContext context) async {
try {
await Firebase.initializeApp();
} catch (e) {}
await Future.delayed(Duration(milliseconds: 1950), () {});
doneInitializing(context);
}
void doneInitializing(BuildContext context) {
if (FirebaseAuth.instance.currentUser != null) {
Navigator.pushReplacementNamed(context, "/choosePHScreen");
} else {
Navigator.pushReplacementNamed(context, "/choosePHScreen");
}
}
@override
Widget build(BuildContext context) {
initializeFirebase(context);
return Scaffold(
body: Stack(
children: [
Container(
alignment: Alignment.center,
child: Image.asset("assets/icon/main_logo.png",width: 80,height: 80,),
),
Container(
margin: EdgeInsets.all(30),
alignment: Alignment.bottomCenter,
child: Text(
"FLEET",
style: TextStyle(
color: kPrimaryColor,
fontSize: 26,
fontFamily: "oswald",
fontWeight: FontWeight.bold,
letterSpacing: 8),
),
),
],
)
);
}
}
|
// Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
export { ElementItemMetricComponent } from './metric.component';
export { ElementItemResultComponent } from './result.component';
export { ElementListMetricsComponent } from './metrics.component';
export { ElementListResultsComponent } from './results.component';
export { ElementPageComponent } from './page.component';
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class GoodReceiveNoteItem extends Model
{
public $fillable = [
'grn_id',
'po_item_id',
'order_quantity',
'receive_quantity'
];
public function purchaseOrderItem()
{
return $this->belongsTo(PurchaseOrderItem::class,'po_item_id', 'id');
}
}
|
#!/bin/sh
export CC=/opt/rh/llvm-toolset-7.0/root/usr/bin/clang
export CPP=/opt/rh/llvm-toolset-7.0/root/usr/bin/clang-cpp
export CXX=/opt/rh/llvm-toolset-7.0/root/usr/bin/clang++
export PATH=/opt/rh/llvm-toolset-7.0/root/usr/bin:/opt/rh/llvm-toolset-7.0/root/usr/sbin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/opt/rh/llvm-toolset-7.0/root/usr/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
pip wheel . -w dist/ --no-deps
auditwheel repair dist/*.whl --plat $AUDITWHEEL_PLAT
twine upload --skip-existing wheelhouse/*
|
unit AqDrop.Core.Generics.Releaser;
interface
uses
System.TypInfo;
type
TAqGenericReleaser = class
strict private
class var FImplementation: TAqGenericReleaser;
private
class procedure ReleaseImplementation;
strict protected
function DoTryToRelease(const pType: PTypeInfo; const pData: Pointer): Boolean; virtual; abstract;
public
class function TryToRelease<T>(pValue: T): Boolean; overload;
class function TryToRelease(const pType: PTypeInfo; const pData: Pointer): Boolean; overload;
class procedure SetImplementation(const pImplementation: TAqGenericReleaser);
class function VerifyIfHasImplementationSetted: Boolean;
end;
implementation
uses
System.SysUtils,
AqDrop.Core.Exceptions;
{ TAqGenericReleaser }
class procedure TAqGenericReleaser.ReleaseImplementation;
begin
FreeAndNil(FImplementation);
end;
class procedure TAqGenericReleaser.SetImplementation(const pImplementation: TAqGenericReleaser);
begin
ReleaseImplementation;
FImplementation := pImplementation;
end;
class function TAqGenericReleaser.TryToRelease(const pType: PTypeInfo; const pData: Pointer): Boolean;
begin
Result := FImplementation.DoTryToRelease(pType, pData);
end;
class function TAqGenericReleaser.TryToRelease<T>(pValue: T): Boolean;
begin
if Assigned(FImplementation) then
begin
Result := FImplementation.DoTryToRelease(TypeInfo(T), @pValue);
end else begin
raise EAqInternal.Create('No implementation provided for TAqGenericReleaser features.');
end;
end;
class function TAqGenericReleaser.VerifyIfHasImplementationSetted: Boolean;
begin
Result := Assigned(FImplementation);
end;
initialization
finalization
TAqGenericReleaser.ReleaseImplementation;
end.
|
module Mrt
module Ingest
class IngestException < RuntimeError
end
end
end
|
#include "regutils.h"
#include <memory>
#include <strsafe.h>
void Log(const wchar_t *format, ...);
std::wstring RegUtil::GuidToString(const GUID &guid) {
wchar_t guidStr[64];
HRESULT hr = ::StringCbPrintfW(
guidStr, sizeof(guidStr),
L"{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", guid.Data1,
guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2],
guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6],
guid.Data4[7]);
if (FAILED(hr)) {
Log(L"StringCbPrintfW failed - %08lx\n", hr);
return L"";
}
return guidStr;
}
bool RegUtil::SetStringInternal(LPCWSTR valueName, LPCWSTR valueData,
DWORD valueDataLength) const {
if (!mKey) {
return false;
}
LSTATUS ls = ::RegSetValueExW(mKey, valueName,
/*Reserved*/ 0, REG_SZ,
reinterpret_cast<const BYTE *>(valueData),
valueDataLength);
if (ls != ERROR_SUCCESS) {
Log(L"RegSetValueExW failed - %08x\n", ls);
return false;
}
return true;
}
RegUtil::RegUtil() : mKey(nullptr) {}
RegUtil::RegUtil(HKEY root, LPCWSTR subkey, bool createIfNotExist)
: mKey(nullptr) {
if (createIfNotExist) {
DWORD dispo;
LSTATUS ls =
::RegCreateKeyExW(root, subkey ? subkey : L"",
/*Reserved*/ 0,
/*lpClass*/ nullptr,
/*dwOptions*/ 0, KEY_ALL_ACCESS,
/*lpSecurityAttributes*/ nullptr, &mKey, &dispo);
if (ls != ERROR_SUCCESS) {
Log(L"RegCreateKeyExW failed - %08lx\n", ls);
return;
}
} else {
LSTATUS ls = ::RegOpenKeyExW(root, subkey,
/*ulOptions*/ 0, KEY_ALL_ACCESS, &mKey);
if (ls != ERROR_FILE_NOT_FOUND && ls != ERROR_SUCCESS) {
Log(L"RegOpenKeyExW failed - %08lx\n", ls);
return;
}
}
}
RegUtil::RegUtil(RegUtil &&other) : mKey(other.mKey) { other.mKey = nullptr; }
RegUtil &RegUtil::operator=(RegUtil &&other) {
if (this != &other) {
mKey = other.mKey;
other.mKey = nullptr;
}
return *this;
}
RegUtil::~RegUtil() {
if (!mKey) {
return;
}
LSTATUS ls = ::RegCloseKey(mKey);
if (ls != ERROR_SUCCESS) {
Log(L"RegCloseKey failed - %08lx\n", ls);
}
}
std::wstring RegUtil::GetString(LPCWSTR valueName) const {
DWORD type;
for (DWORD len = 1;; len *= 2) {
std::unique_ptr<uint8_t[]> buf(new uint8_t[len]);
LSTATUS status = ::RegGetValueW(mKey, nullptr, valueName, RRF_RT_REG_SZ,
&type, buf.get(), &len);
if (status == ERROR_SUCCESS) {
return std::wstring(reinterpret_cast<wchar_t *>(buf.get()));
} else if (status == ERROR_FILE_NOT_FOUND) {
return L"";
} else if (status != ERROR_MORE_DATA) {
Log(L"RegGetValueW failed - %08x\n", status);
return L"";
}
}
}
bool RegUtil::SetString(LPCWSTR valueName, LPCWSTR valueData) const {
return SetStringInternal(
valueName, valueData,
valueData ? static_cast<DWORD>((wcslen(valueData) + 1) * sizeof(wchar_t))
: 0);
}
bool RegUtil::SetString(LPCWSTR valueName,
const std::wstring &valueData) const {
return SetStringInternal(
valueName, valueData.c_str(),
static_cast<DWORD>((valueData.size() + 1) * sizeof(wchar_t)));
}
|
require "vagrant"
module VagrantPlugins
module Cloudstack
class Config < Vagrant.plugin("2", :config)
# Cloudstack api host.
#
# @return [String]
attr_accessor :host
# Hostname for the machine instance
# This will be passed through to the api.
#
# @return [String]
attr_accessor :name
# Cloudstack api path.
#
# @return [String]
attr_accessor :path
# Cloudstack api port.
#
# @return [String]
attr_accessor :port
# Cloudstack api scheme
#
# @return [String]
attr_accessor :scheme
# The API key for accessing Cloudstack.
#
# @return [String]
attr_accessor :api_key
# The secret key for accessing Cloudstack.
#
# @return [String]
attr_accessor :secret_key
# The timeout to wait for an instance to become ready.
#
# @return [Fixnum]
attr_accessor :instance_ready_timeout
# Domain id to launch the instance into.
#
# @return [String]
attr_accessor :domain_id
# Network uuid that the instance should use
#
# @return [String]
attr_accessor :network_id
# Network name that the instance should use
#
# @return [String]
attr_accessor :network_name
# Network Type
#
# @return [String]
attr_accessor :network_type
# Project uuid that the instance should belong to
#
# @return [String]
attr_accessor :project_id
# Service offering uuid to use for the instance
#
# @return [String]
attr_accessor :service_offering_id
# Service offering name to use for the instance
#
# @return [String]
attr_accessor :service_offering_name
# Template uuid to use for the instance
#
# @return [String]
attr_accessor :template_id
# Template name to use for the instance
#
# @return [String]
attr_accessor :template_name
# Zone uuid to launch the instance into. If nil, it will
# launch in default project.
#
# @return [String]
attr_accessor :zone_id
# Zone name to launch the instance into. If nil, it will
# launch in default project.
#
# @return [String]
attr_accessor :zone_name
# The name of the keypair to use.
#
# @return [String]
attr_accessor :keypair
# IP address id to use for port forwarding rule
#
# @return [String]
attr_accessor :pf_ip_address_id
# public port to use for port forwarding rule
#
# @return [String]
attr_accessor :pf_public_port
# private port to use for port forwarding rule
#
# @return [String]
attr_accessor :pf_private_port
# comma separated list of security groups id that going
# to be applied to the virtual machine.
#
# @return [Array]
attr_accessor :security_group_ids
# comma separated list of security groups name that going
# to be applied to the virtual machine.
#
# @return [Array]
attr_accessor :security_group_names
# comma separated list of security groups
# (hash with ingress/egress rules)
# to be applied to the virtual machine.
#
# @return [Array]
attr_accessor :security_groups
# display name for the instance
#
# @return [String]
attr_accessor :display_name
# group for the instance
#
# @return [String]
attr_accessor :group
# The user data string
#
# @return [String]
attr_accessor :user_data
def initialize(domain_specific=false)
@host = UNSET_VALUE
@name = UNSET_VALUE
@path = UNSET_VALUE
@port = UNSET_VALUE
@scheme = UNSET_VALUE
@api_key = UNSET_VALUE
@secret_key = UNSET_VALUE
@instance_ready_timeout = UNSET_VALUE
@domain_id = UNSET_VALUE
@network_id = UNSET_VALUE
@network_name = UNSET_VALUE
@network_type = UNSET_VALUE
@project_id = UNSET_VALUE
@service_offering_id = UNSET_VALUE
@service_offering_name = UNSET_VALUE
@template_id = UNSET_VALUE
@template_name = UNSET_VALUE
@zone_id = UNSET_VALUE
@zone_name = UNSET_VALUE
@keypair = UNSET_VALUE
@pf_ip_address_id = UNSET_VALUE
@pf_public_port = UNSET_VALUE
@pf_private_port = UNSET_VALUE
@security_group_ids = UNSET_VALUE
@display_name = UNSET_VALUE
@group = UNSET_VALUE
@security_group_names = UNSET_VALUE
@security_groups = UNSET_VALUE
@user_data = UNSET_VALUE
# Internal state (prefix with __ so they aren't automatically
# merged)
@__compiled_domain_configs = {}
@__finalized = false
@__domain_config = {}
@__domain_specific = domain_specific
end
# Allows domain-specific overrides of any of the settings on this
# configuration object. This allows the user to override things like
# template and keypair name for domains. Example:
#
# cloudstack.domain_config "abcd-ef01-2345-6789" do |domain|
# domain.template_id = "1234-5678-90ab-cdef"
# domain.keypair_name = "company-east"
# end
#
# @param [String] domain The Domain name to configure.
# @param [Hash] attributes Direct attributes to set on the configuration
# as a shortcut instead of specifying a full block.
# @yield [config] Yields a new domain configuration.
def domain_config(domain, attributes=nil, &block)
# Append the block to the list of domain configs for that domain.
# We'll evaluate these upon finalization.
@__domain_config[domain] ||= []
# Append a block that sets attributes if we got one
if attributes
attr_block = lambda do |config|
config.set_options(attributes)
end
@__domain_config[domain] << attr_block
end
# Append a block if we got one
@__domain_config[domain] << block if block_given?
end
#-------------------------------------------------------------------
# Internal methods.
#-------------------------------------------------------------------
def merge(other)
super.tap do |result|
# Copy over the domain specific flag. "True" is retained if either
# has it.
new_domain_specific = other.instance_variable_get(:@__domain_specific)
result.instance_variable_set(
:@__domain_specific, new_domain_specific || @__domain_specific)
# Go through all the domain configs and prepend ours onto
# theirs.
new_domain_config = other.instance_variable_get(:@__domain_config)
@__domain_config.each do |key, value|
new_domain_config[key] ||= []
new_domain_config[key] = value + new_domain_config[key]
end
# Set it
result.instance_variable_set(:@__domain_config, new_domain_config)
# Merge in the tags
result.tags.merge!(self.tags)
result.tags.merge!(other.tags)
end
end
def finalize!
# Host must be nil, since we can't default that
@host = nil if @host == UNSET_VALUE
# Name must be nil, since we can't default that
@name = nil if @name == UNSET_VALUE
# Path must be nil, since we can't default that
@path = nil if @path == UNSET_VALUE
# Port must be nil, since we can't default that
@port = nil if @port == UNSET_VALUE
# We default the scheme to whatever the user has specifid in the .fog file
# *OR* whatever is default for the provider in the fog library
@scheme = nil if @scheme == UNSET_VALUE
# Try to get access keys from environment variables, they will
# default to nil if the environment variables are not present
@api_key = ENV['CLOUDSTACK_API_KEY'] if @api_key == UNSET_VALUE
@secret_key = ENV['CLOUDSTACK_SECRET_KEY'] if @secret_key == UNSET_VALUE
# Set the default timeout for waiting for an instance to be ready
@instance_ready_timeout = 120 if @instance_ready_timeout == UNSET_VALUE
# Domain id must be nil, since we can't default that
@domain_id = nil if @domain_id == UNSET_VALUE
# Network uuid must be nil, since we can't default that
@network_id = nil if @network_id == UNSET_VALUE
# Network uuid must be nil, since we can't default that
@network_name = nil if @network_name == UNSET_VALUE
# NetworkType is 'Advanced' by default
@network_type = "Advanced" if @network_type == UNSET_VALUE
# Project uuid must be nil, since we can't default that
@project_id = nil if @project_id == UNSET_VALUE
# Service offering uuid must be nil, since we can't default that
@service_offering_id = nil if @service_offering_id == UNSET_VALUE
# Service offering name must be nil, since we can't default that
@service_offering_name = nil if @service_offering_name == UNSET_VALUE
# Template uuid must be nil, since we can't default that
@template_id = nil if @template_id == UNSET_VALUE
# Template name must be nil, since we can't default that
@template_name = nil if @template_name == UNSET_VALUE
# Zone uuid must be nil, since we can't default that
@zone_id = nil if @zone_id == UNSET_VALUE
# Zone uuid must be nil, since we can't default that
@zone_name = nil if @zone_name == UNSET_VALUE
# Keypair defaults to nil
@keypair = nil if @keypair == UNSET_VALUE
# IP address id must be nil, since we can't default that
@pf_ip_address_id = nil if @pf_ip_address_id == UNSET_VALUE
# Public port must be nil, since we can't default that
@pf_public_port = nil if @pf_public_port == UNSET_VALUE
# Private port must be nil, since we can't default that
@pf_private_port = nil if @pf_private_port == UNSET_VALUE
# Security Group IDs must be nil, since we can't default that
@security_group_ids = nil if @security_group_ids == UNSET_VALUE
# Security Group Names must be nil, since we can't default that
@security_group_names = nil if @security_group_names == UNSET_VALUE
# Security Groups must be nil, since we can't default that
@security_groups = nil if @security_groups == UNSET_VALUE
# Display name must be nil, since we can't default that
@display_name = nil if @display_name == UNSET_VALUE
# Group must be nil, since we can't default that
@group = nil if @group == UNSET_VALUE
# User Data is nil by default
@user_data = nil if @user_data == UNSET_VALUE
# Compile our domain specific configurations only within
# NON-DOMAIN-SPECIFIC configurations.
if !@__domain_specific
@__domain_config.each do |domain, blocks|
config = self.class.new(true).merge(self)
# Execute the configuration for each block
blocks.each { |b| b.call(config) }
# The domain name of the configuration always equals the
# domain config name:
config.domain = domain
# Finalize the configuration
config.finalize!
# Store it for retrieval
@__compiled_domain_configs[domain] = config
end
end
# Mark that we finalized
@__finalized = true
end
def validate(machine)
errors = []
if @domain
# Get the configuration for the domain we're using and validate only
# that domain.
config = get_domain_config(@domain)
if !config.use_fog_profile
errors << I18n.t("vagrant_cloudstack.config.api_key_required") if \
config.access_key_id.nil?
errors << I18n.t("vagrant_cloudstack.config.secret_key_required") if \
config.secret_access_key.nil?
end
end
{"Cloudstack Provider" => errors}
end
# This gets the configuration for a specific domain. It shouldn't
# be called by the general public and is only used internally.
def get_domain_config(name)
if !@__finalized
raise "Configuration must be finalized before calling this method."
end
# Return the compiled domain config
@__compiled_domain_configs[name] || self
end
end
end
end
|
__author__ = "Aadil Latif"
__version__ = "1.0.0"
__maintainer__ = "Aadil Latif"
__email__ = "[email protected]"
customer_types = {
0 : 'Residential',
1 : 'Small_Commercial',
2 : 'Large_Commercial',
3 : 'Large_Power',
4 : 'Motor_Load',
5 : 'Irrigation',
6 : 'Oil_and_Gas',
7 : 'Traffic_Lights',
8 : 'Security_and_Street_Lights',
9 : 'Flat_Rate_Load',
10 : 'Primary',
}
load_mix = {
0 : 'Constant kVA PU, Default=1',
1 : 'Constant IMP In PU, Default=0',
2 : 'Constant Current In PU, Default=0',
3 : 'Connection Code W=Wye, D=Delta, Default=W',
4 : 'Named Equipment Category',
}
conductor_material = {
1 : 'Anaconda',
2 : 'ACSR',
3 : 'Alum',
4 : 'AAC',
5 : 'Copper',
6 : 'CW',
7 : 'CWC',
8 : 'HdAlum',
9 : 'HD Copper',
10 : 'HHHC',
11 : 'Steel',
12 : 'User-Defined',
}
xfmr_mounting = {
0 : 'Unknown',
1 : 'Bus Mounted',
2 : 'Pole Mounted',
3 : 'Pad Mounted',
4 : 'Vault Mounted',
5 : 'Substation',
6 : 'Other',
}
device_group = {
0 : 'None',
1 : 'Source',
2 : 'Bay',
3 : 'OCR',
4 : 'Recloser',
5 : 'Fuse',
6 : 'Sectionalizer',
7 : 'Circuit_Breaker',
}
height_units = {
0 : 'Total',
1 : 'mi',
2 : 'km',
3 : 'mft',
4 : 'ft',
5 : 'm',
6 : 'in',
7 : 'cm',
}
impedance_units = {
0 : 'Ohms',
1 : 'Percent',
2 : 'Per Unit',
3 : 'Total',
}
xfmr_types = {
0 : 'Single Phase Balanced',
1 : 'Single Phase Unbalanced',
2 : '3 Phase',
3 : '3 Winding',
}
ugCable_type = {
0 : 'Concentric',
1 : 'Tape Shield',
2 : 'No Concentric',
}
unit_field_values = {
0 : 'Total',
1 : 'Mile',
2 : 'Kilometer',
3 : 'Mft',
4 : 'Feet',
5 : 'Meter',
}
capacitor_conn = {
0 : 'Y',
1 : 'D',
2 : 'Shunt Same as Parent',
3 : 'Series',
}
capacitor_state = {
0 : 'Disconnected',
1 : 'On',
2 : 'Off',
}
capacitor_control_type = {
0 : 'none',
1 : 'voltage',
2 : 'currentFlow',
3 : 'reactivePower',
4 : 'timeScheduled',
5 : 'temperature',
}
circuit_level = {
0 : 'None',
1 : 'Feeder',
2 : 'Substation Low Side Bus',
3 : 'Substation High Side Bus',
4 : 'Spot Load',
5 : 'Consumer',
6 : 'Active Consumer',
7 : 'Inactive Consumer',
}
generator_conn = {
'W' : 'Y',
'D' : 'D',
}
soft_start_types = {
0 : 'None',
1 : 'Impedance',
2 : 'Auto Transformer',
3 : 'Capacitive',
4 : 'Partial Winding',
5 : 'Wye Delta',
}
motor_status = {
0 : 'Disconnected',
1 : 'Off',
2 : 'Locked Rotor',
3 : 'Soft Start',
4 : 'Running',
}
xfmr_conn = {
1 : ['Y', 'Y'],#'(Y,Y Ground)', # Any valid configuration. (Default)
2 : ['D', 'Y'],#'(D-Y Ground)', # See the Transformer Phasing Note 1 section.
3 : ['Y', 'D'],#'(Y-D Ground)', # See the Transformer Phasing Note 1 section.
4 : '(Ungrounded Y-D)',# See the Transformer Phasing Note 1 section.
5 : '(Y-D Open)', #Transformer must be ABC. Upline element can be ABC, AB, or AC.
6 : '(D-D)', #See the Transformer Phasing Note 1 section.
7 : '(Y-Y with Grounded Impedance)', #Any valid configuration.
8 : '(Y-Y with Three-Phase Transformer Core)', #Any valid configuration.
9 : '(D-D One)', #See the Transformer Phasing Note 2 section.
10 : '(D-D Open)', #See the Transformer Phasing Note 1 section.
11 : '(Y-Y-D Ground)', #See the Transformer Phasing Note 1 section.
12 : '(Y-D One)', #See the Transformer Phasing Note 3 section.
13 : '(D-Y Open)', #See the Transformer Phasing Note 1 section.
14 : '(D-Y One)', #See the Transformer Phasing Note 4 section.
15 : '(Ungrounded D-Y)',
16 : '(Y-Y-Y Ground)',
17 : '(D-Y-D)',
18 : '(D-D-D)',
}
generator_model = {
0 : 'Negative Load',
1 : 'Swing Unlimited',
2 : 'Swing kVA',
3 : 'Swing kvar',
}
fault_coord_type = {
0 : 'Not Required',
1 : 'Fuse save for all flt',
2 : 'Fuse save for 3-ph flt',
3 : 'Fuse save for 2-ph flt',
4 : 'Fuse save for 1-ph flt',
5 : 'Fuse blow for all flt',
6 : 'Fuse blow for 3-ph flt',
7 : 'Fuse blow for 2-ph flt',
8 : 'Fuse blow for 1-ph flt',
9 : 'Coordinate for all flt',
10 : 'Coordinate for 3-phase flt',
11 : 'Coordinate for 2-phase flt',
12 : 'Coordinate for 1-phase flt',
13 : 'Sequentially coordinate for transformer multiplier 1.0',
14 : 'Sequentially coordinate for 3-phase fault',
15 : 'Sequentially coordinate for 2-phase fault',
16 : 'Sequentially coordinate for 1-phase fault',
17 : 'Recl has no curves',
18 : 'Recl has no fast curves',
19 : 'Recl has no slow curves',
20 : 'Fuse is too small',
21 : 'Fuse is too large',
22 : '2 and 3 Phs Flt',
23 : '1-phase fault with upline delta transformer',
24 : '2- or 3-phase fault with upline ground return',
25 : 'Recloser has no phase curves',
26 : 'Fuse is too small for multi phase',
27 : 'Fuse is too small for single phase',
28 : 'Coordinate for all faults (initially slower)',
29 : 'Coordinate for 3-phase faults (initially slower)',
30 : 'Coordinate for 2-phase faults (initially slower)',
31 : 'Coordinate for 1-phase faults (initially slower)',
32 : 'Coordinate for 2&3-phase faults (initially slower)',
33 : 'Invalid device coordination type',
}
std_file_headings = {
'Line' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number', 'X Coordinate',
'Y Coordinate','User Tag','Conductor Phase A','Conductor Phase B','Conductor Phase C','Conductor neutral',
'Impedance Length','Construction Description','Load Mix Description','Load Zone Description',
'Load Location', 'Load Growth','Billing Reference','Allocated kW, Ph A','Allocated kW, Ph B',
'Allocated kW, Ph C', 'Allocated kvar, Ph A', 'Allocated kvar, Ph B', 'Allocated kvar, Ph C',
'Allocated Consumers, Phase A', 'Allocated Consumers, Phase B', 'Allocated Consumers, Phase C',
'Load Interruptible Type' ,'Failure Rate','Repair Time','Upline X Coordinate','Upline Y Coordinate',
'Number of Neutrals','Conductor Graphical Length','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'GUID','pGUID','Unused','mGUID','Phase A Energized','Phase B Energized','Phase C Energized','X2','Y2',
'Rotation Angle','Circuit Level','Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Capacitor' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate','Y Coordinate','User Tag','kvar, Phase A','kvar, Phase B','kvar, Phase C',
'Voltage Rating','Switch Type Code','Switch Status Code','Switch On Setting','Switch Off Setting',
'Control Element','Connection','Unit Size kvar','Control Phase','Failure Rate','Repair Time',
'Bypass Time','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','GUID','pGUID','Unused','mGUID','Phase A Energized','Phase B Energized',
'Phase C Energized','X2','Y2','Rotation Angle','Circuit Level','Substation GUID','Substation Name',
'Feeder GUID','Feeder Name'],
'Regulator' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag', 'Regulator Type','Controlling Phase',
'Regulator Winding Connection', 'Regulator Description, Phase A','Regulator Description, Phase B',
'Regulator Description, Phase C','Output Voltage, Phase A','Output Voltage, Phase B',
'Output Voltage, Phase C','LDC R Setting, Phase A','LDC R Setting, Phase B','LDC R Setting, Phase C',
'LDC X Setting, Phase A','LDC X Setting, Phase B','LDC X Setting, Phase C','House High Protector, Ph A',
'1st House High Protector, Ph B','1st House High Protector, Ph C','1st House Low Protector, Ph A',
'1st House Low Protector, Ph B','1st House Low Protector, Ph C','Failure Rate','Repair Time',
'Bypass Time','Regulator Bypass A','Regulator Bypass B','Regulator Bypass C','All Phases Same',
'Control Element','-','-','-','-','-','-','-','-','-','-','-','ceGUID','GUID','pGUID','Unused',
'mGUID','Phase A Energized','Phase B Energized','Phase C Energized','X5','Y5','Rotation Angle',
'Circuit Level','Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Transformer' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag','Transformer Winding Connection','UNUSED',
'Rated Input Voltage (Src Side)','UNUSED','UNUSED','Rated Output Voltage (Load Side)',
'APCNF (Source Side Config)','Rated Tertiary Output Voltage','Tertiary Child Identifier',
'Nominal Output Voltage In kV.','Nominal Output Voltage of Tertiary In kV.','Tran kVA A',
'Tran kVA B','Tran kVA C','Failure Rate','Repair Time','Xfmr Cond Desc. Ph A','Xfmr Cond Desc. Ph B',
'Xfmr Cond Desc. Ph C','Is Center Tap','Transformer Mounting','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','GUID','pGUID','Unused','mGUID','Phase A Energized',
'Phase B Energized','Phase C Energized','X5','Y5','Rotation Angle','Circuit Level',
'Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Switch' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag','Switch Status','Switch ID','Partner Identifier',
'Failure Rate','Repair Time','Bypass Time In Hours','Close Time In Hours','Open Time In Hours',
'Element Specific','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-', '-', '-', '-', '-', '-', '-', '-', '-', '-','-','ptnrGUID','GUID','pGUID','Unused','mGUID',
'Phase A Energized','Phase B Energized','Phase C Energized','X5','Y5','Rotation Angle','Circuit Level',
'Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Node' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number','X Coordinate',
'Y Coordinate','User Tag','Feeder Number','Load Allocation Control Point','Load Mix Description',
'Load Zone Description','Load Location','Load Growth','Billing Reference','Allocated kW, Phase A',
'Allocated kW, Phase B','Allocated kW, Phase C','Allocated kvar, Phase A','Allocated kvar, Phase B',
'Allocated kvar, Phase C','Allocated Consumers, Ph A','Allocated Consumers, Ph B',
'Allocated Consumers, Ph C','Node Is Mandatory','Circuit Level', 'Load Interruptible Type','A Phase Parent',
'B Phase Parent','C Phase Parent','IsMultiParent','Consumer Type','Feeder Color','A Phase Parent GUID',
'B Phase Parent GUID','C Phase Parent GUID','-','-','-','-','-','-','-','-','-','-','-','-','-','GUID',
'pGUID','Unused','mGUID','Phase A Energized','Phase B Energized','Phase C Energized','X8','Y8',
'Rotation Angle','Circuit Level','Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Source' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag','Zsm Impedance Desc Minimum','Zsm Impedance Desc Maximum',
'Substation Number','Bus Voltage','OH Ground Ohms for Min Fault','UG Ground Ohms for Min Fault',
'Nominal Voltage','Load Allocation Control Point','Wye or Delta Connection Code','Regulation Code',
'Failure Rate','Repair Time','Close Time','Open Time','Feeder Color 0x00RRGGBB','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','GUID','pGUID','Unused',
'mGUID','Phase A Energized','Phase B Energized','Phase C Energized','X9','Y9','Rotation Angle',
'Circuit Level','Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Overcurrent Device' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag','Description, Ph A','Description, Ph B',
'Description, Ph C','Is Closed, Phase A','Is Closed, Phase B','Is Closed, Phase C',
'Close All Phases Same as First Existing Phase','Load Allocation Control Point',
'Is Feeder Bay','Feeder Number','Feeder Color','Feeder Name','Failure Rate','Repair Time',
'Bypass Time','Close Time','Open Time','Coordination Failure Rate Failures/Yr',
'Fuse Coordination Method','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','GUID','pGUID','Unused','mGUID','Phase A Energized','Phase B Energized',
'Phase C Energized','X10','Y10','Rotation Angle','Circuit Level','Substation GUID',
'Substation Name','Feeder GUID','Feeder Name'],
'Motor' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag', 'Steady State Cond. Description','Transient Cond. Description',
'Sub Transident Cond. Desc.','Rated Voltage','Load Mix Description','Load Zone Description',
'Load Location','Load Growth',"Allocated kW, Phase A","Allocated kW, Phase B","Allocated kW, Phase C",
"Allocated kvar, Phase A","Allocated kvar, Phase B","Allocated kvar, Phase C",
"Allocated Consumers, Phase A","Allocated Consumers, Phase B","Allocated Consumers, Phase C",
'Model','Motor Status','Horse Power','Running Power Factor','% Efficiency','Rated LG kV','Drop Out Limit',
'NEMA Type','Motor Start Limit','Motor Start Limited By','Soft Start Type','Soft Start Impedance',
'Soft Start Impedance','Soft Start Tap','Soft Start Winding','Locked Rotor Power',
'Locked Rotor Multiplier','Failure Rate','Repair Time','Using advanced model',
'Advanced conductor equipment','Advanced input power','Percent Utilization','-','GUID','pGUID','Unused',
'mGUID','Phase A Energized','Phase B Energized','Phase C Energized','X11','Y11','Rotation Angle',
'Circuit Level','Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Generator' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag','Steady State Cond. Description','Transient Cond. Description',
'Sub Transident Cond. Desc.','Rated Voltage','Load Mix Description','Load Zone Description',
'Load Location','Load Growth',"Allocated kW, Phase A","Allocated kW, Phase B","Allocated kW, Phase C",
"Allocated kvar, Phase A","Allocated kvar, Phase B","Allocated kvar, Phase C",
"Allocated Consumers, Phase A","Allocated Consumers, Phase B","Allocated Consumers, Phase C",'Model',
'Voltage to Hold','Voltage to Hold','Section to Hold Voltage At','kW Out','Maximum kW Out',
'Maximum kvar Lead Output','Maximum kvar Lagg Output','Rated Voltage for Gen. as Source',
'Wye or Delta Connection','Failure Rate','Repair Time','-','-','-','-','-','-','-','-','-','-','-','-',
'GUID','pGUID','Unused','mGUID','Phase A Energized','Phase B Energized','Phase C Energized','X12',
'Y12','Rotation Angle','Circuit Level','Substation GUID','Substation Name','Feeder GUID','Feeder Name'],
'Consumer' : ['Element Name', 'Element Type', 'Phase Configuration', 'Parent Element Name', 'Map Number',
'X Coordinate', 'Y Coordinate','User Tag','Load Mix Description','Load Zone Description','Load Growth',
'Billing Code','Allocated kW (Ph A)','Allocated kW (Ph B)','Allocated kW (Ph C)','Allocated kvar (Ph A)',
'Allocated kvar (Ph B)','Allocated kvar (Ph C)','Allocated Consumers (Ph A)','Allocated Consumers (Ph B)',
'Allocated Consumers (Ph C)','Load Interruptible Type',"Is Consumer Active 0=Inactive, 1=Active",
'Consumer Type','Meter Number','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','GUID','pGUID','Unused','mGUID','Phase A Energized','Phase B Energized',
'Phase C Energized','X13','Y13','Rotation Angle','Circuit Level','Substation GUID','Substation Name',
'Feeder GUID','Feeder Name'],
}
seq_file_headings = {
'Overhead Conductor' : ['Equipment Identifier','Equipment Type','Material','Carrying Capacity','Resistance @ 25',
'Resistance @ 50','Geometric Mean Radius','Preferred Neutral Description','Diameter',
'Named Equipment Category','Preferred Neutral Identifier','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','oGID'],
'Underground Conductor' : ['Equipment Identifier','Equipment Type','Cable Type','Carrying Capacity In Amps',
'Phase Conductor Resistance Ohms/Mile','Geometric Mean Radius In Feet',
'Concentric Neutral Resist Ohms/Mile','# of Individual Strands in Neutral Default=0',
'OD of Cable Insulation In Feet','OD of Cable Including Neutral In Fee','Note Used',
'Dielectric Constant of Insulation Under Neutral ','Diameter Under Neutral In Feet',
'Not Used','kV Depreciated','Type Neutral Depreciated','GMR (Neutral) In Feed',
'Diameter of Conductor In Feet','Distance to CN In Feet','Named Equipment Category','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','oGID'],
'Zsm Conductor' : ['Equipment Identifier','Equipment Type','Carrying Capacity','Types of Units (for display)',
'Base kVA','Base kV','Units (for display)','Self Impedance- R','Self Impedance- +jX',
'Self Impedance- +jB','Mutual Impedance- R','Mutual Impedance- +jX','Mutual Impedance- +jB',
'Positive Sequence- R','Positive Sequence- jX','Zero Sequence- R','Zero Sequence- jX',
'Mutual Reverse- R','Mutual Reverse- jX','Negative Sequence- R','Negative Sequence- jX',
'Named Equipment Category','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','oGID'],
'Zabc Conductor' : ['Equipment Identifier','Equipment Type','Carrying Capacity','Types of Units (for display)',
'Base kVA','Base kV','Units','Impedance R-AA','Impedance jX-AA','Impedance R-AB',
'Impedance jX-AB','Impedance R-AC','Impedance jX-AC','Impedance R-BA','Impedance jX-BA',
'Impedance R-BB','Impedance jX-BB','Impedance R-BC','Impedance jX-BC','Impedance R-CA',
'Impedance jX-CA','Impedance R-CB','Impedance jX-CB','Impedance R-CC','Impedance jX-CC',
'Named Equipment Category','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','oGID'],
'Transformer' : ['Equipment Identifier','Equipment Type','Ampacity','Type of Transformer Cond',
'Percent Impedance- Zps','Percent Impedance- Zpt','Percent Impedance- Zst','X/R Ratio- Phase A',
'X/R Ratio- Phase B','X/R Ratio- Phase C','Single Phase Base kVA- Zps','Single Phase Base kVA- Zpt',
'Single Phase Base kVA- Zst','Zgp- R Value','Zgs- R Value','Zg- R Value','Zgp- X Value',
'Zgs- X Value','Zg- X Value','K Factor','No-Load Loss- Zps','No-Load Loss- Zpt','No-Load Loss- Zst',
'Named Equipment Category','Single Phase Rated kVA- Zps','Single Phase Rated kVA- Zpt',
'Single Phase Rated kVA- Zst','Is Pad Mounted Transformer','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','oGID'],
'Regulator' : ['Equipment Identifier','Equipment Type','Ampacity','CT Rating','% Boost','% Buck','Step Size',
'Bandwidth','Named Equipment Category','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'oGID'],
'Load Mix' : ['Equipment Identifier','Equipment Type','Constant kVA','Constant IMP','Constant Current',
'Connection Code','Named Equipment Category','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','oGID'],
'Construction Code' : ['Equipment Identifier','Equipment Type','OH Single Phase GMDP','OH V-Phase GMDP',
'OH 3-Phase GMPD','OH Single Phase GMDPN','OH V-Phase GMDPN','OH 3-Phase GMDPN','UG GMDP',
'Height Above Ground','Height Unit','Distance Between OD','Distance Unit','Spacing',
'Maximum Operating Voltage','Assume Full Transposition','Position of Single Phase',
'Position of First Phase','Position of Second Phase','Vertical Height Position- Phase A',
'Vertical Height Position- Phase B','Vertical Height Position- Phase C',
'Vertical Height Position- Neutral','Horizontal Distance Position- Phase A',
'Horizontal Distance Position- Phase B','Horizontal Distance Position- Phase C',
'Horizontal Distance Position- Neutral','Named Equipment Category','UG GMDPN','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','oGID'],
'Load Zone' : ['Equipment Identifier','Equipment Type','Growth Rate','Named Equipment Category','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','oGID'],
'Device' : ['Equipment Identifier','Equipment Type','Group','Current Rating','Max Symmetrical Fault',
'Max Asymmetrical Fault','Minimum Pickup Ground','Nominal Voltage','Number of Fast Trip Phase',
'Number of Slow Trip Phase','Electronic or Hydraulic','Use LightTable','LightTable Device Control',
'LightTable Operating Device','Single Phase Operation','Named Equipment Category','Minimum Pickup Phase',
'Has Phase Trip','Has Ground Trip','Number of Fast Trip Ground','Number of Slow Trip Ground','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'oGID'],
'Protected Device' : ['Equipment Identifier','Equipment Type','Protected Device Desc.','Coordination Point 1',
'Coordination Point 2','Protected Device kV','Device kV','Transformation Multiplier',
'Type of Fault','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','oGID'],
'Assemblies' : ['Equipment Identifier','Equipment Type','Named Equipment Category','Assembly Type',
'Associated Element Type','Assembly Description','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-',
'-','-','-','-','-','-','-','oGID'],
'Switchgear' : ['Equipment Identifier','Equipment Type','Switchgear Type','Cabinet Count','Cabinet 1 Number',
'Cabinet 1 Type','Cabinet 1 Eq Phase A NAME','Cabinet 1 Eq Phase B NAME','Cabinet 1 Eq Phase C NAME',
'Cabinet 2 Number','Cabinet 2 Type','Cabinet 2 Eq Phase A NAME','Cabinet 2 Eq Phase B NAME',
'Cabinet 2 Eq Phase C NAME','Cabinet 3 Number','Cabinet 3 Type','Cabinet 3 Eq Phase A NAME',
'Cabinet 3 Eq Phase B NAME','Cabinet 3 Eq Phase C NAME','Cabinet 4 Number','Cabinet 4 Type',
'Cabinet 4 Eq Phase A NAME','Cabinet 4 Eq Phase B NAME','Cabinet 4 Eq Phase C NAME',
'Cabinet 5 Number','Cabinet 5 Type','Cabinet 5 Eq Phase A NAME','Cabinet 5 Eq Phase B NAME',
'Cabinet 5 Eq Phase C NAME','Cabinet 6 Number','Cabinet 6 Type','Cabinet 6 Eq Phase A NAME',
'Cabinet 6 Eq Phase B NAME','Cabinet 6 Eq Phase C NAME','Cabinet 7 Number','Cabinet 7 Type',
'Cabinet 7 Eq Phase A NAME','Cabinet 7 Eq Phase B NAME','Cabinet 7 Eq Phase C NAME',
'Cabinet 8 Number','Cabinet 8 Type','Cabinet 8 Eq Phase A NAME','Cabinet 8 Eq Phase B NAME',
'Cabinet 8 Eq Phase C NAME','Cabinet 9 Number','Cabinet 9 Type','Cabinet 9 Eq Phase A NAME',
'Cabinet 9 Eq Phase B NAME','Cabinet 9 Eq Phase C NAME','oGID'],
}
|
/*
* Created on 29 Mar 2008
*/
package uk.org.ponder.messageutil;
/** A convenient exception class to contribute a {@link TargettedMessage} to the
* current environment, without requiring to inject a particular
* {@link TargettedMessageList}, or take particular responsibility for the
* target.
*
* @author Antranig Basman ([email protected])
*
*/
public class TargettedMessageException extends RuntimeException {
private TargettedMessage message;
/** Construct a TargettedMessageException wrapping the supplied
* {@link TargettedMessage} object. The <code>targetid</code> field may be
* left blank, in which case it will be automatically fixed up by the
* environment, probably to take account of the EL location of the current
* operation.
*
* @param message The message structure to wrap
*/
public TargettedMessageException(TargettedMessage message) {
this.message = message;
}
public TargettedMessageException(TargettedMessage message, Throwable cause) {
super(cause);
this.message = message;
}
public TargettedMessage getTargettedMessage() {
return message;
}
}
|
---
ENTRYTYPE: inproceedings
added: 2020-03-01
authors:
- K. Rustan M. Leino
booktitle: 2013 35th International Conference on Software Engineering (ICSE)
doi: 10.1109/ICSE.2013.6606754
issn: 1558-1225
keywords: program verification;specification languages;Dafny programs;specification
langauge;program verifier;programming language;Arrays;Tutorials;Reactive power;Cognition;Security;Educational
institutions;Computer languages
layout: paper
month: May
number: ''
pages: 1488-1490
read: true
readings:
- 2020-02-28
title: Developing verified programs with Dafny
volume: ''
year: 2013
topics:
- tools
- verification
notes:
- auto-active verification
- Boogie verifier
- Dafny verifier
- ghost code
- Z3 solver
- SMT solver
papers:
- leino:lpair:2010
---
[Dafny][leino:lpair:2010]
is both a language and a verification tool for creating verified
programs.
The language has features of object-oriented languages and functional
languages.
The verification support is based on contract-style verification.
This short, easy read seems to be the accompaniment for a tutorial
and discusses verification of six different functions that
demonstrates contracts and the specification notation,
loop invariants, immutable inductive datatypes, mutable datatypes,
use of pure functions in specifications, classes, ghost-fields,
invariants, and lemmas.
Proofs of lemmas are especially interesting because the lemmas
are just ghost methods and the body of those methods are
the proofs of the lemmas. e.g., to write an inductive proof,
one writes a recursive function using a case split to separate
the base case from the inductive step.
{% include links.html %}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using NuGetGallery;
namespace NuGet.Services
{
public class InMemoryCloudBlobContainer : ICloudBlobContainer
{
private readonly object _lock = new object();
public SortedDictionary<string, InMemoryCloudBlob> Blobs { get; } = new SortedDictionary<string, InMemoryCloudBlob>();
public Task CreateAsync(BlobContainerPermissions permissions)
{
throw new NotImplementedException();
}
public Task CreateIfNotExistAsync(BlobContainerPermissions permissions)
{
throw new NotImplementedException();
}
public Task<bool> DeleteIfExistsAsync()
{
throw new NotImplementedException();
}
public Task<bool> ExistsAsync(BlobRequestOptions options = null, OperationContext operationContext = null)
{
throw new NotImplementedException();
}
public ISimpleCloudBlob GetBlobReference(string blobAddressUri)
{
lock (_lock)
{
InMemoryCloudBlob blob;
if (!Blobs.TryGetValue(blobAddressUri, out blob))
{
blob = new InMemoryCloudBlob();
Blobs[blobAddressUri] = blob;
}
return blob;
}
}
public Task<ISimpleBlobResultSegment> ListBlobsSegmentedAsync(
string prefix,
bool useFlatBlobListing,
BlobListingDetails blobListingDetails,
int? maxResults,
BlobContinuationToken blobContinuationToken,
BlobRequestOptions options,
OperationContext operationContext,
CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public Task SetPermissionsAsync(BlobContainerPermissions permissions)
{
throw new NotImplementedException();
}
}
}
|
immutable PointwiseLayerState{P<:AbstractPointwise} <:
AbstractScatteredLayerState
blobs::Vector{Mocha.Blob}
layer::PointwiseLayer{P}
end
function PointwiseLayerState(
backend::Mocha.CPUBackend,
layer::PointwiseLayer,
inputs::Vector{Mocha.Blob})
blobs = Vector{Mocha.Blob}(length(inputs))
for idblob in eachindex(inputs)
blobs[idblob] = layer.ρ(inputs[idblob])
end
return PointwiseLayerState(blobs, layer)
end
function Mocha.setup(
backend::Mocha.CPUBackend,
layer::PointwiseLayer,
inputs::Vector{Mocha.Blob},
diffs::Vector{Mocha.Blob})
return PointwiseLayerState(backend, layer, inputs)
end
function forward(
backend::Mocha.CPUBackend,
layerstate::PointwiseLayerState,
inputs::Vector{Mocha.Blob})
for id in eachindex(inputs)
map!(layerstate.ρ, layerstate.blobs[id], inputs[id])
end
end
function forward!(
backend::Mocha.CPUBackend,
state::PointwiseLayerState,
ρ::AbstractPointwise,
inputs::Vector)
@inbounds for idblob in eachindex(inputs)
map!(ρ, state.blobs[idblob], inputs[idblob])
end
end
|
package ammonite.interp
import acyclic.file
import ammonite._
import ammonite.util._
import ammonite.util.Util.{windowsPlatform, newLine, normalizeNewlines}
import fastparse.all._
import scala.reflect.internal.Flags
import scala.tools.nsc.{Global => G}
import collection.mutable
/**
* Responsible for all scala-source-code-munging that happens within the
* Ammonite REPL.
*
* Performs several tasks:
*
* - Takes top-level Scala expressions and assigns them to `res{1, 2, 3, ...}`
* values so they can be accessed later in the REPL
*
* - Wraps the code snippet with an wrapper `object` since Scala doesn't allow
* top-level expressions
*
* - Mangles imports from our [[ammonite.util.ImportData]] data structure into a source
* String
*
* - Combines all of these into a complete compilation unit ready to feed into
* the Scala compiler
*/
trait Preprocessor{
def transform(stmts: Seq[String],
resultIndex: String,
leadingSpaces: String,
pkgName: Seq[Name],
indexedWrapperName: Name,
imports: Imports,
printerTemplate: String => String,
extraCode: String): Res[Preprocessor.Output]
}
object Preprocessor{
private case class Expanded(code: String, printer: Seq[String])
case class Output(code: String,
prefixCharLength: Int)
def errMsg(msg: String, code: String, expected: String, idx: Int): String = {
val locationString = {
val (first, last) = code.splitAt(idx)
val lastSnippet = last.split(newLine).headOption.getOrElse("")
val firstSnippet = first.reverse
.split(newLine.reverse)
.lift(0).getOrElse("").reverse
firstSnippet + lastSnippet + newLine + (" " * firstSnippet.length) + "^"
}
s"Syntax Error: $msg${newLine}$locationString"
}
/**
* Splits up a script file into its constituent blocks, each of which
* is a tuple of (leading-whitespace, statements). Leading whitespace
* is returned separately so we can later manipulate the statements e.g.
* by adding `val res2 = ` without the whitespace getting in the way
*/
def splitScript(rawCode: String): Res[Seq[(String, Seq[String])]] = {
Parsers.splitScript(rawCode) match {
case f: Parsed.Failure =>
Res.Failure(None, errMsg(f.msg, rawCode, f.extra.traced.expected, f.index))
case s: Parsed.Success[Seq[(String, Seq[String])]] =>
var offset = 0
val blocks = mutable.Buffer[(String, Seq[String])]()
// comment holds comments or empty lines above the code which is not caught along with code
for( (comment, code) <- s.value){
//ncomment has required number of newLines appended based on OS and offset
//since fastparse has hardcoded `\n`s, while parsing strings with `\r\n`s it
//gives out one extra `\r` after '@' i.e. block change
//which needs to be removed to get correct line number (It adds up one extra line)
//thats why the `comment.substring(1)` thing is necessary
val ncomment =
if(windowsPlatform && !blocks.isEmpty && !comment.isEmpty){
comment.substring(1) + newLine * offset
}else{
comment + newLine * offset
}
// 1 is added as Separator parser eats up the newLine char following @
offset = offset + (comment.split(newLine, -1).length - 1) +
code.map(_.split(newLine, -1).length - 1).sum + 1
blocks.append((ncomment, code))
}
Res.Success(blocks)
}
}
def apply(parse: => String => Either[String, Seq[G#Tree]]): Preprocessor = new Preprocessor{
def transform(stmts: Seq[String],
resultIndex: String,
leadingSpaces: String,
pkgName: Seq[Name],
indexedWrapperName: Name,
imports: Imports,
printerTemplate: String => String,
extraCode: String) = for{
Preprocessor.Expanded(code, printer) <- expandStatements(stmts, resultIndex)
(wrappedCode, importsLength) = wrapCode(
pkgName, indexedWrapperName, leadingSpaces + code,
printerTemplate(printer.mkString(", ")),
imports, extraCode
)
} yield Preprocessor.Output(wrappedCode, importsLength)
def Processor(cond: PartialFunction[(String, String, G#Tree), Preprocessor.Expanded]) = {
(code: String, name: String, tree: G#Tree) => cond.lift(name, code, tree)
}
def pprintSignature(ident: String, customMsg: Option[String]) = {
val customCode = customMsg.fold("_root_.scala.None")(x => s"""_root_.scala.Some("$x")""")
s"""
_root_.ammonite
.repl
.ReplBridge
.value
.Internal
.print($ident, $ident, "$ident", $customCode)
"""
}
def definedStr(definitionLabel: String, name: String) =
s"""
_root_.ammonite
.repl
.ReplBridge
.value
.Internal
.printDef("$definitionLabel", "$name")
"""
def pprint(ident: String) = pprintSignature(ident, None)
/**
* Processors for declarations which all have the same shape
*/
def DefProc(definitionLabel: String)(cond: PartialFunction[G#Tree, G#Name]) =
(code: String, name: String, tree: G#Tree) =>
cond.lift(tree).map{ name =>
Preprocessor.Expanded(
code,
Seq(definedStr(definitionLabel, Name.backtickWrap(name.decoded)))
)
}
val ObjectDef = DefProc("object"){case m: G#ModuleDef => m.name}
val ClassDef = DefProc("class"){ case m: G#ClassDef if !m.mods.isTrait => m.name }
val TraitDef = DefProc("trait"){ case m: G#ClassDef if m.mods.isTrait => m.name }
val DefDef = DefProc("function"){ case m: G#DefDef => m.name }
val TypeDef = DefProc("type"){ case m: G#TypeDef => m.name }
val PatVarDef = Processor { case (name, code, t: G#ValDef) =>
Expanded(
//Only wrap rhs in function if it is not a function
//Wrapping functions causes type inference errors.
code,
// Try to leave out all synthetics; we don't actually have proper
// synthetic flags right now, because we're dumb-parsing it and not putting
// it through a full compilation
if (t.name.decoded.contains("$")) Nil
else if (!t.mods.hasFlag(Flags.LAZY)) Seq(pprint(Name.backtickWrap(t.name.decoded)))
else Seq(s"""${pprintSignature(Name.backtickWrap(t.name.decoded), Some("<lazy>"))}""")
)
}
val Import = Processor{
case (name, code, tree: G#Import) =>
val Array(keyword, body) = code.split(" ", 2)
val tq = "\"\"\""
Expanded(code, Seq(
s"""
_root_.ammonite
.repl
.ReplBridge
.value
.Internal
.printImport($tq$body$tq)
"""
))
}
val Expr = Processor{
//Expressions are lifted to anon function applications so they will be JITed
case (name, code, tree) => Expanded(s"val $name = $code", Seq(pprint(name)))
}
val decls = Seq[(String, String, G#Tree) => Option[Preprocessor.Expanded]](
ObjectDef, ClassDef, TraitDef, DefDef, TypeDef, PatVarDef, Import, Expr
)
def expandStatements(stmts: Seq[String],
wrapperIndex: String): Res[Preprocessor.Expanded] = {
stmts match{
case Nil => Res.Skip
case postSplit =>
complete(stmts.mkString(""), wrapperIndex, postSplit)
}
}
def complete(code: String, resultIndex: String, postSplit: Seq[String]) = {
val reParsed = postSplit.map(p => (parse(p), p))
val errors = reParsed.collect{case (Left(e), _) => e }
if (errors.length != 0) Res.Failure(None, errors.mkString(newLine))
else {
val allDecls = for {
((Right(trees), code), i) <- reParsed.zipWithIndex if (trees.nonEmpty)
} yield {
// Suffix the name of the result variable with the index of
// the tree if there is more than one statement in this command
val suffix = if (reParsed.length > 1) "_" + i else ""
def handleTree(t: G#Tree) = {
decls.iterator.flatMap(_.apply(code, "res" + resultIndex + suffix, t)).next()
}
trees match {
case Seq(tree) => handleTree(tree)
// This handles the multi-import case `import a.b, c.d`
case trees if trees.forall(_.isInstanceOf[G#Import]) => handleTree(trees(0))
// AFAIK this can only happen for pattern-matching multi-assignment,
// which for some reason parse into a list of statements. In such a
// scenario, aggregate all their printers, but only output the code once
case trees =>
val printers = for {
tree <- trees
if tree.isInstanceOf[G#ValDef]
Preprocessor.Expanded(_, printers) = handleTree(tree)
printer <- printers
} yield printer
Preprocessor.Expanded(code, printers)
}
}
val Seq(first, rest@_*) = allDecls
val allDeclsWithComments = Expanded(first.code, first.printer) +: rest
Res(
allDeclsWithComments.reduceOption { (a, b) =>
Expanded(
// We do not need to separate the code with our own semi-colons
// or newlines, as each expanded code snippet itself comes with
// it's own trailing newline/semicolons as a result of the
// initial split
a.code + b.code,
a.printer ++ b.printer
)
},
"Don't know how to handle " + code
)
}
}
}
def importBlock(importData: Imports) = {
// Group the remaining imports into sliding groups according to their
// prefix, while still maintaining their ordering
val grouped = mutable.Buffer[mutable.Buffer[ImportData]]()
for(data <- importData.value){
if (grouped.isEmpty) grouped.append(mutable.Buffer(data))
else {
val last = grouped.last.last
// Start a new import if we're importing from somewhere else, or
// we're importing the same thing from the same place but aliasing
// it to a different name, since you can't import the same thing
// twice in a single import statement
val startNewImport =
last.prefix != data.prefix || grouped.last.exists(_.fromName == data.fromName)
if (startNewImport) grouped.append(mutable.Buffer(data))
else grouped.last.append(data)
}
}
// Stringify everything
val out = for(group <- grouped) yield {
val printedGroup = for(item <- group) yield{
if (item.fromName == item.toName) item.fromName.backticked
else s"${item.fromName.backticked} => ${item.toName.backticked}"
}
val pkgString = group.head.prefix.map(_.backticked).mkString(".")
"import " + pkgString + s".{$newLine " +
printedGroup.mkString(s",$newLine ") + s"$newLine}$newLine"
}
val res = out.mkString
res
}
def wrapCode(pkgName: Seq[Name],
indexedWrapperName: Name,
code: String,
printCode: String,
imports: Imports,
extraCode: String) = {
//we need to normalize topWrapper and bottomWrapper in order to ensure
//the snippets always use the platform-specific newLine
val topWrapper = normalizeNewlines(s"""
package ${pkgName.map(_.backticked).mkString(".")}
${importBlock(imports)}
object ${indexedWrapperName.backticked}{\n""")
val bottomWrapper = normalizeNewlines(s"""\ndef $$main() = { $printCode }
override def toString = "${indexedWrapperName.raw}"
$extraCode
}
""")
val importsLen = topWrapper.length
(topWrapper + code + bottomWrapper, importsLen)
}
}
|
use cagra::graph;
use std::fs;
fn main() -> Result<(), failure::Error> {
let mut g = graph!(f64, {
let x = 1.0;
let y = x * 2.0;
let z = square(y);
});
g.to_dot(&mut fs::File::create("init.dot")?)?;
let z = g.get_index("z");
g.eval_value(z)?;
g.to_dot(&mut fs::File::create("eval_value.dot")?)?;
g.eval_deriv(z)?;
g.to_dot(&mut fs::File::create("eval_deriv.dot")?)?;
Ok(())
}
|
using Base: min, max
export
Rectangle,
set!, intersect!, intersects,
bounds!, contains_point
# A two-dimensional axis-aligned rectangle.
#
# X-axis directed towards the right
#
# Y-Axis directed downward.
#
# left(X)/Top(Y)
# *------------. --> X
# | | |
# | | v Y
# | |
# | |
# .------------*
# Right(X)/Bottom(Y)
#
mutable struct Rectangle{T <: AbstractFloat}
# Top-left corner
min::Point{T}
# Bottom-right corner
max::Point{T}
width::T
height::T
function Rectangle{T}() where {T <: AbstractFloat}
new(Point{T}(), Point{T}(1.0, 1.0), 1.0, 1.0)
end
function Rectangle{T}(minx::T, miny::T, maxx::T, maxy::T) where {T <: AbstractFloat}
new(Point{T}(minx, miny), Point{T}(maxx, maxy), maxx - minx, maxy - miny)
end
function Rectangle{T}(min::Point{T}, max::Point{T}) where {T <: AbstractFloat}
new(min, max, max.x - min.x, max.y - min.y)
end
end
# setters/getters
function set!(rect::Rectangle{T}, minx::T, miny::T, maxx::T, maxy::T) where {T <: AbstractFloat}
set!(rect.min, minx, miny);
set!(rect.max, maxx, maxy);
rect.width = maxx - minx;
rect.height = maxy - miny;
end
# algorithms
function intersect!(intersect::Rectangle{T}, rectA::Rectangle{T}, rectB::Rectangle{T}) where {T <: AbstractFloat}
x0 = max(rectA.min.x, rectB.min.x);
x1 = min(rectA.max.x, rectB.max.x);
if x0 <= x1
y0 = max(rectA.min.y, rectB.min.y);
y1 = min(rectA.max.y, rectB.max.y);
if y0 <= y1
set!(intersect, x0, y0, x1, y1);
end
end
end
function intersects(rectA::Rectangle{T}, rectB::Rectangle{T}) where {T <: AbstractFloat}
rectA.min.x <= rectB.min.x + rectB.width &&
rectB.min.x <= rectA.min.x + rectA.width &&
rectA.max.y <= rectB.max.y + rectB.height &&
rectB.max.y <= rectA.max.y + rectA.height
end
# Returns a new rectangle which completely contains `rectA` and `rectB`.
function bounds!(bounds::Rectangle{T}, rectA::Rectangle{T}, rectB::Rectangle{T}) where {T <: AbstractFloat}
right = max(rectA.max.x, rectB.max.x);
bottom = max(rectA.max.y, rectB.max.y);
left = min(rectA.min.x, rectB.min.x);
top = min(rectA.min.y, rectB.min.y);
set!(bounds.min, left, top);
set!(bounds.max, right, bottom);
bounds.width = right - left;
bounds.height = bottom - top;
end
function contains_point(rect::Rectangle{T}, p::Point{T}) where {T <: AbstractFloat}
p.x >= rect.min.x &&
p.x <= rect.max.x &&
p.y >= rect.min.y &&
p.y <= rect.max.y
end |
while true
do
nvidia-smi -i 0 --query-gpu=timestamp,memory.total,memory.free,memory.used --format=csv | tail -n 1
sleep 1
done
|
import _ from 'lodash';
import { $try } from './utils';
export default class Bindings {
templates = {
// default: ({ field, props, keys, $try }) => ({
// [keys.id]: $try(props.id, field.id),
// }),
};
rewriters = {
default: {
id: 'id',
name: 'name',
type: 'type',
value: 'value',
checked: 'checked',
label: 'label',
placeholder: 'placeholder',
disabled: 'disabled',
onChange: 'onChange',
onBlur: 'onBlur',
onFocus: 'onFocus',
autoFocus: 'autoFocus',
},
};
load(field, name = 'default', props) {
if (_.has(this.rewriters, name)) {
const $bindings = {};
_.each(this.rewriters[name], ($v, $k) =>
_.merge($bindings, { [$v]: $try(props[$k], field[$k]) }));
return $bindings;
}
return this.templates[name]({
keys: this.rewriters[name],
$try,
field,
props,
});
}
register(bindings) {
_.each(bindings, (val, key) => {
if (_.isFunction(val)) _.merge(this.templates, { [key]: val });
if (_.isPlainObject(val)) _.merge(this.rewriters, { [key]: val });
});
return this;
}
}
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFanDraftTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('fan_drafts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->text('scoring');
$table->integer('creds');
$table->integer('all_creds');
$table->integer('team_lim');
$table->integer('all_team');
$table->integer('elite');
$table->integer('writeins');
$table->integer('writein_value');
$table->integer('open')->default('1');
$table->integer('complete')->default('0');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('fan_drafts');
}
}
|
# TAC Participation
## Description
This is the skill for participating in a TAC.
This skill is part of the Fetch.ai TAC demo. It searches for a TAC on the sOEF, and if found, participates in the TAC by communicating with the controller agent.
## Behaviours
* `tac_search`: searches for a TAC
* `transaction_processing`: processes transactions during the competition
## Handlers
* `tac`: handles `tac` messages by the controller for participating in the competition
* `oef`: handles `oef_search` messages to find and connect with a controller
## Links
* <a href="https://docs.fetch.ai/aea/tac-skills-contract/" target="_blank">TAC Demo</a>
|
#!/bin/bash
#####################
# Message Functions #
#####################
# Define colours
BLUE='\033[1;34m'
GREEN='\033[1;32m'
RED='\033[1;31m'
YELLOW='\e[1;93m'
BOLD='\033[1m'
NC='\033[0m' # No Color
error(){
printf "$RED"'Error'"$NC"' ('"$GREEN"'%s'"$NC"'): %s\n' "$(basename $0)" "$@"
}
notice(){
printf "$BLUE"'Notice'"$NC"' ('"$GREEN"'%s'"$NC"'): %s\n' "$(basename $0)" "$@"
}
warning(){
printf "$YELLOW"'Warning'"$NC"' ('"$GREEN"'%s'"$NC"'): %s\n' "$(basename $0)" "$@"
}
####################
# Script Functions #
####################
root_or_rerun(){
if [ "$EUID" -gt 0 ]; then
sudo "$0" $@
exit $?
fi
}
check_environment(){
# Arguments both as non-root in order to handle any input errors before we run root.
handle_arguments $@
if [ -z "$interface" ]; then
error "$(printf "No interface provided. Usage: $GREEN%s$NC interface" "$(basename $0)")"
exit 1
fi
if ! ip a s "$interface" 2> /dev/null >&2; then
error "$(printf "The $BOLD%s$NC interface was not found. Quitting...\n" "$interface")"
exit 2
fi
if nmcli device status 2> /dev/null | grep -v unmanaged | tail -n +2 | cut -d' ' -f1 | grep -q '^'$interface'$'; then
error "$(printf "The $BOLD%s$NC interface is still being managed by NetworkManager. Quitting...\n" "$interface")"
exit 3
fi
}
clean_pid_file(){
if [ -f "$pid_file" ]; then
notice "$(printf "Removing old PID file: $GREEN%s$NC" "$pid_file")"
rm "$pid_file"
return $?
fi
return 0
}
fix_directory(){
if [ -h "$0" ]; then
cd "$(dirname "$(readlink -f "$0")")"
else
cd "$(dirname "$0")"
fi
}
handle_arguments(){
for opt in $(getopt ":a" $@); do
case "$opt" in
"-a")
address_only=1
;;
*)
interface=$opt
;;
esac
done
unset opt
pid_file="/var/run/dhclient-$interface.pid"
}
run_dhclient(){
umask 077
local dhclient_script=./dhclient-script.sh
local short_options="subnet-mask, broadcast-address, host-name, interface-mtu"
if [ -z "$address_only" ]; then
notice "$(printf "Running ${BLUE}%s${NC} on ${BOLD}%s${NC}..." "dhclient" "$interface")"
if [ -f "$dhclient_script" ]; then
dhclient -sf "$dhclient_script" -pf "$pid_file" "$interface"
else
dhclient -pf "$pid_file" "$interface"
fi
else
notice "$(printf "Running ${BLUE}%s${NC} on ${BOLD}%s${NC}... (address-only)" "dhclient" "$interface")"
if [ -f "$dhclient_script" ]; then
dhclient -sf "$dhclient_script" -pf "$pid_file" "$interface" --request-options "$short_options"
else
dhclient -pf "$pid_file" "$interface" --request-options "$short_options"
fi
fi
return $?
}
kill_old_instance(){
if [ -f "$pid_file" ] && pgrep "dhclient" | grep -q "^$(cat "$pid_file")$"; then
# PID file exists, and a dhclient process is running at that PID from a previous run of this script..
notice "Sending a kill signal to previous dhclient process."
dhclient -x -pf "$pid_file"
fi
# Make sure that the PID file is gone, if it exists.
clean_pid_file
}
check_environment $@
root_or_rerun $@
fix_directory
kill_old_instance
run_dhclient
|
/*
Copyright 2021.
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 v1alpha1
import (
"reflect"
"testing"
"github.com/3scale/saas-operator/pkg/util"
"github.com/go-test/deep"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/utils/pointer"
)
func TestImageSpec_Default(t *testing.T) {
type fields struct {
Name *string
Tag *string
PullSecretName *string
PullPolicy *corev1.PullPolicy
}
type args struct {
def defaultImageSpec
}
tests := []struct {
name string
fields fields
args args
want *ImageSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultImageSpec{
Name: pointer.StringPtr("name"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
PullPolicy: func() *corev1.PullPolicy { p := corev1.PullIfNotPresent; return &p }(),
}},
want: &ImageSpec{
Name: pointer.StringPtr("name"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
PullPolicy: func() *corev1.PullPolicy { p := corev1.PullIfNotPresent; return &p }(),
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
Name: pointer.StringPtr("explicit"),
PullPolicy: func() *corev1.PullPolicy { p := corev1.PullAlways; return &p }(),
},
args: args{def: defaultImageSpec{
Name: pointer.StringPtr("name"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
PullPolicy: func() *corev1.PullPolicy { p := corev1.PullIfNotPresent; return &p }(),
}},
want: &ImageSpec{
Name: pointer.StringPtr("explicit"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
PullPolicy: func() *corev1.PullPolicy { p := corev1.PullAlways; return &p }(),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &ImageSpec{
Name: tt.fields.Name,
Tag: tt.fields.Tag,
PullSecretName: tt.fields.PullSecretName,
PullPolicy: tt.fields.PullPolicy,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("ImageSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestImageSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *ImageSpec
want bool
}{
{"Wants false if empty", &ImageSpec{}, false},
{"Wants false if nil", nil, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("ImageSpec.IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeImageSpec(t *testing.T) {
type args struct {
spec *ImageSpec
def defaultImageSpec
}
tests := []struct {
name string
args args
want *ImageSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultImageSpec{
Name: pointer.StringPtr("name"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
}},
want: &ImageSpec{
Name: pointer.StringPtr("name"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
},
},
{
name: "Initializes the struct with appropriate defaults if empty",
args: args{&ImageSpec{}, defaultImageSpec{
Name: pointer.StringPtr("name"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
}},
want: &ImageSpec{
Name: pointer.StringPtr("name"),
Tag: pointer.StringPtr("tag"),
PullSecretName: pointer.StringPtr("pullSecret"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeImageSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeImageSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestProbeSpec_Default(t *testing.T) {
type fields struct {
InitialDelaySeconds *int32
TimeoutSeconds *int32
PeriodSeconds *int32
SuccessThreshold *int32
FailureThreshold *int32
}
type args struct {
def defaultProbeSpec
}
tests := []struct {
name string
fields fields
args args
want *ProbeSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultProbeSpec{
InitialDelaySeconds: pointer.Int32Ptr(1),
TimeoutSeconds: pointer.Int32Ptr(2),
PeriodSeconds: pointer.Int32Ptr(3),
SuccessThreshold: pointer.Int32Ptr(4),
FailureThreshold: pointer.Int32Ptr(5),
}},
want: &ProbeSpec{
InitialDelaySeconds: pointer.Int32Ptr(1),
TimeoutSeconds: pointer.Int32Ptr(2),
PeriodSeconds: pointer.Int32Ptr(3),
SuccessThreshold: pointer.Int32Ptr(4),
FailureThreshold: pointer.Int32Ptr(5),
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
InitialDelaySeconds: pointer.Int32Ptr(9999),
},
args: args{def: defaultProbeSpec{
InitialDelaySeconds: pointer.Int32Ptr(1),
TimeoutSeconds: pointer.Int32Ptr(2),
PeriodSeconds: pointer.Int32Ptr(3),
SuccessThreshold: pointer.Int32Ptr(4),
FailureThreshold: pointer.Int32Ptr(5),
}},
want: &ProbeSpec{
InitialDelaySeconds: pointer.Int32Ptr(9999),
TimeoutSeconds: pointer.Int32Ptr(2),
PeriodSeconds: pointer.Int32Ptr(3),
SuccessThreshold: pointer.Int32Ptr(4),
FailureThreshold: pointer.Int32Ptr(5),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &ProbeSpec{
InitialDelaySeconds: tt.fields.InitialDelaySeconds,
TimeoutSeconds: tt.fields.TimeoutSeconds,
PeriodSeconds: tt.fields.PeriodSeconds,
SuccessThreshold: tt.fields.SuccessThreshold,
FailureThreshold: tt.fields.FailureThreshold,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("ProbeSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestProbeSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *ProbeSpec
want bool
}{
{"Wants true if empty", &ProbeSpec{}, true},
{"Wants false if nil", nil, false},
{"Wants false if other", &ProbeSpec{InitialDelaySeconds: pointer.Int32Ptr(1)}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("ProbeSpec.IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeProbeSpec(t *testing.T) {
type args struct {
spec *ProbeSpec
def defaultProbeSpec
}
tests := []struct {
name string
args args
want *ProbeSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultProbeSpec{
InitialDelaySeconds: pointer.Int32Ptr(1),
TimeoutSeconds: pointer.Int32Ptr(2),
PeriodSeconds: pointer.Int32Ptr(3),
SuccessThreshold: pointer.Int32Ptr(4),
FailureThreshold: pointer.Int32Ptr(5),
}},
want: &ProbeSpec{
InitialDelaySeconds: pointer.Int32Ptr(1),
TimeoutSeconds: pointer.Int32Ptr(2),
PeriodSeconds: pointer.Int32Ptr(3),
SuccessThreshold: pointer.Int32Ptr(4),
FailureThreshold: pointer.Int32Ptr(5),
},
},
{
name: "Deactivated",
args: args{&ProbeSpec{}, defaultProbeSpec{}},
want: &ProbeSpec{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeProbeSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeProbeSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestLoadBalancerSpec_Default(t *testing.T) {
type fields struct {
ProxyProtocol *bool
CrossZoneLoadBalancingEnabled *bool
ConnectionDrainingEnabled *bool
ConnectionDrainingTimeout *int32
ConnectionHealthcheckHealthyThreshold *int32
ConnectionHealthcheckUnhealthyThreshold *int32
ConnectionHealthcheckInterval *int32
ConnectionHealthcheckTimeout *int32
}
type args struct {
def defaultLoadBalancerSpec
}
tests := []struct {
name string
fields fields
args args
want *LoadBalancerSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
}},
want: &LoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
ProxyProtocol: pointer.BoolPtr(false),
},
args: args{def: defaultLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
}},
want: &LoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(false),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &LoadBalancerSpec{
ProxyProtocol: tt.fields.ProxyProtocol,
CrossZoneLoadBalancingEnabled: tt.fields.CrossZoneLoadBalancingEnabled,
ConnectionDrainingEnabled: tt.fields.ConnectionDrainingEnabled,
ConnectionDrainingTimeout: tt.fields.ConnectionDrainingTimeout,
HealthcheckHealthyThreshold: tt.fields.ConnectionHealthcheckHealthyThreshold,
HealthcheckUnhealthyThreshold: tt.fields.ConnectionHealthcheckUnhealthyThreshold,
HealthcheckInterval: tt.fields.ConnectionHealthcheckInterval,
HealthcheckTimeout: tt.fields.ConnectionHealthcheckTimeout,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("LoadBalancerSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestLoadBalancerSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *LoadBalancerSpec
want bool
}{
{"Wants false if empty", &LoadBalancerSpec{}, false},
{"Wants false if nil", nil, false},
{"Wants false if other", &LoadBalancerSpec{ProxyProtocol: pointer.BoolPtr(false)}, false}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("LoadBalancerSpec.IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeLoadBalancerSpec(t *testing.T) {
type args struct {
spec *LoadBalancerSpec
def defaultLoadBalancerSpec
}
tests := []struct {
name string
args args
want *LoadBalancerSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
}},
want: &LoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
},
},
{
name: "Initializes the struct with appropriate defaults if empty",
args: args{&LoadBalancerSpec{}, defaultLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
}},
want: &LoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
ConnectionDrainingEnabled: pointer.BoolPtr(true),
ConnectionDrainingTimeout: pointer.Int32Ptr(1),
HealthcheckHealthyThreshold: pointer.Int32Ptr(2),
HealthcheckUnhealthyThreshold: pointer.Int32Ptr(3),
HealthcheckInterval: pointer.Int32Ptr(4),
HealthcheckTimeout: pointer.Int32Ptr(5),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeLoadBalancerSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeLoadBalancerSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestNLBLoadBalancerSpec_Default(t *testing.T) {
type fields struct {
ProxyProtocol *bool
CrossZoneLoadBalancingEnabled *bool
}
type args struct {
def defaultNLBLoadBalancerSpec
}
tests := []struct {
name string
fields fields
args args
want *NLBLoadBalancerSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultNLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
}},
want: &NLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
ProxyProtocol: pointer.BoolPtr(false),
},
args: args{def: defaultNLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
}},
want: &NLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(false),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &NLBLoadBalancerSpec{
ProxyProtocol: tt.fields.ProxyProtocol,
CrossZoneLoadBalancingEnabled: tt.fields.CrossZoneLoadBalancingEnabled,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("NLBLoadBalancerSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestNLBLoadBalancerSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *NLBLoadBalancerSpec
want bool
}{
{"Wants false if empty", &NLBLoadBalancerSpec{}, false},
{"Wants false if nil", nil, false},
{"Wants false if other", &NLBLoadBalancerSpec{ProxyProtocol: pointer.BoolPtr(false)}, false}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("NLBLoadBalancerSpec.IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeNLBLoadBalancerSpec(t *testing.T) {
type args struct {
spec *NLBLoadBalancerSpec
def defaultNLBLoadBalancerSpec
}
tests := []struct {
name string
args args
want *NLBLoadBalancerSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultNLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
}},
want: &NLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
},
},
{
name: "Initializes the struct with appropriate defaults if empty",
args: args{&NLBLoadBalancerSpec{}, defaultNLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
}},
want: &NLBLoadBalancerSpec{
ProxyProtocol: pointer.BoolPtr(true),
CrossZoneLoadBalancingEnabled: pointer.BoolPtr(true),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeNLBLoadBalancerSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeNLBLoadBalancerSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestGrafanaDashboardSpec_Default(t *testing.T) {
type fields struct {
SelectorKey *string
SelectorValue *string
}
type args struct {
def defaultGrafanaDashboardSpec
}
tests := []struct {
name string
fields fields
args args
want *GrafanaDashboardSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultGrafanaDashboardSpec{
SelectorKey: pointer.StringPtr("key"),
SelectorValue: pointer.StringPtr("label"),
}},
want: &GrafanaDashboardSpec{
SelectorKey: pointer.StringPtr("key"),
SelectorValue: pointer.StringPtr("label"),
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
SelectorKey: pointer.StringPtr("xxxx"),
},
args: args{def: defaultGrafanaDashboardSpec{
SelectorKey: pointer.StringPtr("key"),
SelectorValue: pointer.StringPtr("label"),
}},
want: &GrafanaDashboardSpec{
SelectorKey: pointer.StringPtr("xxxx"),
SelectorValue: pointer.StringPtr("label"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &GrafanaDashboardSpec{
SelectorKey: tt.fields.SelectorKey,
SelectorValue: tt.fields.SelectorValue,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("GrafanaDashboardSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestGrafanaDashboardSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *GrafanaDashboardSpec
want bool
}{
{"Wants true if empty", &GrafanaDashboardSpec{}, true},
{"Wants false if nil", nil, false},
{"Wants false if other", &GrafanaDashboardSpec{SelectorKey: pointer.StringPtr("key")}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("GrafanaDashboardSpec_IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeGrafanaDashboardSpec(t *testing.T) {
type args struct {
spec *GrafanaDashboardSpec
def defaultGrafanaDashboardSpec
}
tests := []struct {
name string
args args
want *GrafanaDashboardSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultGrafanaDashboardSpec{
SelectorKey: pointer.StringPtr("key"),
SelectorValue: pointer.StringPtr("label"),
}},
want: &GrafanaDashboardSpec{
SelectorKey: pointer.StringPtr("key"),
SelectorValue: pointer.StringPtr("label"),
},
},
{
name: "Deactivated",
args: args{&GrafanaDashboardSpec{}, defaultGrafanaDashboardSpec{}},
want: &GrafanaDashboardSpec{},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeGrafanaDashboardSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeGrafanaDashboardSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestPodDisruptionBudgetSpec_Default(t *testing.T) {
type fields struct {
MinAvailable *intstr.IntOrString
MaxUnavailable *intstr.IntOrString
}
type args struct {
def defaultPodDisruptionBudgetSpec
}
tests := []struct {
name string
fields fields
args args
want *PodDisruptionBudgetSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultPodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.FromString("default")),
MaxUnavailable: nil,
}},
want: &PodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.FromString("default")),
MaxUnavailable: nil,
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
MinAvailable: util.IntStrPtr(intstr.FromString("explicit")),
},
args: args{def: defaultPodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.FromString("default")),
MaxUnavailable: nil,
}},
want: &PodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.FromString("explicit")),
MaxUnavailable: nil,
},
},
{
name: "Only one of MinAvailable or MaxUnavailable can be set",
fields: fields{
MinAvailable: util.IntStrPtr(intstr.FromString("explicit")),
},
args: args{def: defaultPodDisruptionBudgetSpec{
MinAvailable: nil,
MaxUnavailable: util.IntStrPtr(intstr.FromString("default")),
}},
want: &PodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.FromString("explicit")),
MaxUnavailable: nil,
},
},
{
name: "Only one of MinAvailable or MaxUnavailable can be set (II)",
fields: fields{},
args: args{def: defaultPodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.IntOrString{Type: intstr.String, StrVal: "defaultMin"}),
MaxUnavailable: util.IntStrPtr(intstr.IntOrString{Type: intstr.String, StrVal: "defaultMax"}),
}},
want: &PodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.IntOrString{Type: intstr.String, StrVal: "defaultMin"}),
MaxUnavailable: nil,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &PodDisruptionBudgetSpec{
MinAvailable: tt.fields.MinAvailable,
MaxUnavailable: tt.fields.MaxUnavailable,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("PodDisruptionBudgetSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestPodDisruptionBudgetSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *PodDisruptionBudgetSpec
want bool
}{
{"Wants true if empty", &PodDisruptionBudgetSpec{}, true},
{"Wants false if nil", nil, false},
{"Wants false if other", &PodDisruptionBudgetSpec{MinAvailable: util.IntStrPtr(intstr.FromInt(1))}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("PodDisruptionBudgetSpec.IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializePodDisruptionBudgetSpec(t *testing.T) {
type args struct {
spec *PodDisruptionBudgetSpec
def defaultPodDisruptionBudgetSpec
}
tests := []struct {
name string
args args
want *PodDisruptionBudgetSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultPodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.FromString("default")),
MaxUnavailable: nil,
}},
want: &PodDisruptionBudgetSpec{
MinAvailable: util.IntStrPtr(intstr.FromString("default")),
MaxUnavailable: nil,
},
},
{
name: "Deactivated",
args: args{&PodDisruptionBudgetSpec{}, defaultPodDisruptionBudgetSpec{}},
want: &PodDisruptionBudgetSpec{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializePodDisruptionBudgetSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializePodDisruptionBudgetSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestHorizontalPodAutoscalerSpec_Default(t *testing.T) {
type fields struct {
MinReplicas *int32
MaxReplicas *int32
ResourceName *string
ResourceUtilization *int32
}
type args struct {
def defaultHorizontalPodAutoscalerSpec
}
tests := []struct {
name string
fields fields
args args
want *HorizontalPodAutoscalerSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultHorizontalPodAutoscalerSpec{
MinReplicas: pointer.Int32Ptr(1),
MaxReplicas: pointer.Int32Ptr(2),
ResourceUtilization: pointer.Int32Ptr(3),
ResourceName: pointer.StringPtr("xxxx"),
}},
want: &HorizontalPodAutoscalerSpec{
MinReplicas: pointer.Int32Ptr(1),
MaxReplicas: pointer.Int32Ptr(2),
ResourceUtilization: pointer.Int32Ptr(3),
ResourceName: pointer.StringPtr("xxxx"),
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
MinReplicas: pointer.Int32Ptr(9999),
},
args: args{def: defaultHorizontalPodAutoscalerSpec{
MinReplicas: pointer.Int32Ptr(1),
MaxReplicas: pointer.Int32Ptr(2),
ResourceUtilization: pointer.Int32Ptr(3),
ResourceName: pointer.StringPtr("xxxx"),
}},
want: &HorizontalPodAutoscalerSpec{
MinReplicas: pointer.Int32Ptr(9999),
MaxReplicas: pointer.Int32Ptr(2),
ResourceUtilization: pointer.Int32Ptr(3),
ResourceName: pointer.StringPtr("xxxx"),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &HorizontalPodAutoscalerSpec{
MinReplicas: tt.fields.MinReplicas,
MaxReplicas: tt.fields.MaxReplicas,
ResourceName: tt.fields.ResourceName,
ResourceUtilization: tt.fields.ResourceUtilization,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("HorizontalPodAutoscalerSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestHorizontalPodAutoscalerSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *HorizontalPodAutoscalerSpec
want bool
}{
{"Wants true if empty", &HorizontalPodAutoscalerSpec{}, true},
{"Wants false if nil", nil, false},
{"Wants false if other", &HorizontalPodAutoscalerSpec{MinReplicas: pointer.Int32Ptr(1)}, false}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("HorizontalPodAutoscalerSpec.IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeHorizontalPodAutoscalerSpec(t *testing.T) {
type args struct {
spec *HorizontalPodAutoscalerSpec
def defaultHorizontalPodAutoscalerSpec
}
tests := []struct {
name string
args args
want *HorizontalPodAutoscalerSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultHorizontalPodAutoscalerSpec{
MinReplicas: pointer.Int32Ptr(1),
MaxReplicas: pointer.Int32Ptr(2),
ResourceUtilization: pointer.Int32Ptr(3),
ResourceName: pointer.StringPtr("xxxx"),
}},
want: &HorizontalPodAutoscalerSpec{
MinReplicas: pointer.Int32Ptr(1),
MaxReplicas: pointer.Int32Ptr(2),
ResourceUtilization: pointer.Int32Ptr(3),
ResourceName: pointer.StringPtr("xxxx"),
},
},
{
name: "Deactivated",
args: args{&HorizontalPodAutoscalerSpec{}, defaultHorizontalPodAutoscalerSpec{}},
want: &HorizontalPodAutoscalerSpec{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeHorizontalPodAutoscalerSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeHorizontalPodAutoscalerSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestResourceRequirementsSpec_Default(t *testing.T) {
type fields struct {
Limits corev1.ResourceList
Requests corev1.ResourceList
}
type args struct {
def defaultResourceRequirementsSpec
}
tests := []struct {
name string
fields fields
args args
want *ResourceRequirementsSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
}},
want: &ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("500m"),
corev1.ResourceMemory: resource.MustParse("500Mi"),
}},
args: args{def: defaultResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
}},
want: &ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("500m"),
corev1.ResourceMemory: resource.MustParse("500Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &ResourceRequirementsSpec{
Limits: tt.fields.Limits,
Requests: tt.fields.Requests,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("ResourceRequirementsSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestResourceRequirementsSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *ResourceRequirementsSpec
want bool
}{
{"Wants true if empty", &ResourceRequirementsSpec{}, true},
{"Wants false if nil", nil, false},
{"Wants false if other",
&ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("500m"),
corev1.ResourceMemory: resource.MustParse("500Mi"),
}},
false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("ResourceRequirementsSpec.IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeResourceRequirementsSpec(t *testing.T) {
type args struct {
spec *ResourceRequirementsSpec
def defaultResourceRequirementsSpec
}
tests := []struct {
name string
args args
want *ResourceRequirementsSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("500m"),
corev1.ResourceMemory: resource.MustParse("500Mi"),
},
}},
want: &ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("500m"),
corev1.ResourceMemory: resource.MustParse("500Mi"),
},
},
},
{
name: "Deactivated",
args: args{&ResourceRequirementsSpec{}, defaultResourceRequirementsSpec{}},
want: &ResourceRequirementsSpec{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeResourceRequirementsSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeResourceRequirementsSpec() = %v, want %v", got, tt.want)
}
})
}
}
func TestMarin3rSidecarSpec_Default(t *testing.T) {
type fields struct {
Ports []SidecarPort
Resources *ResourceRequirementsSpec
ExtraPodAnnotations map[string]string
}
type args struct {
def defaultMarin3rSidecarSpec
}
tests := []struct {
name string
fields fields
args args
want *Marin3rSidecarSpec
}{
{
name: "Sets defaults",
fields: fields{},
args: args{def: defaultMarin3rSidecarSpec{
Ports: []SidecarPort{
{
Name: "test",
Port: 9999,
},
},
Resources: defaultResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
},
}},
want: &Marin3rSidecarSpec{
Ports: []SidecarPort{
{
Name: "test",
Port: 9999,
},
},
Resources: &ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
},
},
},
{
name: "Combines explicitely set values with defaults",
fields: fields{
Resources: &ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("99m"),
corev1.ResourceMemory: resource.MustParse("99Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("99m"),
corev1.ResourceMemory: resource.MustParse("99Mi"),
},
},
},
args: args{def: defaultMarin3rSidecarSpec{
Ports: []SidecarPort{
{
Name: "test",
Port: 9999,
},
},
Resources: defaultResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
},
}},
want: &Marin3rSidecarSpec{
Ports: []SidecarPort{
{
Name: "test",
Port: 9999,
},
},
Resources: &ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("99m"),
corev1.ResourceMemory: resource.MustParse("99Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("99m"),
corev1.ResourceMemory: resource.MustParse("99Mi"),
},
},
},
},
{
name: "Default is deactivated",
fields: fields{},
args: args{def: defaultMarin3rSidecarSpec{}},
want: &Marin3rSidecarSpec{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := &Marin3rSidecarSpec{
Ports: tt.fields.Ports,
Resources: tt.fields.Resources,
ExtraPodAnnotations: tt.fields.ExtraPodAnnotations,
}
spec.Default(tt.args.def)
if !reflect.DeepEqual(spec, tt.want) {
t.Errorf("Marin3rSidecarSpec_Default() = %v, want %v", *spec, *tt.want)
}
})
}
}
func TestMarin3rSidecarSpec_IsDeactivated(t *testing.T) {
tests := []struct {
name string
spec *Marin3rSidecarSpec
want bool
}{
{"Wants true if empty", &Marin3rSidecarSpec{}, true},
{"Wants false if nil", nil, false},
{"Wants false if other", &Marin3rSidecarSpec{
Ports: []SidecarPort{{Port: 9999, Name: "test"}}}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.spec.IsDeactivated(); got != tt.want {
t.Errorf("Marin3rSidecarSpec_IsDeactivated() = %v, want %v", got, tt.want)
}
})
}
}
func TestInitializeMarin3rSidecarSpec(t *testing.T) {
type args struct {
spec *Marin3rSidecarSpec
def defaultMarin3rSidecarSpec
}
tests := []struct {
name string
args args
want *Marin3rSidecarSpec
}{
{
name: "Initializes the struct with appropriate defaults if nil",
args: args{nil, defaultMarin3rSidecarSpec{
Ports: []SidecarPort{
{
Name: "test",
Port: 9999,
},
},
Resources: defaultResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
},
}},
want: &Marin3rSidecarSpec{
Ports: []SidecarPort{
{
Name: "test",
Port: 9999,
},
},
Resources: &ResourceRequirementsSpec{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("200m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("100m"),
corev1.ResourceMemory: resource.MustParse("100Mi"),
},
},
},
},
{
name: "Deactivated",
args: args{&Marin3rSidecarSpec{}, defaultMarin3rSidecarSpec{}},
want: &Marin3rSidecarSpec{},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := InitializeMarin3rSidecarSpec(tt.args.spec, tt.args.def); !reflect.DeepEqual(got, tt.want) {
t.Errorf("InitializeMarin3rSidecarSpec() = %v, want %v", got, tt.want)
}
})
}
}
func Test_stringOrDefault(t *testing.T) {
type args struct {
value *string
defValue *string
}
tests := []struct {
name string
args args
want *string
}{
{
name: "Value explicitely set",
args: args{
value: pointer.StringPtr("value"),
defValue: pointer.StringPtr("default"),
},
want: pointer.StringPtr("value"),
},
{
name: "Value not set",
args: args{
value: nil,
defValue: pointer.StringPtr("default"),
},
want: pointer.StringPtr("default"),
},
{
name: "Nor value not default set",
args: args{
value: nil,
defValue: nil,
},
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := stringOrDefault(tt.args.value, tt.args.defValue)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("stringOrDefault() = %v, want %v", *got, *tt.want)
}
})
}
}
func Test_intOrDefault(t *testing.T) {
type args struct {
value *int32
defValue *int32
}
tests := []struct {
name string
args args
want *int32
}{
{
name: "Value explicitely set",
args: args{
value: pointer.Int32Ptr(100),
defValue: pointer.Int32Ptr(10),
},
want: pointer.Int32Ptr(100),
},
{
name: "Value not set",
args: args{
value: nil,
defValue: pointer.Int32Ptr(10),
},
want: pointer.Int32Ptr(10),
},
{
name: "Nor value not default set",
args: args{
value: nil,
defValue: nil,
},
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := intOrDefault(tt.args.value, tt.args.defValue)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("intOrDefault() = %v, want %v", *got, *tt.want)
}
})
}
}
func Test_boolOrDefault(t *testing.T) {
type args struct {
value *bool
defValue *bool
}
tests := []struct {
name string
args args
want *bool
}{
{
name: "Value explicitely set",
args: args{
value: pointer.BoolPtr(true),
defValue: pointer.BoolPtr(false),
},
want: pointer.BoolPtr(true),
},
{
name: "Value not set",
args: args{
value: nil,
defValue: pointer.BoolPtr(false),
},
want: pointer.BoolPtr(false),
},
{
name: "Nor value not default set",
args: args{
value: nil,
defValue: nil,
},
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := boolOrDefault(tt.args.value, tt.args.defValue)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("boolOrDefault() = %v, want %v", *got, *tt.want)
}
})
}
}
func TestCanary_CanarySpec(t *testing.T) {
type fields struct {
ImageName *string
ImageTag *string
Replicas *int32
Patches []string
}
type args struct {
spec interface{}
canarySpec interface{}
}
tests := []struct {
name string
fields fields
args args
want interface{}
wantErr bool
}{
{
name: "Returns a canary spec",
fields: fields{
Patches: []string{
`[{"op": "replace", "path": "/image/name", "value": "new"}]`,
},
},
args: args{
spec: &BackendSpec{
Image: &ImageSpec{
Name: pointer.StringPtr("old"),
Tag: pointer.StringPtr("tag"),
},
},
canarySpec: &BackendSpec{},
},
want: &BackendSpec{
Image: &ImageSpec{
Name: pointer.StringPtr("new"),
Tag: pointer.StringPtr("tag"),
},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &Canary{
ImageName: tt.fields.ImageName,
ImageTag: tt.fields.ImageTag,
Replicas: tt.fields.Replicas,
Patches: tt.fields.Patches,
}
err := c.PatchSpec(tt.args.spec, tt.args.canarySpec)
if (err != nil) != tt.wantErr {
t.Errorf("Canary.CanarySpec() error = %v, wantErr %v", err, tt.wantErr)
return
}
if diff := deep.Equal(tt.args.canarySpec, tt.want); len(diff) > 0 {
t.Errorf("Canary.CanarySpec() = diff %v", diff)
}
})
}
}
|
def calculate_sum_via_args(*args):
result = 0
for number in args:
result += number
return result
def add_two_numbers(first, second):
return first + second
def run_example():
numbers = [1, 2, 3, 4, 5, 6]
result = calculate_sum_via_args(numbers)
print(result)
result = calculate_sum_via_args(*numbers)
print(result)
two_numbers = [10, 30]
result = add_two_numbers(*two_numbers)
print(result)
combined_numbers = [*numbers, *two_numbers]
print(combined_numbers)
if __name__ == '__main__':
run_example() |
val subProject = if (file("debug.txt").exists())
"debugging_debug"
else
"debugging_release"
include(subProject)
|
package com.sweetrpg.catherder.api.impl;
import com.sweetrpg.catherder.api.registry.ICasingMaterial;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
public class MissingCasingMissing extends ICasingMaterial {
public static final ICasingMaterial NULL = new MissingCasingMissing();
private static final ResourceLocation MISSING_TEXTURE = new ResourceLocation("missingno");
@Override
public ResourceLocation getTexture() {
return MissingCasingMissing.MISSING_TEXTURE;
}
@Override
public Component getTooltip() {
return new TranslatableComponent("cattree.casing.missing", this.getRegistryName());
}
@Override
public Ingredient getIngredient() {
return Ingredient.EMPTY;
}
}
|
import os
import gc
import sys
print(sys.path)
import pickle
import warnings
import numpy as np
import pandas as pd
import datetime as dt
from diamond import helpers as helper
from diamond import utilities as util
from copy import deepcopy
from sklearn.preprocessing import StandardScaler
CONFIG = util.load_config()
class diamond(object):
"""
Class for handling relationships between normalized tables pulled from API
Standardizing adding starting pitchers, lineups (expected and/or actual)
Adding pitcher rolling stats
Adding batter rolling stats
"""
def __init__(self, seasonKey, min_date_gte=None, max_date_lte=None, upcoming_start_gte=None):
self.seasonKey = seasonKey
self.league = 'mlb'
self.min_date_gte = min_date_gte
self.max_date_lte = max_date_lte
self.upcoming_start_gte = upcoming_start_gte
# Pitching Stats attributes
self.pitching_roll_windows = [1, 3, 5, 10]
self.pitching_stats = ['fip', 'bb_per9', 'hr_fb_ratio', 'k_per9', 'gbpct']
self.pitching_roll_stats = [
'{}_roll{}'.format(s, w) for s in self.pitching_stats for
w in self.pitching_roll_windows
]
# Batting Stats Attributes
self.batting_roll_windows = [1, 3, 5, 10]
self.batting_stats = ['obp', 'slg', 'woba', 'iso']
self.batting_roll_stats = [
'{}_roll{}'.format(s, w) for s in self.batting_stats for
w in self.batting_roll_windows
]
self.batting_static_stats = ['atBats']
# Check args
assert not (
seasonKey and
(min_date_gte != None) and
(max_date_lte != None)
)
# Determine time period
if self.seasonKey:
self.min_date_gte = CONFIG.get(self.league)\
.get('seasons')\
.get(self.seasonKey)\
.get('seasonStart')
self.max_date_lte = CONFIG.get(self.league)\
.get('seasons')\
.get(self.seasonKey)\
.get('seasonEnd')
# Read in from daily game
path = CONFIG.get(self.league)\
.get('paths')\
.get('normalized').format(
f='daily_games'
)
paths = [
path+fname for fname in os.listdir(path) if (
(fname[:8] >= self.min_date_gte)
&
(fname[:8] <= self.max_date_lte)
)
]
self.summary = pd.concat(
objs=[pd.read_parquet(p) for p in paths],
axis=0
)
self.summary.drop_duplicates(subset=['gameId'], inplace=True)
self.summary.loc[:, 'gameStartDate'] = \
pd.to_datetime(self.summary['startTime'].str[:10])
def add_starting_pitchers(self, dispositions=['home', 'away']):
"""
ADDS DIMENSIONS TO SUMMARY
"""
helper.progress("Adding Starting Pitchers Attribute")
# Paths
atbats_path = CONFIG.get(self.league)\
.get('paths')\
.get('normalized').format(
f='game_atbats'
)
atbats_paths = [atbats_path+d+"/" for d in os.listdir(atbats_path) if (
(d >= self.min_date_gte)
&
(d <= self.max_date_lte)
)]
atbats_paths_full = []
for abp in atbats_paths:
atbats_paths_full.extend([abp+fname for fname in os.listdir(abp)])
# Get atbats
df_ab = pd.concat(
objs=[pd.read_parquet(p) for p in atbats_paths_full],
axis=0
)
df_ab.loc[:, 'gameStartTime'] = df_ab['gameStartTime'].str[:10]
df_ab.loc[:, 'gameStartTime'] = pd.to_datetime(df_ab['gameStartTime'])
# Save upcoming to use lineup approach with later
if self.upcoming_start_gte:
df_upc = df_ab.loc[df_ab['gameStartTime'] >= self.upcoming_start_gte, :]
df_ab = df_ab.loc[df_ab['gameStartTime'] < self.upcoming_start_gte, :]
else:
df_upc = df_ab.loc[df_ab['gameStartTime'] >= dt.datetime.now(), :]
df_ab = df_ab.loc[df_ab['gameStartTime'] < dt.datetime.now(), :]
# -------------------------
# -------------------------
# Filter to games in the past and use atbats to get starter (in case lineup wrong)
# Get Home Starters
df_top1 = df_ab.loc[(
(df_ab['inning']==1) &
(df_ab['inningHalf']=='TOP') &
(df_ab['outCount']==0)
), :]
df_home_starters = df_top1.loc[:, ['gameId', 'pitcherId']]\
.drop_duplicates(subset=['gameId'])
df_home_starters.rename(
columns={'pitcherId': 'homeStartingPitcherId'},
inplace=True
)
# Get Away Starters
df_bot1 = df_ab.loc[(
(df_ab['inning']==1) &
(df_ab['inningHalf']=='BOTTOM') &
(df_ab['outCount']==0)
), :]
df_away_starters = df_bot1.loc[:, ['gameId', 'pitcherId']]\
.drop_duplicates(subset=['gameId'])
df_away_starters.rename(
columns={'pitcherId': 'awayStartingPitcherId'},
inplace=True
)
# Assemble starters
df_hist_starters = pd.merge(
df_home_starters,
df_away_starters,
how='outer',
on=['gameId'],
validate='1:1'
)
# -------------------------
# -------------------------
# Filter to games in the current/future and use
# lineups to get starter (in case lineup wrong)
if not hasattr(self, 'lineups'):
self.add_lineups()
df_lup_home = self.lineups.loc[
self.lineups['batterDisposition'].str.lower() == 'home', :]
df_lup_away = self.lineups.loc[
self.lineups['batterDisposition'].str.lower() == 'away', :]
# Filter down
df_lup_home = df_lup_home.loc[(
(df_lup_home['playerPositionGeneral'] == 'P')
&
(df_lup_home['gameId'].isin(list(df_upc.gameId)))
), :]
df_lup_away = df_lup_away.loc[(
(df_lup_away['playerPositionGeneral'] == 'P')
&
(df_lup_away['gameId'].isin(list(df_upc.gameId)))
), :]
# Isolate
df_lup_home.rename(columns={'playerId': 'homeStartingPitcherId'}, inplace=True)
df_lup_home = df_lup_home.loc[:,
['gameId', 'homeStartingPitcherId']]\
.drop_duplicates(subset=['gameId'], inplace=False)
df_lup_away.rename(columns={'playerId': 'awayStartingPitcherId'}, inplace=True)
df_lup_away = df_lup_away.loc[:,
['gameId', 'awayStartingPitcherId']]\
.drop_duplicates(subset=['gameId'], inplace=False)
# Combine to one game per row
df_upc_starters = pd.merge(
df_lup_home,
df_lup_away,
how='left',
on=['gameId'],
validate='1:1'
)
# Concat hist and upc vertically to merge back to summary attrib
df_starters = pd.concat(
objs=[df_hist_starters, df_upc_starters],
axis=0
)
# Merge to summary attribute
self.summary = pd.merge(
self.summary,
df_starters,
how='left',
on=['gameId'],
validate='1:1'
)
def add_bullpen_summary(self, dispositions=['home', 'away']):
"""
ADDS ATTRIBUTE "bullpens_summary"
"""
helper.progress("Adding Bullpen Summary Attribute")
# Get atbats, filter to where not equal to starters
if not all(
s in self.summary.columns for s in \
['{}StartingPitcherId'.format(d) for d in dispositions]
):
self.add_starting_pitchers()
# Get atbats
# Paths
atbats_path = CONFIG.get(self.league)\
.get('paths')\
.get('normalized').format(
f='game_atbats'
)
atbats_paths = [atbats_path+d+"/" for d in os.listdir(atbats_path) if (
(d >= self.min_date_gte)
&
(d <= self.max_date_lte)
)]
atbats_paths_full = []
for abp in atbats_paths:
atbats_paths_full.extend([abp+fname for fname in os.listdir(abp)])
# Get atbats and sort by inning / outCount
df_ab = pd.concat(
objs=[pd.read_parquet(p) for p in atbats_paths_full],
axis=0
)
df_ab = df_ab.loc[:, ['gameId', 'gameStartTime', 'pitcherId', 'homeTeamId', 'awayTeamId',
'inning', 'inningHalf', 'outCount']]
# Select home, sort, dd, remove starter, and rerank
bullpen_summary = []
sides = {'TOP': 'home', 'BOTTOM': 'away'}
for half_, disp in sides.items():
# Set up starter map for later mask
startingPitcherMap = self.summary.set_index('gameId')\
['{}StartingPitcherId'.format(disp)].to_dict()
df_ab_h = df_ab.loc[df_ab['inningHalf']==half_, :]
# Sort
df_ab_h = df_ab_h.sort_values(
by=['gameId', 'gameStartTime', 'inning', 'outCount'],
ascending=True,
inplace=False
)
# Drop labels
df_ab_h = df_ab_h.drop(labels=['inning', 'outCount'], axis=1, inplace=False)
# Remove pitcher who was already identified as starter
# (self.summary['homeStartingPitcherId'].iloc[0]?
df_ab_h.loc[:, '{}StartingPitcherId'.format(disp)] = \
df_ab_h['gameId'].map(startingPitcherMap)
df_ab_h = df_ab_h.loc[
df_ab_h['pitcherId'] != df_ab_h['{}StartingPitcherId'.format(disp)], :]
# Handle ordering
df_ab_h['pitcherAppearOrder'] = df_ab_h\
.groupby(by=['gameId'])['pitcherId'].rank(method='first')
df_ab_h = df_ab_h.groupby(
by=['gameId', 'gameStartTime', '{}TeamId'.format(disp), 'pitcherId'],
as_index=False).agg({'pitcherAppearOrder': 'min'})
df_ab_h['pitcherAppearOrder'] = df_ab_h\
.groupby(by=['gameId'])['pitcherId'].rank(method='first')
df_ab_h['pitcherAppearOrderMax'] = df_ab_h\
.groupby('gameId')['pitcherAppearOrder'].transform('max')
# Label middle pitchers relief role and last pitcher closer` role
msk = (df_ab_h['pitcherAppearOrder']==df_ab_h['pitcherAppearOrderMax'])
df_ab_h.loc[msk, 'pitcherRoleType'] = 'closer'
df_ab_h.loc[~msk, 'pitcherRoleType'] = 'reliever'
# Subset (TODO add first inning appeared)
df_ab_h = df_ab_h.loc[:, ['gameId', 'gameStartTime', 'pitcherId', 'pitcherRoleType',
'{}TeamId'.format(disp), 'pitcherAppearOrder']]
df_ab_h.rename(columns={'{}TeamId'.format(disp): 'teamId'}, inplace=True)
df_ab_h['bullpenDisposition'] = disp
bullpen_summary.append(df_ab_h)
bullpen_summary = pd.concat(objs=bullpen_summary, axis=0)
self.bullpen_reliever_summary = bullpen_summary.loc[
bullpen_summary['pitcherRoleType'] == 'reliever', :]
self.bullpen_closer_summary = bullpen_summary.loc[
bullpen_summary['pitcherRoleType'] == 'closer', :]
def add_pitcher_rolling_stats(
self,
dispositions=['home', 'away'],
pitcher_roll_types=['starter', 'reliever', 'closer'],
shift_back=True
):
"""
"""
helper.progress("Adding Pitcher Rolling Stats to pitching-related attributes")
# Path
ptch_roll_path = CONFIG.get(self.league)\
.get('paths')\
.get('rolling_stats').format('pitching')+"player/"
# Read in
ptch_roll = pd.concat(
objs=[pd.read_parquet(ptch_roll_path+fname) for fname in
os.listdir(ptch_roll_path) if
((fname.replace(".parquet", "") >= self.min_date_gte)
&
(fname.replace(".parquet", "") <= self.max_date_lte))],
axis=0
)
# Create rolling metrics
cols = ['gameId', 'gameStartDate', 'playerId'] +\
self.pitching_roll_stats
# Subset
ptch_roll = ptch_roll.loc[:,
['gameId', 'gameStartDate', 'playerId'] +
self.pitching_roll_stats
]
# Sort
ptch_roll.sort_values(by=['gameStartDate'], ascending=True, inplace=True)
# Shift back if interested in rolling stats leading up to game
if shift_back:
for col in self.pitching_roll_stats:
msk = (ptch_roll['playerId'].shift(1)==ptch_roll['playerId'])
ptch_roll.loc[msk, col] = ptch_roll[col].shift(1)
# Handle Infs
for col in self.pitching_roll_stats:
ptch_roll = ptch_roll.loc[~ptch_roll[col].isin([np.inf, -np.inf]), :]
# Check if starter / all designation
if 'starter' in pitcher_roll_types:
print(" Adding stats for starters")
# Check that summary attribute has starting pitchers
if not any('StartingPitcherId' in col for col in
self.summary.columns):
self.add_starting_pitchers(dispositions=dispositions)
# Merge back to starters (one at a time)
pitcher_cols = ['{}StartingPitcherId'.format(d) for
d in dispositions]
# Prep self.starting_pitcher_stats
p = []
for pc in pitcher_cols:
df = self.summary.loc[:, ['gameId', pc]]
df = df.loc[df[pc].notnull(), :]
df.rename(columns={pc: 'pitcherId'}, inplace=True)
df.loc[:, 'pitcherDisposition'] = pc[:4].lower()
p.append(df)
# concatenate to form attribute
self.starting_pitcher_summary = \
pd.concat(objs=p, axis=0)
self.starting_pitcher_summary = pd.merge(
self.starting_pitcher_summary,
ptch_roll,
how='left',
left_on=['gameId', 'pitcherId'],
right_on=['gameId', 'playerId'],
validate='1:1'
)
self.starting_pitcher_summary.drop(
labels=['playerId'],
axis=1,
inplace=True
)
# Check if reliever / all designation
if 'reliever' in pitcher_roll_types:
print(" Adding stats for relievers")
# Check attribute (try / except cheaper but less readable)
if not hasattr(self, 'bullpen_reliever_summary'):
self.add_bullpen_summary(dispositions=dispositions)
# Merge back to relievers in bullpen summary
msk = (self.bullpen_reliever_summary['pitcherRoleType'].str.lower() == 'reliever')
bullpen = self.bullpen_reliever_summary.loc[msk, :]
if bullpen.shape[0] == 0:
warnings.warn(" No relief pitchers found in bullpen_summary attribute")
if not all(d in dispositions for d in ['home', 'away']):
assert len(dispositions) == 1 and dispositions[0] in ['home', 'away']
bullpen_reconstruct = []
for disp in dispositions:
bullpen_disp = bullpen.loc[bullpen['bullpenDisposition'] == disp, :]
bullpen_disp = bullpen_disp.loc[:, ['gameId', 'pitcherId']]
bullpen_disp = pd.merge(
bullpen_disp,
ptch_roll,
how='left',
left_on=['gameId', 'pitcherId'],
right_on=['gameId', 'playerId'],
validate='1:1'
)
bullpen_disp.drop(labels=['playerId'], axis=1, inplace=True)
bullpen_reconstruct.append(bullpen_disp)
bullpen_reconstruct = pd.concat(objs=bullpen_reconstruct, axis=0)
# Add back to summary / detail
self.bullpen_reliever_summary = pd.merge(
self.bullpen_reliever_summary,
bullpen_reconstruct,
how='left',
on=['gameId', 'pitcherId'],
validate='1:1'
)
# Set
# TODO Standard Deviation might not be best here
aggDict = {stat: ['mean', 'max', 'min'] for stat in [
x for x in self.bullpen_reliever_summary.columns if
any(y in x for y in self.pitching_stats)
]}
df = self.bullpen_reliever_summary.groupby(
by=['gameId', 'gameStartTime', 'teamId', 'bullpenDisposition'],
as_index=False
).agg(aggDict)
df.columns = [
x[0] if x[1] == '' else x[0]+"~"+x[1] for x in
df.columns
]
self.bullpen_reliever_summary = df
# TODO FIX CLOSER MERGE _x _y
if 'closer' in pitcher_roll_types:
print(" Adding stats for closers")
# Check if closer / all designation
if not hasattr(self, 'bullpen_closer_summary'):
self.add_bullpen_summary(dispositions=dispositions)
# Merge back to closers in bullpen summary
msk = (self.bullpen_closer_summary['pitcherRoleType'].str.lower() == 'closer')
bullpen = self.bullpen_closer_summary.loc[msk, :]
if bullpen.shape[0] == 0:
warnings.warn(" No closing pitchers found in bullpen_summary attribute")
if not all(d in dispositions for d in ['home', 'away']):
assert len(dispositions) == 1 and dispositions[0] in ['home', 'away']
bullpen_reconstruct = []
for disp in dispositions:
bullpen_disp = bullpen.loc[bullpen['bullpenDisposition'] == disp, :]
bullpen_disp = bullpen_disp.loc[:, ['gameId', 'pitcherId']]
bullpen_disp = pd.merge(
bullpen_disp,
ptch_roll,
how='left',
left_on=['gameId', 'pitcherId'],
right_on=['gameId', 'playerId'],
validate='1:1'
)
bullpen_disp.drop(labels=['playerId'], axis=1, inplace=True)
bullpen_reconstruct.append(bullpen_disp)
bullpen_reconstruct = pd.concat(objs=bullpen_reconstruct, axis=0)
# Add back to summary / detail
self.bullpen_closer_summary = pd.merge(
self.bullpen_closer_summary,
bullpen_reconstruct,
how='left',
on=['gameId', 'pitcherId'],
validate='1:1'
)
# Set
# TODO Standard Deviation might not be best here
aggDict = {stat: ['mean', 'max', 'min'] for stat in [
x for x in self.bullpen_closer_summary.columns if
any(y in x for y in self.pitching_stats)
]}
df = self.bullpen_closer_summary.groupby(
by=['gameId', 'gameStartTime', 'teamId', 'bullpenDisposition'],
as_index=False
).agg(aggDict)
df.columns = [
x[0] if x[1] == '' else x[0]+"~"+x[1] for x in
df.columns
]
self.bullpen_closer_summary = df
def add_lineups(self, status='auto'):
"""
status: 'auto' - expected/actual
"""
helper.progress("Adding Lineups Attribute")
# Add lineups
# add expected for upcoming game
# add actual for completed games
lineups_path = CONFIG.get(self.league)\
.get('paths')\
.get('normalized')\
.format(f='game_lineup')
df_lineup = pd.concat(
objs=[pd.read_parquet(lineups_path+fname) for fname in os.listdir(lineups_path) if
((fname.replace(".parquet", "") >= self.min_date_gte)
&
(fname.replace(".parquet", "") <= self.max_date_lte))],
axis=0
)
# Actual
actual = df_lineup.loc[df_lineup['positionStatus'] == 'actual', :]
actual = actual.drop_duplicates(subset=['gameId', 'playerId'])
actual_ids = list(set(actual.gameId))
# Expected
exp = df_lineup.loc[(
(df_lineup['positionStatus'] == 'expected')
&
~(df_lineup['gameId'].isin(actual_ids))
), :]
exp = exp.drop_duplicates(subset=['gameId', 'playerId'])
# Concat
actual = pd.concat(objs=[actual, exp], axis=0)
actual = actual.rename(columns={'teamDisposition': 'batterDisposition'})
self.lineups = actual
def add_batter_rolling_stats(self, shift_back=True):
"""
Adds:
attrib self.batter_summary
"""
# Path
bat_roll_path = CONFIG.get(self.league)\
.get('paths')\
.get('rolling_stats')\
.format('batting')+"player/"
# Read in
bat_roll = pd.concat(
objs=[pd.read_parquet(bat_roll_path+fname) for fname in
os.listdir(bat_roll_path) if
((fname.replace(".parquet", "") >= self.min_date_gte)
&
(fname.replace(".parquet", "") <= self.max_date_lte))],
axis=0
)
# Create rolling metrics
cols = ['gameId', 'gameStartDate', 'playerId'] +\
self.batting_roll_stats
# Subset
bat_roll = bat_roll.loc[:,
['gameId', 'gameStartDate', 'playerId'] +
self.batting_roll_stats +
self.batting_static_stats
]
# Sort
bat_roll.sort_values(by=['gameStartDate'], ascending=True, inplace=True)
# Shift back if interested in rolling stats leading up to game
if shift_back:
for col in self.batting_roll_stats:
msk = (bat_roll['playerId'].shift(1)==bat_roll['playerId'])
bat_roll.loc[msk, col] = bat_roll[col].shift(1)
# Handle Infs
for col in self.batting_roll_stats:
bat_roll = bat_roll.loc[~bat_roll[col].isin([np.inf, -np.inf]), :]
# Merge batting stats rolling (with shift) on to batters from lineup
# Check that summary attribute has starting pitchers
if not hasattr(self, 'lineups'):
self.add_lineups()
# Prep self.batter_summary
self.batter_summary = pd.merge(
self.lineups[['gameId', 'playerId']],
bat_roll,
how='left',
on=['gameId', 'playerId'],
validate='1:1'
)
def fit_batter_cluster_model(self, k='best'):
"""
Add best cluster model as record in config to reference later
Batter cluster model contains rolling stats and rolling stat diffs
- exact features are saved as list in CSV
- pickled model is saved as object in same dir as CSV
- current "best" model will be saved in config
- model filenames formatted {batter}_k{6}.pkl
"""
# Check attribute
if not hasattr(self, 'batter_summary'):
self.add_batter_rolling_stats()
# Reference model saved in config and read in
if k == 'best':
path = CONFIG.get(self.league)\
.get('paths')\
.get('cluster_models')
model_fname = CONFIG.get(self.league)\
.get('models')\
.get('cluster')\
.get('batter')\
.get('model_filename')
feat_fname = CONFIG.get(self.league)\
.get('models')\
.get('cluster')\
.get('batter')\
.get('model_features')
else:
path = kwargs.get('path')
model_fname = kwargs.get('model_fname')
feat_fname = kwargs.get('feat_fname')
clstr = pickle.load(open(path + model_fname, 'rb'))
feats = pd.read_csv(path + feat_fname, dtype=str)
feats = list(set(feats.features))
# Get diff metrics involved with particular model
diffs = [x for x in feats if 'diff' in x]
warnings.warn("'_' in metric not currently handled for batting")
# Calculate diffs (order reversed)
for diff in diffs:
# TODO - Issue if "_" in metric
mtr = diff.split("_")[0]
from_ = diff.split("_")[2] #3
to_ = diff.split("_")[1] # 10
new = '{}_{}_{}_diff'.format(mtr, to_, from_)
self.batter_summary.loc[:, new] = (
self.batter_summary.loc[:, '{}_roll{}'.format(mtr, from_)] -
self.batter_summary.loc[:, '{}_roll{}'.format(mtr, to_)]
)
assert all(f in self.batter_summary for f in feats)
# Subset out summary to dropna and avoid error on fit
sub = self.batter_summary.loc[:, ['gameId', 'playerId'] + feats].dropna()
for col in feats:
med = np.median(sub.loc[~sub[col].isin([np.inf, -np.inf]), :][col])
sub.loc[sub[col].isin([np.inf, -np.inf]), col] = med
# Fit cluster model
scaler = StandardScaler()
df_sc = scaler.fit_transform(sub[feats])
clstr.fit(df_sc)
sub.loc[:, 'batterIdClusterName'] = clstr.labels_
sub = sub.loc[:, ['gameId', 'playerId', 'batterIdClusterName']]
# Merge back to attribute
self.batter_summary = pd.merge(
self.batter_summary,
sub[['gameId', 'playerId', 'batterIdClusterName']],
how='left',
on=['gameId', 'playerId'],
validate='1:1'
)
def fit_starting_pitcher_cluster_model(self, k='best'):
"""
"""
# Check attribute
if not hasattr(self, 'starting_pitcher_summary'):
self.add_starting_pitchers()
self.add_pitcher_rolling_stats()
if k == 'best':
path = CONFIG.get(self.league)\
.get('paths')\
.get('cluster_models')
model_fname = CONFIG.get(self.league)\
.get('models')\
.get('cluster')\
.get('starting_pitcher')\
.get('model_filename')
feat_fname = CONFIG.get(self.league)\
.get('models')\
.get('cluster')\
.get('starting_pitcher')\
.get('model_features')
else:
path = kwargs.get('path')
model_fname = kwargs.get('model_fname')
feat_fname = kwargs.get('feat_fname')
clstr = pickle.load(open(path + model_fname, 'rb'))
feats = pd.read_csv(path + feat_fname, dtype=str)
feats = list(set(feats.features))
# Get diff metrics involved with particular model
diffs = [x for x in feats if 'diff' in x]
# Calculate diffs (order NOT reversed)
for diff in diffs:
if len(diff.split("_")) > 3:
mtr = "_".join(diff.split("_")[:-3])
from_ = "_".join(diff.split("_")[-3])
to_ = "_".join(diff.split("_")[-2])
else:
mtr = diff.split("_")[0]
from_ = diff.split("_")[1]
to_ = diff.split("_")[2]
new = '{}_{}_{}_diff'.format(mtr, from_, to_)
self.starting_pitcher_summary.loc[:, new] = (
self.starting_pitcher_summary.loc[:, '{}_roll{}'.format(mtr, from_)] -
self.starting_pitcher_summary.loc[:, '{}_roll{}'.format(mtr, to_)]
)
assert all(f in self.starting_pitcher_summary.columns for f in feats)
# Handle infinites (will error in scaler fit to follow)
sub = self.starting_pitcher_summary.loc[:, ['gameId', 'pitcherId'] + feats]\
.dropna()
for col in feats:
med = np.median(sub.loc[~sub[col].isin([np.inf, -np.inf]), :][col])
sub.loc[sub[col].isin([np.inf, -np.inf]), col] = med
# Subset out summary to dropna and avoid error on fit
sub = self.starting_pitcher_summary.loc[:,
['gameId', 'pitcherId'] + feats
].dropna()
# Fit cluster model
scaler = StandardScaler()
df_sc = scaler.fit_transform(sub[feats])
clstr.fit(df_sc)
sub.loc[:, 'startingPitcherClusterName'] = clstr.labels_
sub = sub.loc[:, ['gameId', 'pitcherId', 'startingPitcherClusterName']]
# Merge back to attribute
self.starting_pitcher_summary = pd.merge(
self.starting_pitcher_summary,
sub,
how='left',
left_on=['gameId', 'pitcherId'],
right_on=['gameId', 'pitcherId'],
validate='1:1'
)
def fit_bullpen_cluster_model(self, k='best', roletypes=['reliever', 'closer']):
"""
Cluster applied to bullpen as collective group (means of player metrics)
Does not fit diffs, just recent rolling since multiple pitchers being aggregated
Recent (3, 5) metrics used
"""
for roletype in roletypes:
# Check attribute
if not hasattr(self, 'bullpen_{}_summary'.format(roletype)):
self.add_bullpen_summary()
self.add_pitcher_rolling_stats()
if k == 'best':
path = CONFIG.get(self.league)\
.get('paths')\
.get('cluster_models')
model_fname = CONFIG.get(self.league)\
.get('models')\
.get('cluster')\
.get('bullpen')\
.get('model_filename')
feat_fname = CONFIG.get(self.league)\
.get('models')\
.get('cluster')\
.get('bullpen')\
.get('model_features')
else:
path = kwargs.get('path')
model_fname = kwargs.get('model_fname')
feat_fname = kwargs.get('feat_fname')
clstr = pickle.load(open(path + model_fname, 'rb'))
feats = pd.read_csv(path + feat_fname, dtype=str)
feats = list(set(feats.features))
if roletype == 'reliever':
assert all(f in self.bullpen_reliever_summary.columns for f in feats)
sub = self.bullpen_reliever_summary.loc[:,
['gameId', 'teamId'] + feats
]
for col in feats:
med = np.nanmedian(sub.loc[~sub[col].isin([np.inf, -np.inf]), :][col])
sub.loc[sub[col].isin([np.inf, -np.inf]), col] = med
sub.loc[sub[col].isnull(), col] = med
# Fit cluster model
scaler = StandardScaler()
scaler.fit(sub[feats])
df_sc = scaler.transform(sub[feats])
clstr.fit(df_sc)
sub.loc[:, 'teamBullpenClusterName'] = clstr.labels_
sub = sub.loc[:, ['gameId', 'teamId', 'teamBullpenClusterName']]
# Subset of summary
smry = self.bullpen_reliever_summary.drop_duplicates(subset=['gameId', 'teamId'])
self.bullpen_reliever_summary = pd.merge(
smry,
sub,
how='left',
on=['gameId', 'teamId'],
validate='1:1'
)
if roletype == 'closer':
assert all(f in self.bullpen_closer_summary.columns for f in feats)
sub = self.bullpen_closer_summary.loc[:,
['gameId', 'teamId'] + feats
].dropna()
for col in feats:
med = np.median(sub.loc[~sub[col].isin([np.inf, -np.inf]), :][col])
sub.loc[sub[col].isin([np.inf, -np.inf]), col] = med
# Fit cluster model
scaler = StandardScaler()
df_sc = scaler.fit_transform(sub[feats])
clstr.fit(df_sc)
sub.loc[:, 'teamBullpenClusterName'] = clstr.labels_
sub = sub.loc[:, ['gameId', 'teamId', 'teamBullpenClusterName']]
self.bullpen_closer_summary = pd.merge(
self.bullpen_closer_summary,
sub,
how='left',
on=['gameId', 'teamId'],
validate='1:1'
)
# TODO
# TODO
# TODO THE BULLPEN SUMMARY IS PLAYER LEVEL - THE CLUSTER IS TEAM LEVEL
#self.bullpen_summary = pd.merge(
# self.bullpen_summary,
# sub,
# how='left',
# on=['gameId', 'teamId'],
# validate='1:1'
#)
def add_elo_scores(self):
"""
"""
#
print()
def add_wager_table(self, seasonKey=None):
"""
"""
#
print()
|
using System.Collections.Generic;
using MithrilShards.Core.Shards;
using MithrilShards.Example.Network.Client;
namespace MithrilShards.Example
{
public class ExampleSettings : MithrilShardSettingsBase
{
const long DEFAULT_MAX_TIME_ADJUSTMENT = 70 * 60;
public long MaxTimeAdjustment { get; set; } = DEFAULT_MAX_TIME_ADJUSTMENT;
public List<ExampleClientPeerBinding> Connections { get; } = new List<ExampleClientPeerBinding>();
}
} |
(function() {
"use strict";
const coll = db.find5;
coll.drop();
assert.writeOK(coll.insert({a: 1}));
assert.writeOK(coll.insert({b: 5}));
assert.eq(2, coll.find({}, {b: 1}).count(), "A");
function getIds(projection) {
return coll.find({}, projection).map(doc => doc._id).sort();
}
assert.eq(Array.tojson(getIds(null)), Array.tojson(getIds({})), "B1 ");
assert.eq(Array.tojson(getIds(null)), Array.tojson(getIds({a: 1})), "B2 ");
assert.eq(Array.tojson(getIds(null)), Array.tojson(getIds({b: 1})), "B3 ");
assert.eq(Array.tojson(getIds(null)), Array.tojson(getIds({c: 1})), "B4 ");
let results = coll.find({}, {a: 1}).sort({a: -1});
let first = results[0];
assert.eq(1, first.a, "C1");
assert.isnull(first.b, "C2");
let second = results[1];
assert.isnull(second.a, "C3");
assert.isnull(second.b, "C4");
results = coll.find({}, {b: 1}).sort({a: -1});
first = results[0];
assert.isnull(first.a, "C5");
assert.isnull(first.b, "C6");
second = results[1];
assert.isnull(second.a, "C7");
assert.eq(5, second.b, "C8");
assert(coll.drop());
assert.writeOK(coll.insert({a: 1, b: {c: 2, d: 3, e: 4}}));
assert.eq(2, coll.findOne({}, {"b.c": 1}).b.c, "D");
const o = coll.findOne({}, {"b.c": 1, "b.d": 1});
assert(o.b.c, "E 1");
assert(o.b.d, "E 2");
assert(!o.b.e, "E 3");
assert(!coll.findOne({}, {"b.c": 1}).b.d, "F");
assert(coll.drop());
assert.writeOK(coll.insert({a: {b: {c: 1}}}));
assert.eq(1, coll.findOne({}, {"a.b.c": 1}).a.b.c, "G");
}());
|
# frozen_string_literal: true
require_relative '../../test_helper'
class TestFakerKpop < Test::Unit::TestCase
def setup
@tester = Faker::Kpop
end
def test_i_groups
assert @tester.i_groups.match(/\w+/)
end
def test_ii_groups
assert @tester.ii_groups.match(/\w+/)
end
def test_iii_groups
assert @tester.iii_groups.match(/\w+/)
end
def test_girl_groups
assert @tester.girl_groups.match(/\w+/)
end
def test_boy_bands
assert @tester.boy_bands.match(/\w+/)
end
def test_solo
assert @tester.solo.match(/\w+/)
end
end
|
#!/bin/bash
set -e
docker build -t invokit-web-test .
echo Running on http://localhost:8080
docker run --rm -p 8080:80 invokit-web-test |
package com.daimler.mbingresskit.implementation.filestorage
import com.daimler.mbingresskit.filestorage.FileWriter
import java.io.File
internal class HtmlFileWriter : FileWriter<String> {
override fun writeToFile(data: String, outFile: File): String? {
val outStream = outFile.outputStream()
outStream.write(data.toByteArray())
outStream.close()
return outFile.absolutePath
}
override fun readFile(inFile: File): String? {
return inFile.readText()
}
} |
<#
.Synopsis
Requirements
.Description
Requirements Feature Modules
.NOTES
Author: Yi
Website: http://fengyi.tel
#>
<#
.Requirements
.先决条件
#>
Function Requirements
{
Clear-Host
$Host.UI.RawUI.WindowTitle = "$($Global:UniqueID)'s Solutions | Prerequisites"
Write-Host "`n Prerequisites`n ---------------------------------------------------------------"
Write-Host -NoNewline " Checking PS version 5.1 and above".PadRight(58)
if ($PSVersionTable.PSVersion.major -ge "5") {
Write-Host -ForegroundColor Green "OK".PadLeft(8)
} else {
Write-Host -ForegroundColor Red " Failed".PadLeft(8)
}
Write-Host -NoNewline " Checking Windows version > 10.0.16299.0".PadRight(58)
$OSVer = [System.Environment]::OSVersion.Version;
if (($OSVer.Major -eq 10 -and $OSVer.Minor -eq 0 -and $OSVer.Build -ge 16299)) {
Write-Host -ForegroundColor Green "OK".PadLeft(8)
} else {
Write-Host -ForegroundColor Red "Failed".PadLeft(8)
}
Write-Host -NoNewline " Checking Must be elevated to higher authority".PadRight(58)
if (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544") {
Write-Host -ForegroundColor Green "OK".PadLeft(8)
} else {
Write-Host -ForegroundColor Red "Failed".PadLeft(8)
Write-Host "`n It will automatically exit after 6 seconds." -ForegroundColor Red
Start-Sleep -s 6
exit
}
Write-Host "`n Congratulations, passing the prerequisites.`n About to go to the next step." -ForegroundColor Green
Start-Sleep -s 4
}
Export-ModuleMember -Function * -Alias * |
package config
import (
"os"
"path"
"github.com/pkg/errors"
"github.com/spf13/viper"
)
const (
availableContextsKey = "availableContexts"
defaultContextKey = "defaultContext"
credentialsStoreBackendKey = "credentialsStore.backend"
credentialsStoreFilePassphrase = "credentialsStore.filePassphrase"
)
// Init initializes config store for Capact CLI.
func Init(configPath string) error {
err := viper.BindEnv(credentialsStoreBackendKey, "CAPACT_CREDENTIALS_STORE_BACKEND")
if err != nil {
return errors.Wrapf(err, "while binding %s key", credentialsStoreBackendKey)
}
err = viper.BindEnv(credentialsStoreFilePassphrase, "CAPACT_CREDENTIALS_STORE_FILE_PASSPHRASE")
if err != nil {
return errors.Wrapf(err, "while binding %s key", credentialsStoreFilePassphrase)
}
if configPath == "" {
configPath, err = GetDefaultConfigPath("config.yaml")
if err != nil {
return errors.Wrap(err, "while getting default config path")
}
}
viper.SetConfigFile(configPath)
viper.SetConfigType("yaml")
err = viper.ReadInConfig()
if _, ok := err.(viper.ConfigFileNotFoundError); ok || os.IsNotExist(err) {
dir := path.Dir(configPath)
err = os.MkdirAll(dir, 0700)
if err != nil {
return errors.Wrap(err, "while creating directory for config file")
}
err = viper.WriteConfig()
if err != nil {
return errors.Wrap(err, "while writing config file")
}
} else if err != nil {
return errors.Wrap(err, "while reading configuration")
}
return nil
}
// GetDefaultConfigPath returns Capact location for a given config file
func GetDefaultConfigPath(fileName string) (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
return path.Join(homeDir, ".config", "capact", fileName), nil
}
// SetAsDefaultContext sets default Hub server which is used for all executed operations.
func SetAsDefaultContext(server string, override bool) error {
currentDefaultContext := GetDefaultContext()
if currentDefaultContext == "" || override {
viper.Set(defaultContextKey, server)
if err := viper.WriteConfig(); err != nil {
return errors.Wrap(err, "while writing default context into config file")
}
}
return nil
}
// GetDefaultContext returns default Hub server URL.
func GetDefaultContext() string {
return viper.GetString(defaultContextKey)
}
// AddNewContext adds a new context if not exists to the collection of available contexts.
func AddNewContext(server string) error {
availableContexts := GetAvailableContexts()
if err := storeAvailableContexts(appendContextIfMissing(availableContexts, server)); err != nil {
return errors.Wrap(err, "while setting and writing a new context")
}
return nil
}
// DeleteContext delete a context from the the collection of available contexts.
func DeleteContext(server string) error {
availableContexts := GetAvailableContexts()
for index, context := range availableContexts {
if context == server {
availableContexts = append(availableContexts[:index], availableContexts[index+1:]...)
}
}
if err := storeAvailableContexts(availableContexts); err != nil {
return errors.Wrap(err, "while setting and writing available contexts")
}
return nil
}
// GetAvailableContexts return collection of available contexts.
func GetAvailableContexts() []string {
return viper.GetStringSlice(availableContextsKey)
}
// GetCredentialsStoreBackend returns keyring backend type.
func GetCredentialsStoreBackend() string {
return viper.GetString(credentialsStoreBackendKey)
}
// GetCredentialsStoreFilePassphrase returns passphrase for file keyring backend type.
func GetCredentialsStoreFilePassphrase() string {
return viper.GetString(credentialsStoreFilePassphrase)
}
func storeAvailableContexts(contexts []string) error {
viper.Set(availableContextsKey, contexts)
if err := viper.WriteConfig(); err != nil {
return errors.Wrap(err, "while writing available contexts into config file")
}
return nil
}
func appendContextIfMissing(contexts []string, newContext string) []string {
for _, context := range contexts {
if context == newContext {
return contexts
}
}
return append(contexts, newContext)
}
|
require 'rails/generators/generated_attribute'
module GeneratorUtils
RAILS_ADDED_COLS = %w(id created_at updated_at)
#TODO...There has GOT to be a better way to do this (column name gets listed first if it contains the word "name")
ATTR_SORT_PROC =
proc do |a, b|
if a =~ /name/
1
elsif b =~ /name/
-1
elsif a =~ /email/
1
elsif b =~ /email/
-1
else
0
end
end
def self.attr_cols(table_name)
#return an array of the columns we are interested in allowing the user to change...
# as GeneratedAttribute objects
acs = table_name.classify.constantize.columns
.reject{ |col| RAILS_ADDED_COLS.include?(col.name) }
.sort(&ATTR_SORT_PROC)
.map { |ac| Rails::Generators::GeneratedAttribute.new(ac.name, ac.type)}
end
def self.curr_locale
I18n.locale.to_s
end
end |
// Portable Grid v0.7.3
// © 2018 Gus Cost
// MIT license
(function (r, f) {
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f(require("react"), require("prop-types"), require("create-react-class"));
} else if (typeof define === "function" && define.amd) {
define(["react", "prop-types", "create-react-class"], function (a, b, c) {
return (r.PortableGrid = f(a, b, c));
});
} else {
r.PortableGrid = f(r.React, r.PropTypes, r.createReactClass);
}
}(this, function (React, PropTypes, createReactClass) {
// alias for React.createElement
var el = React.createElement;
// constant styles for static proportions
var _rowSpacerStyle = {
padding: "7px",
boxSizing: "border-box",
whiteSpace: "pre-wrap",
userSelect: "none",
MozUserSelect: "none",
MsUserSelect: "none",
WebkitUserSelect: "none"
};
var _pagerForwardButtonContainerStyle = {
position: "absolute",
right: "1px",
width: "64px"
};
var _pagerBackButtonContainerStyle = {
position: "absolute",
left: "4px"
};
var _pagerPageContainerStyle = {
position: "absolute",
left: "100px",
height: "32px",
lineHeight: "32px"
};
// these will get passed in to the onClickHeader function for use if needed
var _defaultSortOrderUpdate = function (sortOrder) {
return sortOrder ? (sortOrder === "down" ? undefined : "down") : "up";
};
var _defaultSort = function (field, sort, a, b) {
if (!sort) { field = "id"; }
var valueA = a[field];
var valueB = b[field];
if (sort === "down") { return valueA < valueB ? 1 : (valueA > valueB ? -1 : 0); }
else { return valueA > valueB ? 1 : (valueA < valueB ? -1 : 0); }
};
return createReactClass({
// name for debugging
displayName: "PortableGrid",
// data prop should be an array of data objects
// columns prop should be an array of column definitions
// each data item should have keys matching "field" from each column
// alternatively a column can specify a "template" function that takes the row item
// to scope these functions correctly, a scope prop should be passed in
// data items can include _rowSelected key to set whether the row is selected
// data items can include _rowBackground key to set the row background color
propTypes: PropTypes ? {
data: PropTypes.arrayOf(
PropTypes.shape({
_rowSelected: PropTypes.bool,
_rowBackground: PropTypes.string
})
).isRequired,
columns: PropTypes.arrayOf(
PropTypes.shape({
title: PropTypes.string.isRequired,
width: PropTypes.string.isRequired,
field: PropTypes.string,
template: PropTypes.func,
sort: PropTypes.oneOf(["up", "down"])
})
).isRequired,
detail: PropTypes.func,
headerVisible: PropTypes.bool,
currentPage: PropTypes.number,
pageSize: PropTypes.number,
onChangePage: PropTypes.func,
onClickHeader: PropTypes.func,
onClickRow: PropTypes.func,
scope: PropTypes.object // typically a reference to the parent component
} : null,
componentDidUpdate: function () {
if (this.refs.page) { this.refs.page.value = this.props.currentPage; }
},
getDefaultProps: function () {
return {
headerVisible: true,
headerBackgroundColor: "#263248",
headerBorderColor: "#555555",
headerTextColor: "#FFFFFF",
pagerBackgroundColor: "#F1F1F1",
pagerButtonBackgroundColor: "#DFDFDF",
pagerButtonActiveBackgroundColor: "#CECECE",
pagerButtonBorderColor: "#CCCCCC",
pagerButtonActiveBorderColor: "#AAAAAA",
pagerButtonTextColor: "#333333",
pagerPageInputBorderColor: "#CCCCCC",
pagerPageInputActiveBorderColor: "#AAAAAA",
rowEvenBackgroundColor: "#F9F9F9",
rowOddBackgroundColor: "#FFFFFF",
rowSelectedBackgroundColor: "#FFFFDD",
rowSelectedBorderColor: "#DDDDDD"
};
},
// handlers for buttons
_onButtonActivate: function (event) {
event.target.style.backgroundColor = this.props.pagerButtonActiveBackgroundColor;
event.target.style.border = "1px solid " + this.props.pagerButtonActiveBorderColor;
event.target.style.zIndex = 1;
},
_onButtonDeactivate: function (event) {
event.target.style.backgroundColor = this.props.pagerButtonBackgroundColor;
event.target.style.border = "1px solid " + this.props.pagerButtonBorderColor;
event.target.style.zIndex = 0;
},
// handlers for page change buttons
_onFirstPage: function () {
this.props.onChangePage(1);
},
_onPreviousPage: function () {
this.props.onChangePage(Math.max(this.props.currentPage - 1, 1));
},
_onNextPage: function () {
this.props.onChangePage(
Math.min(
this.props.currentPage + 1,
Math.ceil((this.props.data.length || 1) / this.props.pageSize)
)
);
},
_onLastPage: function () {
this.props.onChangePage(Math.ceil((this.props.data.length || 1) / this.props.pageSize));
},
// handlers for the page input box
_onInputPage: function (event) {
var sanitizedValue = isNaN(parseFloat(event.target.value)) ? 1 : event.target.value;
this.props.onChangePage(Math.floor(Math.min(
Math.max(sanitizedValue, 1),
Math.ceil((this.props.data.length || 1) / this.props.pageSize)
)));
},
_onKeyPage: function (event) {
if (event.key === "Enter") {
this._onInputPage(event);
}
},
_onFocusPage: function (event) {
event.target.style.border = "1px solid " + this.props.pagerPageInputActiveBorderColor;
},
_onBlurPage: function (event) {
event.target.style.border = "1px solid " + this.props.pagerPageInputBorderColor;
this._onInputPage(event);
},
// render function
render: function () {
var component = this;
var previousRowSelected = false;
var hasOnClickHeader = !!component.props.onClickHeader;
var hasOnClickRow = !!component.props.onClickRow;
// styles for pager
var pagerStyle = {
position: "relative",
width: "100%",
backgroundColor: component.props.pagerBackgroundColor,
height: "38px",
paddingTop: "3px",
boxSizing: "border-box"
};
var pagerButtonStyle = {
boxSizing: "border-box",
fontSize: "1em",
width: "32px",
height: "32px",
lineHeight: "16px",
padding: "1px 7px",
margin: "0px 0px 0px -1px",
position: "relative",
backgroundColor: component.props.pagerButtonBackgroundColor,
border: "1px solid " + component.props.pagerButtonBorderColor,
outline: "none",
color: component.props.pagerButtonTextColor,
cursor: "pointer",
appearance: "none",
MozAppearance: "none",
WebkitAppearance: "none"
};
var pagerPageInputStyle = {
display: "inline-block",
boxSizing: "border-box",
border: "1px solid " + component.props.pagerPageInputBorderColor,
outline: "none",
width: "50px",
height: "32px",
fontSize: "1em",
lineHeight: "22px",
paddingLeft: "7px"
};
// styles for sort direction indicator
var sortIndicatorText = { "up": "▲", "down": "▼" };
var sortIndicatorStyle = {
backgroundColor: component.props.headerBackgroundColor,
fontSize: ".8em",
position: "absolute",
right: "8px",
top: "8px"
};
// pre-process page of data to display
var dataPage;
var pagerVisible = false;
if (component.props.pageSize && component.props.currentPage) {
var firstIndex = (component.props.currentPage - 1) * component.props.pageSize;
dataPage = component.props.data.slice(firstIndex, firstIndex + component.props.pageSize);
pagerVisible = true;
while (dataPage.length < component.props.pageSize) { dataPage.push(null); }
} else {
dataPage = component.props.data;
}
// render grid
return React.createElement("div", {
className: component.props.className,
style: { width: "auto" }
},
el("div", {
className: "dataTableHeader",
style: {
backgroundColor: component.props.headerBackgroundColor,
border: "1px solid " + component.props.headerBackgroundColor,
overflowX: "hidden",
whiteSpace: "nowrap",
boxSizing: "border-box",
userSelect: "none",
MozUserSelect: "none",
MsUserSelect: "none",
WebkitUserSelect: "none"
}
},
// generate a react element for each column header
component.props.columns.map(function (column, index) {
// column header style
var dataTableColumnHeaderStyle = {
cursor: hasOnClickHeader ? "pointer" : null,
width: column.width,
position: "relative",
display: "inline-block",
padding: "6px 7px",
overflowX: "hidden",
whiteSpace: "nowrap",
boxSizing: "border-box",
borderLeft: "1px solid " + (index > 0 ?
component.props.headerBorderColor :
component.props.headerBackgroundColor),
color: component.props.headerTextColor,
verticalAlign: "middle" // overflow fix: http://stackoverflow.com/questions/23529369/
};
// return column header
return el("div", {
style: dataTableColumnHeaderStyle,
key: index,
onClick: hasOnClickHeader ? component.props.onClickHeader.bind(
component.props.scope,
column,
_defaultSortOrderUpdate,
_defaultSort
) : null
},
column.title || el("div", { dangerouslySetInnerHTML: { __html: " " } }),
column.sort ? el("span", { style: sortIndicatorStyle },
sortIndicatorText[column.sort]
) : null
);
})
),
dataPage.map(function (item, rowIndex) {
// render spacer row if data item is null
if (!item) {
return el("div", { key: rowIndex, style: _rowSpacerStyle }, el("div", null, " "));
}
// row class
var rowClass = item._rowSelected ? "bold" : "";
// row background color
// to highlight row, set "_rowSelected" property on data object
// otherwise rows render with alternate shading
var rowBackgroundColor = (item._rowBackground ? item._rowBackground :
(item._rowSelected ? component.props.rowSelectedBackgroundColor :
(rowIndex % 2 === 1 ? component.props.rowOddBackgroundColor :
component.props.rowEvenBackgroundColor)));
// row container class
var rowContainerClass = "dataTableRow"
+ (hasOnClickRow ? " clickable" : "");
// row container style has border when selected
var rowContainerStyle = {
borderStyle: "solid",
borderColor: item._rowSelected ?
component.props.rowSelectedBorderColor : rowBackgroundColor,
borderWidth: (previousRowSelected ? "0px" : "1px") + " 1px 1px 1px",
overflowX: "hidden",
whiteSpace: "nowrap",
boxSizing: "border-box"
};
// row detail has dotted border on top
var rowDetailStyle = {
borderTop: "1px dotted " + component.props.rowSelectedBorderColor
};
// save if row was selected to render top border of next row
previousRowSelected = item._rowSelected;
// row container
return el("div", {
key: rowIndex,
className: rowContainerClass,
style: rowContainerStyle,
onClick: hasOnClickRow ?
component.props.onClickRow.bind(component.props.scope, item) : null
},
el("div", {
className: rowClass,
style: { backgroundColor: rowBackgroundColor }
},
// generate a react element for each column
component.props.columns.map(function (column, columnIndex) {
// run the column template if it exists (pass in component as this)
// otherwise return the value for the column key
var hasTemplate = !!column.template;
var contents = hasTemplate ?
column.template.call(component.props.scope, item) :
item[column.field];
// special case: convert to string if zero
if (contents === 0) { contents = "0"; }
// column style
var columnStyle = {
display: "inline-block",
width: column.width,
textAlign: column.align || "left",
padding: column.padding || "6px 7px",
overflowX: "hidden",
whiteSpace: "nowrap",
boxSizing: "border-box",
verticalAlign: "middle"
};
// return column
return el("div", {
style: columnStyle,
key: columnIndex
},
contents ||
el("div", { dangerouslySetInnerHTML: { __html: " " } })
);
})
),
// render detail row if property exists
(item._rowSelected && component.props.detail) ? el("div", {
style: rowDetailStyle
},
component.props.detail.call(component.props.scope, item)
) : null
);
}),
// render pager if data is longer than page size
pagerVisible ? el("div", { style: pagerStyle },
el("div", { style: _pagerBackButtonContainerStyle },
el("div", null,
el("input", {
type: "button",
value: "«",
style: pagerButtonStyle,
onClick: component._onFirstPage,
onMouseDown: component._onButtonActivate,
onMouseUp: component._onButtonDeactivate,
onMouseOut: component._onButtonDeactivate
}),
el("input", {
type: "button",
value: "‹",
style: pagerButtonStyle,
onClick: component._onPreviousPage,
onMouseDown: component._onButtonActivate,
onMouseUp: component._onButtonDeactivate,
onMouseOut: component._onButtonDeactivate
})
)
),
el("div", { style: _pagerPageContainerStyle },
"Page ",
el("div", { style: { display: "inline-block", width: "50px", height:"32px" } },
el("input", {
type: "text",
ref: "page",
style: pagerPageInputStyle,
defaultValue: component.props.currentPage,
onKeyDown: component._onKeyPage,
onFocus: component._onFocusPage,
onBlur: component._onBlurPage
})
),
" of ",
Math.ceil((component.props.data.length || 1) / component.props.pageSize)
),
el("div", { style: _pagerForwardButtonContainerStyle },
el("div", null,
el("input", {
type: "button",
value: "›",
style: pagerButtonStyle,
onClick: component._onNextPage,
onMouseDown: component._onButtonActivate,
onMouseUp: component._onButtonDeactivate,
onMouseOut: component._onButtonDeactivate
}),
el("input", {
type: "button",
value: "»",
style: pagerButtonStyle,
onClick: component._onLastPage,
onMouseDown: component._onButtonActivate,
onMouseUp: component._onButtonDeactivate,
onMouseOut: component._onButtonDeactivate
})
)
)
) : null
);
}
});
}));
|
<?php
/**
* PHP Parser and UML/XMI generator. Reverse-engineering tool.
*
* A package to scan PHP files and directories, and get an UML/XMI representation
* of the parsed classes/packages.
* The XMI code can then be imported into a UML designer tool, like Rational Rose
* or ArgoUML.
*
* PHP version 5
*
* @category PHP
* @package PHP_UML
* @author Baptiste Autin <[email protected]>
* @license http://www.gnu.org/licenses/lgpl.html LGPL License 3
* @version SVN: $Revision: 176 $
* @link http://pear.php.net/package/PHP_UML
* @link http://www.baptisteautin.com/projects/PHP_UML/
* @since $Date: 2011-09-19 00:03:11 +0200 (lun., 19 sept. 2011) $
*/
require_once 'PEAR/Exception.php';
spl_autoload_register(array('PHP_UML', 'autoload'));
/**
* Facade to use, through its methods:
* - the setInput() method to set the files and/or directories to parse
* - the parse('name') method to start parsing, and building the model
* - the helper method export('format', 'location') to export the model
*
* For example:
* <code>
* $t = new PHP_UML();
* $t->setInput('PHP_UML/');
* $t->export('xmi', '/home/wwww/');
* </code>
*
* If you want to produce XMI without using the PHP parser, please refer to
* the file /examples/test_with_api.php; it will show how you can build a
* model by yourself, with the PHP_UML_Metamodel package.
*
* @category PHP
* @package PHP_UML
* @author Baptiste Autin <[email protected]>
* @license http://www.gnu.org/licenses/lgpl.html LGPL License 3
* @link http://pear.php.net/package/PHP_UML
* @link http://www.baptisteautin.com/projects/PHP_UML/
* @see PHP_UML_Metamodel_Superstructure
*
*/
class PHP_UML
{
/**
* Character used to separate the patterns passed to setIgnorePattern() and
* setMatchPattern().
* @var string
*/
const PATTERN_SEPARATOR = ',';
/**
* If true, a UML logical view is created.
* @var boolean
*/
public $logicalView = true;
/**
* If true, a UML deployment view is created.
* Each file produces an artifact.
* @var boolean
*/
public $deploymentView = true;
/**
* If true, a component view is created.
* file system. Each file produces an component
* @var boolean
*/
public $componentView = false;
/**
* If true, the docblocks content is parsed.
* All possible information is retrieved : general comments, @package, @param...
* @var boolean
*/
public $docblocks = true;
/**
* If true, the elements (class, function) are included in the API only if their
* comments contain explicitly a docblock "@api"
* @var boolean
*/
public $onlyApi = false;
/**
* If true, only classes and namespaces are retrieved. If false, procedural
* functions and constants are also included
*/
public $pureObject = false;
/**
* If true, the empty namespaces (inc. no classes nor interfaces) are ignored
* @var boolean
*/
public $removeEmptyNamespaces = true;
/**
* If true, the elements marked with @internal are included in the API.
* @var boolean
*/
public $showInternal = false;
/**
* If true, the PHP variable prefix $ is kept
* @var boolean
*/
public $dollar = true;
/**
* A reference to a UML model
* @var PHP_UML::Metamodel::PHP_UML_Metamodel_Superstructure
*/
private $model;
/**
* List of directories to scan
* @var array
*/
private $directories = array();
/**
* List of files to scan
* @var array
*/
private $files = array();
/**
* Allowed filenames (possible wildcards are ? and *)
*
* @var array
*/
private $matchPatterns = array('*.php');
/**
* Ignored directories (possible wildcards are ? and *)
*
* @var array();
*/
private $ignorePatterns = array();
/**
* Current exporter object.
*
* @var PHP_UML_Output_Exporter
*/
private $exporter;
/**
* Current importer object.
*
* @var PHP_UML_Input_ImporterFileScanner
*/
private $importer;
/**
* Constructor.
*
* Creates an empty model and holds a reference to it.
*
*/
public function __construct()
{
$this->model = new PHP_UML_Metamodel_Superstructure;
$this->importer = new PHP_UML_Input_PHP_FileScanner($this->model);
//$this->importer->setModel($this->model);
}
/**
* Parse a PHP file, and return a PHP_UML_Metamodel_Superstructure object
* (= a UML model) corresponding to what has been found in the file.
*
* @param mixed $files File(s) to parse. Can be a single file,
* or an array of files.
* @param string $name A name for the model to generate
*
* @deprecated Use setInput() instead
*
* @return PHP_UML_Metamodel_Superstructure The resulting UML model
*/
public function parseFile($files, $name = 'default')
{
$this->setInput($files);
return $this->parse($name);
}
/**
* Set the input elements (files and/or directories) to parse
*
* @param mixed $pathes Array, or string of comma-separated-values
*/
public function setInput($pathes)
{
if (!is_array($pathes)) {
$pathes = explode(self::PATTERN_SEPARATOR, $pathes);
$pathes = array_map('trim', $pathes);
}
foreach ($pathes as $path) {
if (is_file($path)) {
$this->files[] = $path;
}
elseif (is_dir($path))
$this->directories[] = $path;
else
throw new PHP_UML_Exception($path.': unknown file or folder');
}
}
/**
* Setter for the FileScanner used for the parsing. Automatically
* sets the importer's model with the model owned by PHP_UML
*
* @param PHP_UML_Input_ImporterFileScanner $importer FileScanner to be used
*/
public function setImporter(PHP_UML_Input_ImporterFileScanner $importer)
{
$this->importer = $importer;
$this->importer->setModel($this->model);
}
/**
* Setter for the filename patterns.
* Usage: $phpuml->setFilePatterns(array('*.php', '*.php5'));
* Or: $phpuml->setFilePatterns('*.php, *.php5');
*
* @param mixed $patterns List of patterns (string or array)
*/
public function setMatchPatterns($patterns)
{
if (is_array($patterns)) {
$this->matchPatterns = $patterns;
} else {
$this->matchPatterns = explode(self::PATTERN_SEPARATOR, $patterns);
$this->matchPatterns = array_map('trim', $this->matchPatterns);
}
}
/**
* Set a list of files / directories to ignore during parsing
* Usage: $phpuml->setIgnorePatterns(array('examples', '.svn'));
* Or: $phpuml->setIgnorePatterns('examples .svn');
*
* @param mixed $patterns List of patterns (string or array)
*/
public function setIgnorePatterns($patterns)
{
if (is_array($patterns)) {
$this->ignorePatterns = $patterns;
} else {
$this->ignorePatterns = explode(self::PATTERN_SEPARATOR, $patterns);
}
$this->ignorePatterns = array_map(array('self', 'cleanPattern'), $this->ignorePatterns);
}
/**
* Converts a path pattern to the format expected by FileScanner
* (separator can only be / ; must not start by any separator)
*
* @param string $p Pattern
*
* @return string Pattern converted
*
* @see PHP_UML_FilePatternFilterIterator#accept()
*/
private static function cleanPattern($p)
{
$p = str_replace('/', DIRECTORY_SEPARATOR, trim($p));
if ($p[0]==DIRECTORY_SEPARATOR)
$p = substr($p, 1);
return $p;
}
/**
* Set the packages to include in the XMI code
* By default, ALL packages found will be included.
*
* @param mixed $packages List of packages (string or array)
* TODO
public function setPackages($packages)
{
if (is_array($patterns)) {
$this->packages = $patterns;
}
else {
$this->packages = explode(self::PATTERN_SEPARATOR, $patterns);
$this->packages = array_map('trim', $this->packages);
}
}
*/
/**
* Parse a PHP folder, and return a PHP_UML_Metamodel_Superstructure object
* (= a UML model) corresponding to what has been parsed.
*
* @param mixed $directories Directory path(es). Can be a single path,
* or an array of pathes.
* @param string $modelName A name for the model to generate
*
* @deprecated Use setInput() instead
*
* @return PHP_UML_Metamodel_Superstructure The resulting UML model
*/
public function parseDirectory($directories, $modelName = 'default')
{
$this->setInput($directories);
return $this->parse($modelName);
}
/**
* Parse the directories and the files (depending on what the $directories
* and $files properties have been set to with setInput()) and return a
* UML model.
*
* @param string $modelName A model name (e.g., the name of your application)
*
* @return PHP_UML_Metamodel_Superstructure The resulting UML model
*/
public function parse($modelName = 'default')
{
$this->model->initModel($modelName);
if ($this->importer instanceof PHP_UML_Input_PHP_FileScanner)
$this->setInputPhpParserOptions();
$this->importer->setFiles($this->files);
$this->importer->setDirectories($this->directories);
$this->importer->setMatchPatterns($this->matchPatterns);
$this->importer->setIgnorePatterns($this->ignorePatterns);
$this->importer->import();
if ($this->removeEmptyNamespaces)
PHP_UML_Metamodel_Helper::deleteEmptyPackages($this->model->packages);
return $this->model;
}
private function setInputPhpParserOptions()
{
$options = new PHP_UML_Input_PHP_ParserOptions();
$options->keepDocblocks = $this->docblocks;
$options->keepDollar = $this->dollar;
$options->skipInternal = (!$this->showInternal);
$options->onlyApi = $this->onlyApi;
$options->strict = $this->pureObject;
$this->importer->setParserOptions($options);
}
/**
* Update an instance of Xmi_Exporter with the current output settings
*
* @param PHP_UML_Output_Xmi_Exporter $e Exporter object to update
*/
private function setOutputXmiOptions(PHP_UML_Output_Xmi_Exporter $e)
{
$e->setLogicalView($this->logicalView);
$e->setComponentView($this->componentView);
$e->setDeploymentView($this->deploymentView);
$e->setStereotypes($this->docblocks);
}
/**
* Convert the UML model (stored in the object) into some output data.
*
* @param string $format Desired format ("xmi", "html", "php"...)
* @param string $outputDir Output directory
*/
public function export($format='xmi', $outputDir='.')
{
if (empty($outputDir)) {
throw new PHP_UML_Exception('No output folder given.');
}
if (empty($this->model) || empty($this->model->packages)) {
throw new PHP_UML_Exception('No model given.');
}
$this->exporter = PHP_UML_Output_Exporter::getInstance($format);
$this->exporter->setModel($this->model);
return $this->exporter->export($outputDir);
}
/**
* Public accessor to the metamodel.
*
* @return PHP_UML_Metamodel_Superstructure Model generated during PHP parsing
*/
public function getModel()
{
return $this->model;
}
/**
* Set the exporter to use (an Output_Xmi_Exporter is already set by default)
*
* @param PHP_UML_Output_Exporter $exporter The exporter object to use
*/
public function setExporter(PHP_UML_Output_Exporter $exporter)
{
$this->exporter = $exporter;
$this->exporter->setModel($this->model);
}
/**
* Autoloader
*
* @param string $class Class name
*/
static function autoload($class)
{
if (substr($class, 0, 7)=='PHP_UML') {
$path = 'UML'.str_replace('_', '/', substr($class, 7).'.php');
require $path;
}
}
}
?> |
use crate::model::complex_types::{local_simple_type, top_level_simple_type};
// xsd:simpleType
// Element information
// Namespace: http://www.w3.org/2001/XMLSchema
// Schema document: datatypes.xsd
// Type: xsd:localSimpleType
// Properties: Local, Qualified
//
// Used in
// Anonymous type of element xsd:list
// Anonymous type of element xsd:union
// Group xsd:elementModel
// Group xsd:simpleRestrictionModel
// Anonymous type of element xsd:restriction via reference to xsd:simpleRestrictionModel
// Type xsd:localAttributeType (Element xsd:attribute)
// Type xsd:topLevelAttributeType (Element xsd:attribute)
// Type xsd:localElement via reference to xsd:elementModel (Element xsd:element)
// Type xsd:narrowMaxMin via reference to xsd:elementModel (Element xsd:element)
// Type xsd:simpleRestrictionType via reference to xsd:simpleRestrictionModel (Element xsd:restriction)
// Type xsd:topLevelElement via reference to xsd:elementModel (Element xsd:element)
pub type LocalSimpleType<'a> = local_simple_type::LocalSimpleType<'a>;
// xsd:simpleType
// See http://www.w3.org/TR/xmlschema-2/#element-simpleType.
// Element information
// Namespace: http://www.w3.org/2001/XMLSchema
// Schema document: datatypes.xsd
// Type: xsd:topLevelSimpleType
// Properties: Global, Qualified
//
// Used in
// Group xsd:redefinable
// Anonymous type of element xsd:redefine via reference to xsd:redefinable
// Anonymous type of element xsd:schema via reference to xsd:schemaTop
// Group xsd:schemaTop via reference to xsd:redefinable
pub type TopLevelSimpleType<'a> = top_level_simple_type::TopLevelSimpleType<'a>;
|
# prezto-contrib
[Prezto][1] is a configuration framework for zsh aimed at providing better
defaults and other conveniences. However, to avoid feature bloat in the core
repository, prezto-contrib was born. This repository is meant to include
additional modules which are either not ready for inclusion in prezto-core or
don't currently have a maintainer willing to support them.
## Usage
Multiple module directory support is built into prezto, so it's pretty easy to
use these modules. Simply do the following:
```
cd $ZPREZTODIR
git clone https://github.com/belak/prezto-contrib contrib
```
After the repo is cloned, you can load modules in the same way you'd load a
normal prezto module.
Alternatively, you can clone contrib elsewhere and update the module dirs
setting.
[1]: https://github.com/sorin-ionescu/prezto
|
namespace D_Parser.Dom
{
public interface IMetaDeclaration : ISyntaxRegion, IVisitable<MetaDeclarationVisitor>
{
}
public interface IMetaDeclarationBlock : IMetaDeclaration
{
CodeLocation BlockStartLocation { get; set; }
new CodeLocation EndLocation {get;set;}
}
public class AttributeMetaDeclaration : IMetaDeclaration
{
public DAttribute[] AttributeOrCondition;
public ElseMetaDeclaration OptionalElseBlock;
public AttributeMetaDeclaration(params DAttribute[] attr)
{
this.AttributeOrCondition = attr;
}
/// <summary>
/// The start location of the first given attribute
/// </summary>
public CodeLocation Location
{
get
{
return AttributeOrCondition[0].Location;
}
set { throw new System.NotImplementedException (); }
}
public CodeLocation EndLocation {
get;
set;
}
public void Accept(MetaDeclarationVisitor vis)
{
vis.Visit(this);
}
}
public class ElseMetaDeclaration : IMetaDeclaration
{
public CodeLocation Location { get;set; }
public CodeLocation EndLocation { get;set; }
public void Accept(MetaDeclarationVisitor vis)
{
vis.Visit(this);
}
}
public class ElseMetaDeclarationBlock : ElseMetaDeclaration, IMetaDeclarationBlock
{
public CodeLocation BlockStartLocation
{
get;
set;
}
}
public class ElseMetaDeclarationSection : ElseMetaDeclaration { }
/// <summary>
/// Describes a meta block that begins with a colon. 'Ends' right after the colon.
/// </summary>
public class AttributeMetaDeclarationSection : AttributeMetaDeclaration
{
public AttributeMetaDeclarationSection(DAttribute attr) : base(attr) { }
}
/// <summary>
/// Describes a meta block that is enclosed by curly braces.
/// Examples are
/// static if(...){
/// }
///
/// @safe{
/// }
/// </summary>
public class AttributeMetaDeclarationBlock : AttributeMetaDeclaration, IMetaDeclarationBlock
{
public AttributeMetaDeclarationBlock(params DAttribute[] attr) : base(attr) {}
public CodeLocation BlockStartLocation
{
get;
set;
}
}
/// <summary>
/// A simple block that is just used for code alignment but semantically irrelevant elsehow.
/// {
/// int cascadedIntDecl;
/// }
/// </summary>
public class MetaDeclarationBlock : IMetaDeclarationBlock
{
public CodeLocation BlockStartLocation
{
get;
set;
}
public CodeLocation Location
{
get { return BlockStartLocation; }
set { BlockStartLocation = value; }
}
public CodeLocation EndLocation { get;set; }
public void Accept(MetaDeclarationVisitor vis)
{
vis.Visit(this);
}
}
}
|
[ -n "$1" ] || { echo Node must be supplied ; exit 1;}
[ -n "$2" ] || { echo PID must be supplied; exit 1; }
list=$(invoke ssh ps-childs $1 $2)
for i in $list
do
invoke ssh command $1 kill $i || echo Failed to kill $i
done
invoke ssh command $1 kill $2 |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Unity.VectorGraphics;
using UnityEngine;
/// <summary>
/// Tools for image processing
/// </summary>
namespace ImageUtils
{
/// <summary>
/// Processes PNG and SVG images
/// </summary>
public static class ImageModule
{
/// <summary>
/// Convert string-formated bytearray to bytearray
/// </summary>
/// <param name="responseString">Formated string</param>
/// <param name="pattern">How the string is formated</param>
/// <returns>A byte array</returns>
public static byte[] toByteArray(string responseString, string pattern)
{
responseString = Regex.Replace(responseString, pattern, "");
return responseString.Split(' ').Select(x => Byte.Parse(x, NumberStyles.Integer, null)).ToArray();
}
/// <summary>
/// Converts a string-formated SVG bytearray to a Sprite.
/// </summary>
/// <param name="responseString">Formated bytearray</param>
/// <returns>A Sprite</returns>
public static Sprite ImportSVG(string responseString)
{
string path = Application.persistentDataPath + @"\temp.svg";
File.WriteAllBytes(
path,
toByteArray(responseString, @"#|\[|\]|\n|( 0)*")
);
var tessOptions = new VectorUtils.TessellationOptions()
{
StepDistance = 100.0f,
MaxCordDeviation = 0.5f,
MaxTanAngleDeviation = 0.1f,
SamplingStepSize = 0.01f
};
var sceneInfo = SVGParser.ImportSVG(new StreamReader(path));
var geoms = VectorUtils.TessellateScene(sceneInfo.Scene, tessOptions);
return VectorUtils.BuildSprite(geoms, 100.0f, VectorUtils.Alignment.Center, Vector2.zero, 128, true);
}
/// <summary>
/// Converts a string-formated PNG bytearray to a Sprite.
/// </summary>
/// <param name="responseString">Formated bytearray</param>
/// <returns>A Sprite</returns>
public static Sprite ImportPNG(string responseString)
{
Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(toByteArray(responseString, @"#|\[|\]|\n"));
return Sprite.Create(
tex,
new Rect(0, 0, tex.width, tex.height),
Vector2.zero
);
}
}
} |
<?php
$table = Table::withContents($books->items())->striped()
->callback('Ações', function ($field, $book) {
$linkEdit = route('books.edit', ['book' => $book->id]);
$linkDestroy = route('books.destroy', ['book' => $book->id]);
$linkChapters = route('chapters.index', ['book' => $book->id]);
$linkCovers = route('books.cover.store', ['book' => $book->id]);
$linkExport = route('books.export', ['book' => $book->id]);
$deleteFormId = "delete-form-{$book->id}";
$deleteForm = Form::open(['route' =>
['books.destroy', 'book' => $book->id],
'method' => 'DELETE', 'id' => $deleteFormId, 'style' => 'display:none']) .
Form::close();
$anchorDestroy = Button::link('Enviar para Lixeira')
->asLinkTo($linkDestroy)->addAttributes([
'onclick' => "event.preventDefault();
document.getElementById(\"{$deleteFormId}\").submit();"
]);
$anchorExport = Button::link('Exportar')
->asLinkTo($linkExport)->addAttributes([
'onclick' => "event.preventDefault();exportBook(\"$linkExport\");"
]);
$buttonChapter = Button::link('Capítulos')->asLinkTo($linkChapters);
$buttonCover = Button::link('Cover')->asLinkTo($linkCovers);
$buttonEdit = Button::link('Editar')->asLinkTo($linkEdit);
return "<ul class=\"list-inline\">" .
"<li>" . $anchorExport . "</li>" .
"<li>|</li>" .
"<li>" . $buttonChapter . "</li>" .
"<li>|</li>" .
"<li>" . $buttonCover . "</li>" .
"<li>|</li>" .
"<li>" . $buttonEdit . "</li>" .
"<li>|</li>" .
"<li>" . $anchorDestroy . "</li>" .
"</ul>" .
$deleteForm;
});
?>
{!! $table !!}
|
import numpy as np
def load_data():
data = np.loadtxt('input.csv', dtype='int32', delimiter=',')
return data
def find_noun_verb(data):
for noun in range(0, 100):
for verb in range(0, 100):
d = np.array(data, copy=True)
d[1] = noun
d[2] = verb
index = 0
while(True):
cmd = d[index * 4]
if cmd == 99:
break
else:
try:
in1 = d[index*4 + 1]
val1 = d[in1]
in2 = d[index*4 + 2]
val2 = d[in2]
out = d[index*4 + 3]
if cmd == 1:
d[out] = val1 + val2
elif cmd == 2:
d[out] = val1 * val2
except:
break
index += 1
print(f'noun={noun}, verb={verb}, total={d[0]}')
if d[0] == 19690720:
return noun, verb
def main():
data = load_data()
noun, verb = find_noun_verb(data)
print(f'noun={noun}, verb={verb}, total={100*noun + verb}')
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.