repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
hairyhenderson/rancheros
util/cutil.go
// +build linux package util /* #cgo LDFLAGS: -lmount -lblkid -luuid -lselinux #include<blkid/blkid.h> #include<libmount/libmount.h> #include<stdlib.h> */ import "C" import "unsafe" import ( "errors" ) func ResolveDevice(spec string) string { cSpec := C.CString(spec) defer C.free(unsafe.Pointer(cSpec)) cString := C.blkid_evaluate_spec(cSpec, nil) defer C.free(unsafe.Pointer(cString)) return C.GoString(cString) } func GetFsType(device string) (string, error) { var ambi *C.int cDevice := C.CString(device) defer C.free(unsafe.Pointer(cDevice)) cString := C.mnt_get_fstype(cDevice, ambi, nil) defer C.free(unsafe.Pointer(cString)) if cString != nil { return C.GoString(cString), nil } return "", errors.New("Error while getting fstype") } func intToBool(value C.int) bool { if value == 0 { return false } return true }
Indexical-Metrics-Measure-Advisory/watchmen
packages/watchmen-dqc/src/watchmen_dqc/monitor/rule/disabled_rules.py
<gh_stars>0 from typing import List from watchmen_model.dqc import MonitorRuleCode disabled_rules: List[MonitorRuleCode] = [ MonitorRuleCode.RAW_MISMATCH_STRUCTURE, # ignored now MonitorRuleCode.FACTOR_MISMATCH_DATE_TYPE, # should be detected on pipeline run MonitorRuleCode.FACTOR_USE_CAST, # should be detected on pipeline run MonitorRuleCode.FACTOR_BREAKS_MONOTONE_INCREASING, # ignored now MonitorRuleCode.FACTOR_BREAKS_MONOTONE_DECREASING # ignored now ]
drt4243566/leetcode_learn
niuke_HW/ds_zuo/8_11_wordDragon.cpp
<reponame>drt4243566/leetcode_learn #include <iostream> #include <string> #include <vector> #include <queue> using namespace std; int N; vector<string> words; char start; string connect(string preDragon, string back, int num) { return preDragon.substr(0, preDragon.size() - num) + back; } int isconnect(string preDragon, string back) { int maxL = min(preDragon.size() - 1, back.size() - 1); int dragonSize = preDragon.size(); for (int i = 0; i < maxL; i++) { int b = preDragon.substr(dragonSize - maxL + i, maxL - i) == back.substr(0, maxL - i); if (b) { return maxL - i; } } return 0; } int contain(string str1, string str2) { int L1 = str1.size(); int L2 = str2.size(); if (L2 > L1)return 0; if (str1.substr(L1 - L2, L2) == str2) { return 1; } return 0; } int isconnect2(string preDragon, string back) { int size1 = preDragon.size(); int size2 = back.size(); int size = 0; for (int i = 0; i < min(size1,size2); i++) { if (preDragon[size1 - 1] == back[i]) { for (int j = size1 - 1, k = i; j >= 0 && k >= 0; j--, k--) { if (preDragon[j] != back[k]) { return 0; } } size = i + 1; break; } } return size; } void process(string dragon, vector<int> visit, priority_queue<int> &res) { //int flag1 = 0; int flag2 = 0; for (int i = 0; i < N; i++) { if (visit[i] < 2) { //flag1 = 1; //cout<<dragon<<" "<<words[i]<<endl; //cout << "visit: " << words[i] << " visit=" << visit[i] << endl; int num = isconnect2(dragon, words[i]); if (num == words[i].size())num = 0; //cout<<"out"<<endl; if (num) { flag2 = 1; vector<int> tempv = visit; tempv[i]++; cout << endl; for (int k = 0; k < visit.size(); k++) { cout << words[k] << " visit:" << visit[k] << " "; } cout << endl; cout << "connect:" << dragon << "," << words[i] << ","<<num<<endl; string temp = connect(dragon, words[i], num); cout << "yesnect:"<<temp << endl; process(temp, tempv, res); //cout<<visit[i]<<" "; } } } if (flag2 == 0) { cout << "out --------->end:" << dragon << " size:"<<dragon.size()<<endl; res.push(dragon.size()); //cout<<dragon<<endl; } } int wordDragon(vector<int> visit) { if (N <= 0) { return 0; } priority_queue<int> res; for (int i = 0; i < N; i++) { if (words[i][0] == start and visit[i] < 2) { visit[i]++; cout << "enter-->" << words[i] << endl; process(words[i], visit, res); } } if (res.empty()) { return 0; } else { return res.top(); } } int main() { ///* cin >> N; vector<int> visit; for (int i = 0; i < N; i++) { string temp; cin >> temp; words.push_back(temp); visit.push_back(0); } cin >> start; cout << wordDragon(visit) << endl; system("pause"); //*/ //cout<<isconnect2("abababcdababa", "abababc"); cin.get(); return 0; }
ambadhan/OnlinePythonTutor
v4-cokapi/backends/c_cpp/valgrind-3.11.0/none/tests/tilegx/insn_test_tblidxb3_Y0.c
<filename>v4-cokapi/backends/c_cpp/valgrind-3.11.0/none/tests/tilegx/insn_test_tblidxb3_Y0.c //file: _insn_test_tblidxb3_Y0.c //op=232 #include <stdio.h> #include <stdlib.h> void func_exit(void) { printf("%s\n", __func__); exit(0); } void func_call(void) { printf("%s\n", __func__); exit(0); } unsigned long mem[2] = { 0xfd7000ecef4ffb36, 0xcf14c16c8fe6d80a }; int main(void) { unsigned long a[4] = { 0, 0 }; asm __volatile__ ( "moveli r29, 21338\n" "shl16insli r29, r29, -8055\n" "shl16insli r29, r29, -7131\n" "shl16insli r29, r29, 21377\n" "moveli r28, 11583\n" "shl16insli r28, r28, -32720\n" "shl16insli r28, r28, 17409\n" "shl16insli r28, r28, -25838\n" "{ tblidxb3 r29, r28 ; fnop ; ld r63, r54 }\n" "move %0, r29\n" "move %1, r28\n" :"=r"(a[0]),"=r"(a[1])); printf("%016lx\n", a[0]); printf("%016lx\n", a[1]); return 0; }
drxaos/JvmVM
src/test/java/com/github/drxaos/jvmvm/tests/interpretable/libtest/Dependent.java
package com.github.drxaos.jvmvm.tests.interpretable.libtest; public class Dependent { public static String test() { Dependency d = new Dependency(); d.addWord("Hello"); d.addWord("World"); d.addWord("!"); return "Dependent " + d.join(); } }
MewX/contendo-viewer-v1.6.3
org/apache/http/nio/protocol/Pipelined.java
package org.apache.http.nio.protocol; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Pipelined {} /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/http/nio/protocol/Pipelined.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
safe2008/learning-go
basics/03-Operators/Operators.go
package main import "fmt" func main() { var i int = 10 var k int = 20 var z int = 30 // Arithmetic Operators fmt.Printf("i + k = %d\n", i+k) fmt.Printf("i - k = %d\n", i-k) fmt.Printf("i * k = %d\n", i*k) fmt.Printf("i / k = %d\n", i/k) fmt.Printf("i mod k = %d\n", i%k) // Comparison Operators fmt.Println(i == k) fmt.Println(i != k) fmt.Println(i < k) fmt.Println(i <= k) fmt.Println(i > k) fmt.Println(i >= k) // Logical Operators fmt.Println(i < z && i > k) fmt.Println(i < z || i > k) fmt.Println(!(i == z && i > k)) // Assignment Operators var x, y = 15, 25 x = y fmt.Println("= ", x) x = 15 x += y fmt.Println("+=", x) x = 50 x -= y fmt.Println("-=", x) x = 2 x *= y fmt.Println("*=", x) x = 100 x /= y fmt.Println("/=", x) x = 40 x %= y fmt.Println("%=", x) }
li-boxuan/stargate
sgv2-dynamo-api/src/main/java/io/stargate/sgv2/dynamosvc/resources/DynamoResource.java
package io.stargate.sgv2.dynamosvc.resources; import static io.stargate.sgv2.dynamosvc.dynamo.Proxy.awsRequestMapper; import com.amazonaws.AmazonWebServiceResult; import com.amazonaws.services.dynamodbv2.model.CreateTableRequest; import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest; import com.amazonaws.services.dynamodbv2.model.GetItemRequest; import com.amazonaws.services.dynamodbv2.model.PutItemRequest; import com.amazonaws.services.dynamodbv2.model.QueryRequest; import com.codahale.metrics.annotation.Timed; import com.fasterxml.jackson.core.JsonProcessingException; import io.stargate.proto.QueryOuterClass; import io.stargate.sgv2.common.cql.builder.QueryBuilder; import io.stargate.sgv2.common.cql.builder.Replication; import io.stargate.sgv2.common.grpc.StargateBridgeClient; import io.stargate.sgv2.common.http.CreateStargateBridgeClient; import io.stargate.sgv2.dynamosvc.dynamo.ItemProxy; import io.stargate.sgv2.dynamosvc.dynamo.Proxy; import io.stargate.sgv2.dynamosvc.dynamo.QueryProxy; import io.stargate.sgv2.dynamosvc.dynamo.TableProxy; import io.stargate.sgv2.dynamosvc.models.DynamoStatementType; import io.swagger.annotations.*; import java.io.IOException; import java.util.Collections; import java.util.Map; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/") @Produces(MediaType.APPLICATION_JSON) @Api( produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON, tags = {"data"}) @ApiImplicitParams({ @ApiImplicitParam( name = "Authorization", paramType = "header", value = "The token returned from the authorization endpoint. Use this token in each request.", required = true) }) @CreateStargateBridgeClient public class DynamoResource { private static final Logger logger = LoggerFactory.getLogger(DynamoResource.class); private final TableProxy tableProxy; private final ItemProxy itemProxy; private final QueryProxy queryProxy; public DynamoResource(TableProxy tableProxy, ItemProxy itemProxy, QueryProxy queryProxy) { this.tableProxy = tableProxy; this.itemProxy = itemProxy; this.queryProxy = queryProxy; } @Timed @POST @Consumes("application/x-amz-json-1.0") @Produces("application/json") public Response handleRequest( @Context StargateBridgeClient bridge, @Context HttpHeaders headers, @HeaderParam("X-Amz-Target") String target, String payload) { target = target.split("\\.")[1]; DynamoStatementType statementType = DynamoStatementType.valueOf(target); byte[] response; try { AmazonWebServiceResult result; switch (statementType) { case CreateTable: CreateTableRequest createTableRequest = awsRequestMapper.readValue(payload, CreateTableRequest.class); result = tableProxy.createTable(createTableRequest, bridge); break; case DeleteTable: DeleteTableRequest deleteTableRequest = awsRequestMapper.readValue(payload, DeleteTableRequest.class); result = tableProxy.deleteTable(deleteTableRequest, bridge); break; case PutItem: PutItemRequest putItemRequest = awsRequestMapper.readValue(payload, PutItemRequest.class); result = itemProxy.putItem(putItemRequest, bridge); break; case GetItem: GetItemRequest getItemRequest = awsRequestMapper.readValue(payload, GetItemRequest.class); result = itemProxy.getItem(getItemRequest, bridge); break; case Query: QueryRequest queryRequest = awsRequestMapper.readValue(payload, QueryRequest.class); result = queryProxy.query(queryRequest, bridge); break; default: throw new WebApplicationException( "Invalid statement type: " + target, Response.Status.BAD_REQUEST); } response = awsRequestMapper.writeValueAsBytes(result); } catch (JsonProcessingException ex) { throw new WebApplicationException("Invalid payload", Response.Status.BAD_REQUEST); } catch (IOException ex) { throw new WebApplicationException( "An error occurred when connecting to Cassandra", Response.Status.INTERNAL_SERVER_ERROR); } catch (Exception ex) { throw new WebApplicationException(ex.getMessage(), Response.Status.INTERNAL_SERVER_ERROR); } return Response.status(Response.Status.OK).entity(response).build(); } @Timed @GET @Produces("application/json") @Path("/keyspace/create") public Response createKeyspace( @Context StargateBridgeClient bridge, @Context HttpHeaders headers) { QueryOuterClass.Query query = new QueryBuilder() .create() .keyspace(Proxy.KEYSPACE_NAME) .ifNotExists() .withReplication(Replication.simpleStrategy(1)) .build(); bridge.executeQuery(query); final Map<String, Object> responsePayload = Collections.singletonMap("name", Proxy.KEYSPACE_NAME); return Response.status(Response.Status.CREATED).entity(responsePayload).build(); } }
ScalablyTyped/SlinkyTyped
o/octokit__types/src/main/scala/typingsSlinky/octokitTypes/endpointsMod/AppsGetBySlugEndpoint.scala
<reponame>ScalablyTyped/SlinkyTyped package typingsSlinky.octokitTypes.endpointsMod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait AppsGetBySlugEndpoint extends StObject { var app_slug: String = js.native } object AppsGetBySlugEndpoint { @scala.inline def apply(app_slug: String): AppsGetBySlugEndpoint = { val __obj = js.Dynamic.literal(app_slug = app_slug.asInstanceOf[js.Any]) __obj.asInstanceOf[AppsGetBySlugEndpoint] } @scala.inline implicit class AppsGetBySlugEndpointMutableBuilder[Self <: AppsGetBySlugEndpoint] (val x: Self) extends AnyVal { @scala.inline def setApp_slug(value: String): Self = StObject.set(x, "app_slug", value.asInstanceOf[js.Any]) } }
Dongfang1021/Leetcode
k-th-smallest-prime-fraction/k-th-smallest-prime-fraction.py
class Solution: def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: from fractions import Fraction def under(x): count = best = 0 i = -1 for j in range(1, len(arr)): while arr[i + 1] < arr[j] * x: i += 1 count += i + 1 if i >= 0: best = max(best, Fraction(arr[i], arr[j])) return count, best low, high = 0.0, 1.0 while high - low > 1e-9: mid = (low + high) / 2.0 count, best = under(mid) if count < k: low = mid else: ans = best high = mid return ans.numerator, ans.denominator
faichele/NumCpp
docs/doxygen/html/median_8hpp.js
var median_8hpp = [ [ "median", "median_8hpp.html#ab2f8d43b44ab30c20a016e666c11f542", null ] ];
computestdev/computest-openrunner
lib/WebExtListeners.js
<gh_stars>10-100 'use strict'; const log = require('./logger')({MODULE: 'WebExtListeners'}); class WebExtListeners { constructor(api, thisObject = null) { this._api = api; this._thisObject = thisObject; this._cleanup = []; Object.freeze(this); } add(event, callback, ...args) { const emitter = this._api[event]; const thisObject = this._thisObject; const listenerCallback = (...args) => callback.apply(thisObject, args); emitter.addListener(listenerCallback, ...args); this._cleanup.push(() => emitter.removeListener(listenerCallback)); } cleanup() { for (const func of this._cleanup) { try { func(); } catch (err) { log.error({err}, 'Error removing listener'); } } this._cleanup.length = 0; } } module.exports = WebExtListeners;
berg-turing/point-framework
point-dal/src/test/java/io/github/bergturing/point/dal/constants/LockConstants.java
<reponame>berg-turing/point-framework package io.github.bergturing.point.dal.constants; public class LockConstants { /** * 单个实体锁分组 */ public static final String LOCK_GROUP_ENTITY = "point:dal:lock:test:entity:"; /** * 关联实体锁分组 */ public static final String LOCK_GROUP_ASSOCIATION = "point:dal:lock:test:association:"; /** * 常数锁分组 */ public static final String LOCK_GROUP_CONSTANTS = "point:dal:lock:test:constants:"; /** * 对属性加锁的服务对象 */ public static final String SERVICE_FIELD = "lockFieldService"; /** * 对方法加锁的服务对象 */ public static final String SERVICE_METHOD = "lockMethodService"; }
thomasgibson/firedrake-hybridization
profile_compressible_solver/plot_local_op_times.py
<gh_stars>0 import os import pandas as pd import seaborn as sns from matplotlib import pyplot as plt sns.set_context("talk") FONTSIZE = 14 MARKERSIZE = 10 LINEWIDTH = 3 cfl_range = [1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] rt0_ml_str_data = ["results/RT0_dx346km_dz156m_cfl%s_Hybrid_SCPC_fgmres_ml_richardson_stronger_data.csv" % cfl for cfl in cfl_range] rt1_ml_str_data = ["results/RT1_dx346km_dz156m_cfl%s_Hybrid_SCPC_fgmres_ml_richardson_stronger_data.csv" % cfl for cfl in cfl_range] bdfm1_ml_str_data = ["results/BDFM1_dx346km_dz156m_cfl%s_Hybrid_SCPC_fgmres_ml_richardson_stronger_data.csv" % cfl for cfl in cfl_range] for data in (rt0_ml_str_data + rt1_ml_str_data + bdfm1_ml_str_data): if not os.path.exists(data): import sys print("Cannot find data file: %s" % data) sys.exit(1) fig, (axes,) = plt.subplots(1, 1, figsize=(7, 5), squeeze=False) ax, = axes ax.set_ylim(0, 5) ax.xaxis.set_ticks_position("bottom") ax.yaxis.set_ticks_position("left") ax.set_xticks(cfl_range) ax.set_ylabel("Execution time (s)", fontsize=FONTSIZE+2) # Create data matrices rt0_ml_str_dfs = pd.concat(pd.read_csv(d) for d in rt0_ml_str_data) rt1_ml_str_dfs = pd.concat(pd.read_csv(d) for d in rt1_ml_str_data) bdfm1_ml_str_dfs = pd.concat(pd.read_csv(d) for d in bdfm1_ml_str_data) # Organize and group by CFL number rt0_ml_str_grps = rt0_ml_str_dfs.groupby(["horizontal_courant"], as_index=False) rt1_ml_str_grps = rt1_ml_str_dfs.groupby(["horizontal_courant"], as_index=False) bdfm1_ml_str_grps = bdfm1_ml_str_dfs.groupby(["horizontal_courant"], as_index=False) # RT0, fgmres + ML(richardson(5)) rt0_ml_str_cfls = [] rt0_ml_str_times = [] t_prev = 0.0 for group in rt0_ml_str_grps: cfl, df = group rt0_ml_str_cfls.append(cfl) time = df.back_sub + df.forward_elim rt0_ml_str_times.append(time - t_prev) t_prev = time # RT1, fgmres + ML(richardson(5)) rt1_ml_str_cfls = [] rt1_ml_str_times = [] t_prev = 0.0 for group in rt1_ml_str_grps: cfl, df = group rt1_ml_str_cfls.append(cfl) time = df.back_sub + df.forward_elim rt1_ml_str_times.append(time - t_prev) t_prev = time # BDFM1, fgmres + ML(richardson(5)) bdfm1_ml_str_cfls = [] bdfm1_ml_str_times = [] t_prev = 0.0 for group in bdfm1_ml_str_grps: cfl, df = group bdfm1_ml_str_cfls.append(cfl) time = df.back_sub + df.forward_elim bdfm1_ml_str_times.append(time - t_prev) t_prev = time ax.plot(rt0_ml_str_cfls, rt0_ml_str_times, label="$RT_0$", markersize=MARKERSIZE, linewidth=LINEWIDTH, color="k", marker="o", linestyle="solid") ax.plot(rt1_ml_str_cfls, rt1_ml_str_times, label="$RT_1$", markersize=MARKERSIZE, linewidth=LINEWIDTH, color="m", marker="^", linestyle="solid") ax.plot(bdfm1_ml_str_cfls, bdfm1_ml_str_times, label="$BDFM_1$", markersize=MARKERSIZE, linewidth=LINEWIDTH, color="g", marker="*", linestyle="solid") for tick in ax.get_xticklabels(): tick.set_fontsize(FONTSIZE) for tick in ax.get_yticklabels(): tick.set_fontsize(FONTSIZE) ax.grid(b=True, which='major', linestyle='-.') xlabel = fig.text(0.5, -0.15, "Horiz. CFL number\n $\\sqrt{\\frac{c_p T_0}{\\gamma}}\\frac{\\Delta t}{\\Delta x}$", ha='center', fontsize=FONTSIZE) title = fig.text(0.5, 0.9, "Local operation times", ha='center', fontsize=FONTSIZE) handles, labels = ax.get_legend_handles_labels() legend = fig.legend(handles, labels, loc=9, bbox_to_anchor=(0.5, 1.1), bbox_transform=fig.transFigure, ncol=3, handlelength=1.5, fontsize=FONTSIZE-2, numpoints=1, frameon=False) fig.savefig("cfl_vs_local_times.pdf", orientation="landscape", format="pdf", transparent=True, bbox_inches="tight", bbox_extra_artists=[xlabel, legend, title])
bluespeck/OakVR
src/LLAPI/Renderer/DirectX/DirectX11/DirectX11Renderer.h
<filename>src/LLAPI/Renderer/DirectX/DirectX11/DirectX11Renderer.h #pragma once #include "Renderer/Renderer/Renderer.h" #include "Math/Vector3.h" struct ID3D11Device; struct ID3D11DeviceContext; struct IDXGISwapChain; struct ID3D11RenderTargetView; struct ID3D11RasterizerState; struct ID3D11DepthStencilState; struct ID3D11Buffer; struct ID3D11SamplerState; struct ID3D11DepthStencilView; namespace oakvr { namespace render { class DirectX11Renderer : public Renderer { public: enum RasterizerStateIndex { eRSI_First = 0, eRSI_FillSolid_CullBack_FrontCCW = eRSI_First, eRSI_FillSolid_CullBack_FrontCW, eRSI_FillSolid_CullFront_FrontCCW, eRSI_FillSolid_CullFront_FrontCW, eRSI_FillWireframe_CullBack_FrontCCW, eRSI_FillWireframe_CullBack_FrontCW, eRSI_FillWireframe_CullFront_FrontCCW, eRSI_FillWireframe_CullFront_FrontCW, eRSI_Last = eRSI_FillWireframe_CullFront_FrontCW, eRSI_Count }; // constructors DirectX11Renderer(); // overrides virtual void Initialize(); virtual void Update( float dt ); virtual void Cleanup(); virtual void ClearBackground(const Color &color); virtual void SwapBuffers(); virtual void BeginDraw(); virtual void EndDraw(); virtual void DrawPrimitives(uint32_t numPrimitives, uint32_t startVertex = 0); virtual void DrawIndexedPrimitives(uint32_t numPrimitives, uint32_t numVertices = 0, uint32_t startIndex = 0, uint32_t startVertex = 0); virtual void CreateTexture ( Texture *texture ); virtual void ReleaseTexture ( Texture *texture ); virtual void UseTexture ( Texture *texture ); virtual void CreateVertexBuffer ( VertexBuffer *pVertexBuffer ); virtual void LockVertexBuffer ( VertexBuffer *pVertexBuffer, void **ppBuff, uint32_t offsetToLock = 0, uint32_t sizeToLock = 0, uint32_t flags = 0 ); virtual void UnlockVertexBuffer ( VertexBuffer *pVertexBuffer ); virtual void ReleaseVertexBuffer( VertexBuffer *pVertexBuffer ); virtual void UseVertexBuffer( VertexBuffer *pVertexBuffer ); virtual void CreateIndexBuffer ( IndexBuffer *ibuff ); virtual void LockIndexBuffer ( IndexBuffer *pIndexBuffer, void **ppBuff, uint32_t offsetToLock = 0, uint32_t sizeToLock = 0, uint32_t flags = 0 ); virtual void UnlockIndexBuffer ( IndexBuffer *pIndexBuffer ); virtual void ReleaseIndexBuffer ( IndexBuffer *pIndexBuffer ); virtual void UseIndexBuffer( IndexBuffer *pIndexBuffer ); virtual void UsePrimitiveTopology( PrimitiveTopology primitiveTopology ); virtual void CreateShader( Shader *pShader ); virtual void ReleaseShader( Shader *pShader ); virtual void UseShader( Shader *pShader ); virtual void OutputText( const std::string &text, uint32_t x, uint32_t y); virtual void EnableOrtographicProjection(); virtual void EnablePerspectiveProjection(); virtual void EnableDepthBuffer(); virtual void DisableDepthBuffer(); virtual void EnableFillWireframe(); virtual void EnableFillSolid(); virtual oakvr::math::Matrix CreateViewMatrix(oakvr::math::Vector3 eye, oakvr::math::Vector3 lookAt, oakvr::math::Vector3 up); // misc void CreateInputLayoutDesc( uint32_t vertexFormat, void *&pLayoutDesc, uint32_t &numElems ); void InitializeStateObjects(); void SetRasterizerState( RasterizerStateIndex rsi ); ID3D11Device *GetDevice() { return m_pDevice; } ID3D11DeviceContext *GetDeviceContext() { return m_pDeviceContext; } private: void SetMatrices(); private: IDXGISwapChain *m_pSwapChain; // the swap chain interface ID3D11Device *m_pDevice; // Direct3D device interface ID3D11DeviceContext *m_pDeviceContext; // Direct3D device context ID3D11RenderTargetView *m_pBackBufferRenderTargetView; ID3D11DepthStencilView *m_pDepthStencilView; // directx state objects ID3D11DepthStencilState *m_pDepthStencilStateDepthDisabled; ID3D11DepthStencilState *m_pDepthStencilStateDepthEnabled; ID3D11RasterizerState *m_pRasterizerStates[eRSI_Count]; ID3D11SamplerState *m_pSamplerState; ID3D11Buffer *m_pMatrixBuffer; bool m_bPerspectiveProjection; }; } // namespace render } // namespace oakvr
jiashiwen/redissyncer-server
syncer-transmission/src/main/java/syncer/transmission/client/jedis/ClusterNodesUtil.java
<filename>syncer-transmission/src/main/java/syncer/transmission/client/jedis/ClusterNodesUtil.java package syncer.transmission.client.jedis; /** * @author zhanenqiang * @Description 描述 * @Date 2020/12/24 */ import org.springframework.util.StringUtils; import syncer.jedis.HostAndPort; import syncer.jedis.Jedis; import java.util.*; /** * cluster Nodes 工具类,主要基于cluter nodes命令生成Cluster集群的内网外网映射表 * 解决内网搭建时 */ public class ClusterNodesUtil { public static boolean isExSet(Set<String> set, String tar){ if(set.contains(tar)){ return true; } return false; } /** * 构建映射表 * @param nodesMap * @param hostAndPorts * @param password */ public static void builderMap1(Map<String,String> nodesMap, Set<HostAndPort>hostAndPorts, String password){ Set<String>hostBSet=new HashSet<>(); for (HostAndPort hap:hostAndPorts ) { hostBSet.add(hap.getHost()); } for (HostAndPort hap:hostAndPorts ) { String oldHost=hap.getHost(); Jedis jedis=new Jedis(hap); if(!StringUtils.isEmpty(password)){ jedis.auth(password); } //连接获取每个redis节点 jedis.connect(); List<Object> slots = jedis.clusterSlots(); jedis.close(); //遍历每个地址 for(Object slotInfoObj:slots){ List<Object> slotInfo = (List<Object>) slotInfoObj; for (Object slot:slotInfo){ if(slot instanceof ArrayList){ List<Object>list= (List<Object>)slot; for (Object ii:list){ if(ii instanceof byte[]){ String hoty=new String((byte[]) ii); if(!isExSet(hostBSet,hoty)){ nodesMap.put(hoty,oldHost); }else { nodesMap.put(hoty,hoty); } break; } } } } } } } public static void builderMap(Map<String,String>nodesMap,Set<HostAndPort>hostAndPorts,String password){ Set<String>hostBSet=new HashSet<>(); for (HostAndPort hap:hostAndPorts ) { hostBSet.add(hap.getHost()); } for (HostAndPort hap:hostAndPorts ) { String oldHost=hap.getHost(); Jedis jedis=new Jedis(hap); if(!StringUtils.isEmpty(password)){ jedis.auth(password); } //连接获取每个redis节点 jedis.connect(); List<Object> slots = jedis.clusterSlots(); jedis.close(); String data=jedis.clusterNodes(); // System.out.println(data); List<String>addressList= Arrays.asList(data.split("\n")); //遍历每个地址 for (String address:addressList ) { try { String[]add=address.split(" "); String host=add[1].split(":")[0]; if(add[2].startsWith("myself")) { nodesMap.put(host, hap.getHost()); }else { nodesMap.put(host, host); } }catch (Exception e){ nodesMap.put(hap.getHost(), hap.getHost()); } } } } }
autonomous-interdependent-repositories/airport
libs/autopilot/lib/api/AutopilotApiLoader.js
import { AUTOPILOT_API_LOADER, DI, IOC } from '@airport/di'; import { LOCAL_API_CLIENT } from '../tokens'; export class AutopilotApiLoader { loadApiAutopilot(token) { return new Proxy({}, { get(target, methodName) { switch (methodName) { case '__initialized__': return true; case 'then': return target; } return function (...args) { return IOC.getSync(LOCAL_API_CLIENT) .invokeApiMethod(token, methodName, args); }; } }); } } DI.set(AUTOPILOT_API_LOADER, AutopilotApiLoader); //# sourceMappingURL=AutopilotApiLoader.js.map
loveweb58/React-Pro-Dashboard
architectui-react-pro/src/DemoPages/Components/ScrollableElements/Examples/index.js
<gh_stars>0 import React, {Component, Fragment} from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import { Row, Col, Card, CardBody, CardTitle, CardHeader, CardFooter } from 'reactstrap'; import bg1 from '../../../../assets/utils/images/dropdown-header/abstract1.jpg'; import bg2 from '../../../../assets/utils/images/dropdown-header/abstract2.jpg'; import bg3 from '../../../../assets/utils/images/dropdown-header/abstract3.jpg'; import { Button, UncontrolledButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem, Nav, NavItem, NavLink } from 'reactstrap'; import PerfectScrollbar from 'react-perfect-scrollbar'; import PageTitle from '../../../../Layout/AppMain/PageTitle'; class ScrollableElements extends Component { render() { return ( <Fragment> <ReactCSSTransitionGroup component="div" transitionName="TabsAnimation" transitionAppear={true} transitionAppearTimeout={0} transitionEnter={false} transitionLeave={false}> <Row> <Col lg="6"> <Card className="main-card mb-3"> <CardBody> <CardTitle>Medium Scrollable Area</CardTitle> <div className="scroll-area-md"> <PerfectScrollbar> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sodales ullamcorper vehicula. Duis placerat quam porta lorem lobortis, sit amet sodales mauris finibus. Donec posuere diam at volutpat viverra. Cras fringilla auctor augue sed congue. Maecenas mollis quis enim quis egestas. In sollicitudin mi a pretium varius. Integer eleifend sodales pharetra. Nullam vitae libero sem. Nulla et eros congue, tincidunt ante eu, tincidunt eros. Donec nisl purus, convallis a hendrerit ut, eleifend in lectus. Proin luctus dignissim lacus, in laoreet arcu eleifend non. Quisque viverra ipsum a massa porta convallis. Donec tincidunt imperdiet purus, interdum elementum ante commodo a. Quisque pharetra arcu sapien, vel ornare magna sollicitudin quis. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> </PerfectScrollbar> </div> </CardBody> </Card> <Card className="main-card mb-3"> <CardBody> <CardTitle>Large Scrollable Area</CardTitle> <div className="scroll-area-lg"> <PerfectScrollbar> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sodales ullamcorper vehicula. Duis placerat quam porta lorem lobortis, sit amet sodales mauris finibus. Donec posuere diam at volutpat viverra. Cras fringilla auctor augue sed congue. Maecenas mollis quis enim quis egestas. In sollicitudin mi a pretium varius. Integer eleifend sodales pharetra. Nullam vitae libero sem. Nulla et eros congue, tincidunt ante eu, tincidunt eros. Donec nisl purus, convallis a hendrerit ut, eleifend in lectus. Proin luctus dignissim lacus, in laoreet arcu eleifend non. Quisque viverra ipsum a massa porta convallis. Donec tincidunt imperdiet purus, interdum elementum ante commodo a. Quisque pharetra arcu sapien, vel ornare magna sollicitudin quis. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> </PerfectScrollbar> </div> </CardBody> </Card> </Col> <Col lg="6"> <Card className="main-card mb-3"> <CardBody> <CardTitle>Small Scrollable Area</CardTitle> <div className="scroll-area-sm"> <PerfectScrollbar> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sodales ullamcorper vehicula. Duis placerat quam porta lorem lobortis, sit amet sodales mauris finibus. Donec posuere diam at volutpat viverra. Cras fringilla auctor augue sed congue. Maecenas mollis quis enim quis egestas. In sollicitudin mi a pretium varius. Integer eleifend sodales pharetra. Nullam vitae libero sem. Nulla et eros congue, tincidunt ante eu, tincidunt eros. Donec nisl purus, convallis a hendrerit ut, eleifend in lectus. Proin luctus dignissim lacus, in laoreet arcu eleifend non. Quisque viverra ipsum a massa porta convallis. Donec tincidunt imperdiet purus, interdum elementum ante commodo a. Quisque pharetra arcu sapien, vel ornare magna sollicitudin quis. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> </PerfectScrollbar> </div> </CardBody> </Card> <Card className="main-card mb-3"> <CardBody> <CardTitle>Scrollable Dropdown Menus</CardTitle> <UncontrolledButtonDropdown> <DropdownToggle caret className="mb-2 mr-2" color="primary"> Bottom Header Buttons </DropdownToggle> <DropdownMenu className="dropdown-menu-lg"> <div className="dropdown-menu-header"> <div className="dropdown-menu-header-inner bg-primary"> <div className="menu-header-image" style={{ backgroundImage: 'url(' + bg1 + ')' }} /> <div className="menu-header-content"> <div> <h5 className="menu-header-title">Settings</h5> <h6 className="menu-header-subtitle">Manage all of your options</h6> </div> <div className="menu-header-btn-pane"> <Button size="sm" color="dark" className="mr-2"> Settings </Button> <Button size="sm" className="btn-icon btn-icon-only" color="warning"> <i className="pe-7s-config btn-icon-wrapper"> </i> </Button> </div> </div> </div> </div> <div className="scroll-area-xs"> <PerfectScrollbar> <Nav vertical> <NavItem className="nav-item-header"> Activity </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Chat <div className="ml-auto badge badge-pill badge-info">8 </div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);">Recover Password</NavLink> </NavItem> <NavItem className="nav-item-header"> My Account </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Settings <div className="ml-auto badge badge-success">New</div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Messages <div className="ml-auto badge badge-warning">512</div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Logs </NavLink> </NavItem> <NavItem className="nav-item-divider"/> <NavItem className="nav-item-btn"> <Button size="sm" className="btn-wide btn-shadow" color="danger"> Cancel </Button> </NavItem> </Nav> </PerfectScrollbar> </div> </DropdownMenu> </UncontrolledButtonDropdown> <UncontrolledButtonDropdown> <DropdownToggle caret color="success" className="mb-2 mr-2"> Left Aligned Header </DropdownToggle> <DropdownMenu className="dropdown-menu-lg"> <div className="dropdown-menu-header"> <div className="dropdown-menu-header-inner bg-success"> <div className="menu-header-image opacity-1" style={{ backgroundImage: 'url(' + bg3 + ')' }} /> <div className="menu-header-content text-left"> <h5 className="menu-header-title">Settings</h5> <h6 className="menu-header-subtitle">Manage all of your options</h6> <div className="menu-header-btn-pane"> <Button size="sm" color="dark" className="mr-2"> Settings </Button> <Button size="sm" className="btn-icon btn-icon-only" color="warning"> <i className="pe-7s-config btn-icon-wrapper"> </i> </Button> </div> </div> </div> </div> <div className="scroll-area-xs" style={{ height: '150px' }}> <PerfectScrollbar> <Nav vertical> <NavItem className="nav-item-header"> Activity </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Chat <div className="ml-auto badge badge-pill badge-info">8 </div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);">Recover Password</NavLink> </NavItem> <NavItem className="nav-item-header"> My Account </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Settings <div className="ml-auto badge badge-success">New</div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Messages <div className="ml-auto badge badge-warning">512</div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Logs </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Messages <div className="ml-auto badge badge-warning">512</div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Logs </NavLink> </NavItem> </Nav> </PerfectScrollbar> </div> <Nav vertical> <NavItem className="nav-item-divider"/> <NavItem className="nav-item-btn"> <Button size="sm" className="btn-wide btn-shadow" color="danger"> Cancel </Button> </NavItem> </Nav> </DropdownMenu> </UncontrolledButtonDropdown> <UncontrolledButtonDropdown> <DropdownToggle caret color="secondary" className="mb-2 mr-2"> Left Aligned Header Buttons </DropdownToggle> <DropdownMenu className="dropdown-menu-lg"> <div className="dropdown-menu-header"> <div className="dropdown-menu-header-inner bg-secondary"> <div className="menu-header-image opacity-5" style={{ backgroundImage: 'url(' + bg2 + ')' }} /> <div className="menu-header-content btn-pane-right"> <div> <h5 className="menu-header-title">Settings</h5> <h6 className="menu-header-subtitle">Manage all of your options</h6> </div> <div className="menu-header-btn-pane"> <Button size="sm" className="btn-icon btn-icon-only" color="warning"> <i className="pe-7s-config btn-icon-wrapper"> </i> </Button> </div> </div> </div> </div> <div className="scroll-area-xs"> <PerfectScrollbar> <Nav vertical> <NavItem className="nav-item-header"> Activity </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Chat <div className="ml-auto badge badge-pill badge-info">8 </div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);">Recover Password</NavLink> </NavItem> <NavItem className="nav-item-header"> My Account </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Settings <div className="ml-auto badge badge-success">New</div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Messages <div className="ml-auto badge badge-warning">512</div> </NavLink> </NavItem> <NavItem> <NavLink href="javascript:void(0);"> Logs </NavLink> </NavItem> <NavItem className="nav-item-divider"/> <NavItem> <NavLink href="javascript:void(0);"> Logs </NavLink> </NavItem> </Nav> </PerfectScrollbar> </div> <Nav vertical> <NavItem className="nav-item-divider"/> <NavItem className="nav-item-btn"> <Button size="sm" className="btn-wide btn-shadow" color="danger"> Cancel </Button> </NavItem> </Nav> </DropdownMenu> </UncontrolledButtonDropdown> </CardBody> </Card> <Card className="main-card mb-3"> <CardHeader> <i className="header-icon lnr-laptop-phone icon-gradient bg-plum-plate"> </i> Header Menu <div className="btn-actions-pane-right actions-icon-btn"> <Button className="btn-icon btn-icon-only" color="link"> <i className="pe-7s-leaf btn-icon-wrapper"/> </Button> <Button className="btn-icon btn-icon-only" color="link"> <i className="pe-7s-cloud-download btn-icon-wrapper"/> </Button> <UncontrolledButtonDropdown> <DropdownToggle className="btn-icon btn-icon-only" color="link"> <i className="pe-7s-menu btn-icon-wrapper"/> </DropdownToggle> <DropdownMenu className="dropdown-menu-right dropdown-menu-shadow dropdown-menu-hover-link"> <DropdownItem header>Header</DropdownItem> <DropdownItem> <i className="dropdown-icon lnr-inbox"> </i> <span>Menus</span> </DropdownItem> <DropdownItem> <i className="dropdown-icon lnr-file-empty"> </i> <span>Settings</span> </DropdownItem> <DropdownItem> <i className="dropdown-icon lnr-book"> </i> <span>Actions</span> </DropdownItem> <DropdownItem divider/> <div className="p-3 text-right"> <Button className="mr-2 btn-shadow btn-sm" color="link">View Details</Button> <Button className="mr-2 btn-shadow btn-sm" color="primary">Action</Button> </div> </DropdownMenu> </UncontrolledButtonDropdown> </div> </CardHeader> <CardBody> <div className="scroll-area-sm"> <PerfectScrollbar> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sodales ullamcorper vehicula. Duis placerat quam porta lorem lobortis, sit amet sodales mauris finibus. Donec posuere diam at volutpat viverra. Cras fringilla auctor augue sed congue. Maecenas mollis quis enim quis egestas. In sollicitudin mi a pretium varius. Integer eleifend sodales pharetra. Nullam vitae libero sem. Nulla et eros congue, tincidunt ante eu, tincidunt eros. Donec nisl purus, convallis a hendrerit ut, eleifend in lectus. Proin luctus dignissim lacus, in laoreet arcu eleifend non. Quisque viverra ipsum a massa porta convallis. Donec tincidunt imperdiet purus, interdum elementum ante commodo a. Quisque pharetra arcu sapien, vel ornare magna sollicitudin quis. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> <p> Nunc congue magna eget eros blandit, eu viverra magna semper. Nullam in diam a metus dictum consequat. Quisque ultricies, ipsum non euismod semper, velit felis lacinia nibh, et finibus quam leo vitae nisi. Maecenas interdum diam quis risus bibendum, eu fermentum est pharetra. In dictum at enim pretium bibendum. Praesent efficitur iaculis dolor in sodales. Morbi maximus in ipsum in malesuada. Proin semper lacus tempor magna aliquam, sed aliquam dui scelerisque. Donec nisi nulla, rhoncus a tristique eget, ultrices vitae dolor. Ut id urna vitae ante tincidunt pharetra at non metus. Nunc in suscipit nulla. Sed vitae leo vulputate, euismod tortor vel, aliquet velit. Curabitur eget tincidunt elit. Nam et ligula finibus, eleifend velit et, commodo quam. Praesent non libero velit. </p> </PerfectScrollbar> </div> </CardBody> <CardFooter className="d-block text-right"> <Button size="sm" className="mr-2" color="link">Cancel</Button> <Button size="lg" color="success">Save</Button> </CardFooter> </Card> </Col> </Row> </ReactCSSTransitionGroup> </Fragment> ); } }; export default ScrollableElements;
mulesoft/amf
amf-api-contract/shared/src/main/scala/amf/apicontract/internal/annotations/InvalidBinding.scala
package amf.apicontract.internal.annotations import amf.core.client.scala.model.domain.{AmfElement, Annotation, AnnotationGraphLoader, SerializableAnnotation} case class InvalidBinding(value: String) extends SerializableAnnotation { override val name: String = "invalid-binding" } object InvalidBinding extends AnnotationGraphLoader { override def unparse(value: String, objects: Map[String, AmfElement]): Option[Annotation] = Some(InvalidBinding(value)) }
blackgeorge-boom/algorithms_data_structures
Chapter_15/cut_stick.cpp
<reponame>blackgeorge-boom/algorithms_data_structures<filename>Chapter_15/cut_stick.cpp<gh_stars>0 // // Created by blackgeorge on 1/9/19. // #include <climits> #include <algorithm> #include <iostream> #include <ctime> int cut_stick_naive(int p[], int n) { if (n == 0) return 0; auto q = INT_MIN; for (auto i = 1; i <= n; ++i) q = std::max(q, p[i] + cut_stick_naive(p, n - i)); return q; } int cut_stick_memo_aux(int p[], int n, int r[]) { if (r[n] >= 0) return r[n]; int q; if (n == 0) q = 0; else { q = INT_MIN; for (auto i = 1; i <= n; ++i) q = std::max(q, p[i] + cut_stick_memo_aux(p, n - i, r)); } r[n] = q; return q; } int cut_stick_memo(int p[], int n) { int r[n + 1]; std::fill_n(r, n + 1, INT_MIN); return cut_stick_memo_aux(p, n, r); } int cut_stick_bottom_up(int p[], int n) { int r[n + 1]; r[0] = 0; int q; for (auto j = 1; j <= n; ++j) { q = INT_MIN; for (auto i = 1; i <= j; ++i) q = std::max(q, p[i] + r[j - i]); r[j] = q; } return r[n]; } int main() { int N; // N = 11; // int p[N] = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; N = 30; int p[N] = {10}; std::clock_t start; std::cout << "Naive approach: \n"; start = std::clock(); for (auto i = 1; i < N; i++) { std::cout << 'r' << i << " = " << cut_stick_naive(p, i) << '\n'; } std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl; std::cout << "Memoization approach: \n"; start = std::clock(); for (auto i = 1; i < N; i++) { std::cout << 'r' << i + 1 << " = " << cut_stick_memo(p, i) << '\n'; } std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl; std::cout << "Bottom-up approach: \n"; start = std::clock(); for (auto i = 1; i < N; i++) { std::cout << 'r' << i + 1 << " = " << cut_stick_bottom_up(p, i) << '\n'; } std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl; }
fishstormX/fishmaple
src/test/java/fishmaple/BinaryTreeNode.java
package fishmaple; import javax.swing.tree.TreeNode; import java.util.ArrayList; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class BinaryTreeNode { //二叉树的个种子遍历 public BinaryTreeNode root; BinaryTreeNode(Integer integer){ this.value=integer; } public BinaryTreeNode createTree(Integer nt){ this.root=new BinaryTreeNode(nt); return root; } BinaryTreeNode left; BinaryTreeNode right; Integer value; BinaryTreeNode(){ } private ArrayList<Integer> list=new ArrayList<Integer>(200); public void readTree(BinaryTreeNode node,int p){ for(int i=0;i<100;i++){ list.add(-1); } list.set(p,node.value); if(node.left!=null){ readTree(node.left,p*2); } if(node.right!=null){ readTree(node.right,p*2+1); } } Queue<Integer> q= new ArrayBlockingQueue<Integer>(20); public void getCeng(BinaryTreeNode node){ Queue<BinaryTreeNode> queue= new ArrayBlockingQueue<>(20); queue.add(node); while(!queue.isEmpty()){ node=queue.poll(); System.out.println(node.value); if(node.left!=null){ queue.add(node.left); } if(node.right!=null){ queue.add(node.right); } } } public void getList(){ for(Integer i:list){ System.out.print(i+" "); } } public void preorder(BinaryTreeNode root){ if(root!=null){ System.out.print(root.value+" "); preorder(root.left); preorder(root.right); } } /*//中序遍历 public void inorder(BinTree root){ if(root!=null){ inorder(root.lChild); visit(root.getData()); inorder(root.rChild); } } //后序遍历 public void afterorder(BinTree root){ if(root!=null){ afterorder(root.lChild); afterorder(root.rChild); visit(root.getData()); } }*/ public static void main(String args[]){ BinaryTreeNode bTree=new BinaryTreeNode(1); // bTree=bTree.createTree(1); //bTree.createTree(1); bTree.left=new BinaryTreeNode(3); bTree.right=new BinaryTreeNode(8); bTree.left.left=new BinaryTreeNode(4); bTree.left.left.left=new BinaryTreeNode(6); bTree.left.left.right=new BinaryTreeNode(12); // bTree.preorder(bTree); //bTree.readTree(bTree,1); //bTree.getList(); bTree.getCeng(bTree); } }
bchandle/cogexmachina
src/main/scala/cogx/compiler/gpu_operator/statement/WriteTensor.scala
/* * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 cogx.compiler.gpu_operator.statement import cogx.compiler.gpu_operator.expression.GPUExpression import cogx.compiler.gpu_operator.types.OutFieldIndex import cogx.platform.types.FieldType /** Statement to write a tensor in an output field. * * @param index Index of the output field to be written. * @param value The tensor value to be written. */ private[gpu_operator] class WriteTensor(val index: OutFieldIndex, value: GPUExpression) extends WriteStatement { constructed() /** Generate a string that implements the write statement. * * @param outputFieldType Type of the output field being written. * @return String for write statement */ def toString(outputFieldType: FieldType): String = { require(outputFieldType != null) // Block illegal threads from writing "out of bounds" val buffer = new StringBuffer val protection: String = outputFieldType.dimensions match { case 3 => "if (_layer < _layers &&_row < _rows && _column < _columns) " case 2 => "if (_row < _rows && _column < _columns) " case 1 => "if (_column < _columns) " case 0 => "" } buffer append protection buffer append "_writeTensorLocal" + index.index + " = " + value.exprString buffer.toString } }
pavlopoul/vxquery
vxquery-core/src/main/java/org/apache/vxquery/metadata/VXQueryIndexingOperatorDescriptor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.vxquery.metadata; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import java.util.logging.Logger; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.api.comm.IFrame; import org.apache.hyracks.api.comm.IFrameFieldAppender; import org.apache.hyracks.api.comm.VSizeFrame; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.IOperatorNodePushable; import org.apache.hyracks.api.dataflow.value.IRecordDescriptorProvider; import org.apache.hyracks.api.dataflow.value.RecordDescriptor; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.api.job.IOperatorDescriptorRegistry; import org.apache.hyracks.data.std.api.IPointable; import org.apache.hyracks.data.std.util.ArrayBackedValueStorage; import org.apache.hyracks.dataflow.common.comm.io.FrameFixedFieldTupleAppender; import org.apache.hyracks.dataflow.common.comm.io.FrameTupleAccessor; import org.apache.hyracks.dataflow.common.comm.util.FrameUtils; import org.apache.hyracks.dataflow.std.base.AbstractSingleActivityOperatorDescriptor; import org.apache.hyracks.dataflow.std.base.AbstractUnaryInputUnaryOutputOperatorNodePushable; import org.apache.vxquery.datamodel.accessors.TaggedValuePointable; import org.apache.vxquery.datamodel.values.XDMConstants; import org.apache.vxquery.exceptions.SystemException; import org.apache.vxquery.functions.BuiltinFunctions; import org.apache.vxquery.runtime.functions.index.IndexConstructorUtil; import org.apache.vxquery.runtime.functions.index.VXQueryIndexReader; import org.apache.vxquery.runtime.functions.index.centralizer.IndexCentralizerUtil; import org.apache.vxquery.runtime.functions.index.update.IndexUpdater; import org.apache.vxquery.xmlparser.ITreeNodeIdProvider; import org.apache.vxquery.xmlparser.TreeNodeIdProvider; public class VXQueryIndexingOperatorDescriptor extends AbstractSingleActivityOperatorDescriptor { protected static final Logger LOGGER = Logger.getLogger(VXQueryCollectionOperatorDescriptor.class.getName()); private static final long serialVersionUID = 1L; private short dataSourceId; private short totalDataSources; private String[] collectionPartitions; private final String functionCall; private List<Integer> childSeq; private List<Integer> indexChildSeq; private List<Integer> indexAttsSeq; private List<Byte[]> indexSeq; public VXQueryIndexingOperatorDescriptor(IOperatorDescriptorRegistry spec, VXQueryIndexingDataSource ds, RecordDescriptor rDesc) { super(spec, 1, 1); this.functionCall = ds.getFunctionCall(); collectionPartitions = ds.getPartitions(); dataSourceId = (short) ds.getDataSourceId(); totalDataSources = (short) ds.getTotalDataSources(); recordDescriptors[0] = rDesc; childSeq = ds.getChildSeq(); indexChildSeq = ds.getIndexChildSeq(); indexAttsSeq = ds.getIndexAttsSeq(); indexSeq = ds.getIndexValueSeq(); } @Override public IOperatorNodePushable createPushRuntime(IHyracksTaskContext ctx, IRecordDescriptorProvider recordDescProvider, int partition, int nPartitions) throws HyracksDataException { final FrameTupleAccessor fta = new FrameTupleAccessor( recordDescProvider.getInputRecordDescriptor(getActivityId(), 0)); final int fieldOutputCount = recordDescProvider.getOutputRecordDescriptor(getActivityId(), 0).getFieldCount(); final IFrame frame = new VSizeFrame(ctx); final IFrameFieldAppender appender = new FrameFixedFieldTupleAppender(fieldOutputCount); final short partitionId = (short) ctx.getTaskAttemptId().getTaskId().getPartition(); final ITreeNodeIdProvider nodeIdProvider = new TreeNodeIdProvider(partitionId, dataSourceId, totalDataSources); final String nodeId = ctx.getJobletContext().getApplicationContext().getNodeId(); final String collectionName = collectionPartitions[partition % collectionPartitions.length]; final String collectionModifiedName = collectionName.replace("${nodeId}", nodeId); IndexCentralizerUtil indexCentralizerUtil = new IndexCentralizerUtil( ctx.getIOManager().getIODevices().get(0).getMount()); indexCentralizerUtil.readIndexDirectory(); final IPointable result = (TaggedValuePointable) TaggedValuePointable.FACTORY.createPointable(); return new AbstractUnaryInputUnaryOutputOperatorNodePushable() { @Override public void open() throws HyracksDataException { appender.reset(frame, true); writer.open(); } @Override public void nextFrame(ByteBuffer buffer) throws HyracksDataException { fta.reset(buffer); final ArrayBackedValueStorage abvs = new ArrayBackedValueStorage(); final ArrayBackedValueStorage abvsFileNode = new ArrayBackedValueStorage(); abvs.reset(); abvsFileNode.reset(); if (collectionModifiedName.contains("hdfs://")) { throw new HyracksDataException("Indexing support for HDFS not yet implemented."); } else { if (functionCall.equals( BuiltinFunctions.FN_BUILD_INDEX_ON_COLLECTION_1.getFunctionIdentifier().getName())) { try { createIndex(result, abvs, abvsFileNode); } catch (IOException e) { throw new HyracksDataException(e); } } else if (functionCall .equals(BuiltinFunctions.FN_UPDATE_INDEX_1.getFunctionIdentifier().getName())) { updateIndex(result, abvs, abvsFileNode); } else if (functionCall .equals(BuiltinFunctions.FN_DELETE_INDEX_1.getFunctionIdentifier().getName())) { deleteIndex(result, abvs, abvsFileNode); } else if (functionCall .equals(BuiltinFunctions.FN_COLLECTION_FROM_INDEX_1.getFunctionIdentifier().getName()) || functionCall .equals(BuiltinFunctions.FN_COLLECTION_1.getFunctionIdentifier().getName())) { usingIndex(result); } else { throw new HyracksDataException("Unsupported function call (" + functionCall + ")"); } } } public void createIndex(IPointable result, ArrayBackedValueStorage abvs, ArrayBackedValueStorage abvsFileNode) throws IOException { String indexModifiedName = indexCentralizerUtil.putIndexForCollection(collectionModifiedName); File collectionDirectory = new File(collectionModifiedName); //check if directory is in the local file system if (collectionDirectory.exists() && collectionDirectory.isDirectory()) { IndexConstructorUtil indexConstructorUtil = new IndexConstructorUtil(); try { indexConstructorUtil.evaluate(collectionModifiedName, indexModifiedName, result, abvs, nodeIdProvider, abvsFileNode, false, nodeId); XDMConstants.setTrue(result); FrameUtils.appendFieldToWriter(writer, appender, result.getByteArray(), result.getStartOffset(), result.getLength()); } catch (SystemException e) { throw new HyracksDataException("Could not create index for collection: " + collectionName + " in dir: " + indexModifiedName + " " + e.getMessage(), e); } } else { throw new HyracksDataException("Cannot find Collection Directory (" + nodeId + ":" + collectionDirectory.getAbsolutePath() + ")"); } } public void updateIndex(IPointable result, ArrayBackedValueStorage abvs, ArrayBackedValueStorage abvsFileNode) throws HyracksDataException { String indexModifiedName = indexCentralizerUtil.getIndexForCollection(collectionModifiedName); IndexUpdater updater = new IndexUpdater(indexModifiedName, result, abvs, nodeIdProvider, abvsFileNode, nodeId); try { updater.setup(); updater.updateIndex(); updater.updateMetadataFile(); updater.exit(); XDMConstants.setTrue(result); FrameUtils.appendFieldToWriter(writer, appender, result.getByteArray(), result.getStartOffset(), result.getLength()); } catch (IOException e) { throw new HyracksDataException( "Could not update index in " + indexModifiedName + " " + e.getMessage(), e); } } public void deleteIndex(IPointable result, ArrayBackedValueStorage abvs, ArrayBackedValueStorage abvsFileNode) throws HyracksDataException { String indexModifiedName = indexCentralizerUtil.getIndexForCollection(collectionModifiedName); IndexUpdater updater = new IndexUpdater(indexModifiedName, result, abvs, nodeIdProvider, abvsFileNode, nodeId); indexCentralizerUtil.deleteEntryForCollection(collectionModifiedName); try { updater.setup(); updater.deleteAllIndexes(); XDMConstants.setTrue(result); FrameUtils.appendFieldToWriter(writer, appender, result.getByteArray(), result.getStartOffset(), result.getLength()); } catch (IOException e) { throw new HyracksDataException( "Could not delete index in " + indexModifiedName + " " + e.getMessage(), e); } } public void usingIndex(IPointable result) throws HyracksDataException { String indexModifiedName = indexCentralizerUtil.getIndexForCollection(collectionModifiedName); VXQueryIndexReader indexReader = new VXQueryIndexReader(ctx, indexModifiedName, childSeq, indexChildSeq, indexAttsSeq, indexSeq, appender); try { indexReader.init(); for (int tupleIndex = 0; tupleIndex < fta.getTupleCount(); ++tupleIndex) { while (indexReader.step(result, writer, tupleIndex)) { } } } catch (AlgebricksException e) { throw new HyracksDataException("Could not read index.", e); } } @Override public void fail() throws HyracksDataException { writer.fail(); } @Override public void close() throws HyracksDataException { // Check if needed? if (appender.getTupleCount() > 0) { appender.flush(writer); } writer.close(); indexCentralizerUtil.writeIndexDirectory(); } }; } }
ZiOS-Repo/IU_RTImagePicker
Example/Pods/DoraemonKit/iOS/DoraemonKit/Src/Core/Plugin/Common/NSUserDefaults/ViewControllers/DoraemonNSUserDefaultsViewController.h
// // DoraemonNSUserDefaultsViewController.h // DoraemonKit // // Created by 0xd-cc on 2019/11/26. // #import <UIKit/UIKit.h> #import "DoraemonBaseViewController.h" NS_ASSUME_NONNULL_BEGIN @interface DoraemonNSUserDefaultsViewController : DoraemonBaseViewController @end NS_ASSUME_NONNULL_END
icedreamer/test
src/com/tlys/sys/model/job/TimerJob.java
<reponame>icedreamer/test<filename>src/com/tlys/sys/model/job/TimerJob.java package com.tlys.sys.model.job; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.Job; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class TimerJob implements Job { final static Log logger = LogFactory.getLog(TimerJob.class); Object object = null; Method method = null; public void execute(JobExecutionContext ctx) throws JobExecutionException { // TODO Auto-generated method stub if (object == null) { JobDetail jobDetail = ctx.getJobDetail(); TimerTask timerTask = (TimerTask) jobDetail.getJobDataMap().get( TimerTask.class.getName()); object = timerTask.getObject(); method = timerTask.getMethod(); } try { method.invoke(object); } catch (Exception e) { logger.error("invote fail!", e); } } }
deadzq/facecat
facecat_cpp/source/date/DayDiv.cpp
<filename>facecat_cpp/source/date/DayDiv.cpp #include "..\\..\\stdafx.h" #include "..\\..\\include\\date\\DayDiv.h" namespace FaceCat{ DayDiv::DayDiv(FCCalendar *calendar){ m_am_ClickRowFrom = 0; m_am_ClickRowTo = 0; m_am_Direction = 0; m_am_Tick = 0; m_am_TotalTick = 40; m_calendar = calendar; onLoad(); } DayDiv::~DayDiv(){ m_calendar = 0; m_dayButtons.clear(); m_dayButtons_am.clear(); } FCCalendar* DayDiv::getCalendar(){ return m_calendar; } void DayDiv::setCalendar(FCCalendar *calendar){ m_calendar = calendar; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DayDiv::hide(){ int dayButtonSize = (int)m_dayButtons.size(); for(int i = 0; i < dayButtonSize; i++){ DayButton *dayButton = m_dayButtons.get(i); dayButton->setVisible(false); } } void DayDiv::onClick(FCTouchInfo touchInfo){ FCPoint mp = touchInfo.m_firstPoint; int dayButtonsSize = (int)m_dayButtons.size(); for (int i = 0; i < dayButtonsSize; i++){ DayButton *dayButton = m_dayButtons.get(i); if (dayButton->isVisible()){ FCRect bounds = dayButton->getBounds(); if (mp.x >= bounds.left && mp.x <= bounds.right && mp.y >= bounds.top && mp.y <= bounds.bottom){ dayButton->onClick(touchInfo); return; } } } int dayFCButtonmSize = (int)m_dayButtons_am.size(); for (int i = 0; i < dayFCButtonmSize; i++){ DayButton *dayButton = m_dayButtons_am.get(i); if (dayButton->isVisible()){ FCRect bounds = dayButton->getBounds(); if (mp.x >= bounds.left && mp.x <= bounds.right && mp.y >= bounds.top && mp.y <= bounds.bottom){ dayButton->onClick(touchInfo); return; } } } } void DayDiv::onLoad(){ if (m_calendar){ if(m_dayButtons.size() == 0 || m_dayButtons_am.size() == 0){ m_dayButtons.clear(); m_dayButtons_am.clear(); FCHost *host = m_calendar->getNative()->getHost(); for (int i = 0; i < 42; i++){ DayButton *dayButton = new DayButton(m_calendar); m_dayButtons.add(dayButton); DayButton *dayFCButtonm = new DayButton(m_calendar); dayFCButtonm->setVisible(false); m_dayButtons_am.add(dayFCButtonm); } } } } void DayDiv::onPaint(FCPaint *paint, const FCRect& clipRect){ int dayButtonsSize = (int)m_dayButtons.size(); for (int i = 0; i < dayButtonsSize; i++){ DayButton *dayButton = m_dayButtons.get(i); if (dayButton->isVisible()){ FCRect bounds = dayButton->getBounds(); dayButton->onPaintBackGround(paint, bounds); dayButton->onPaintForeground(paint, bounds); dayButton->onPaintBorder(paint, bounds); } } int dayFCButtonmSize = (int)m_dayButtons_am.size(); for (int i = 0; i < dayFCButtonmSize; i++){ DayButton *dayButton = m_dayButtons_am.get(i); if (dayButton->isVisible()){ FCRect bounds = dayButton->getBounds(); dayButton->onPaintBackGround(paint, bounds); dayButton->onPaintForeground(paint, bounds); dayButton->onPaintBorder(paint, bounds); } } } void DayDiv::onResetDiv(int state){ if(m_calendar){ CMonth *thisMonth = m_calendar->getMonth(); CMonth *lastMonth = m_calendar->getLastMonth(thisMonth->getYear(), thisMonth->getMonth()); CMonth *nextMonth = m_calendar->getNextMonth(thisMonth->getYear(), thisMonth->getMonth()); int left = 0; int headHeight = m_calendar->getHeadDiv()->getBottom(); int top = headHeight; int width = m_calendar->getWidth(); int height = m_calendar->getHeight(); height -= m_calendar->getTimeDiv()->getHeight(); int dayButtonHeight = height - headHeight; if (dayButtonHeight < 1) dayButtonHeight = 1; int subH = 0, toY = 0; if (m_am_Direction == 1){ subH = (6 - (m_am_ClickRowTo - m_am_ClickRowFrom)) * (dayButtonHeight / 6); toY = -height + subH + headHeight; toY = toY * m_am_Tick / m_am_TotalTick; if(state == 1){ thisMonth = nextMonth; lastMonth = m_calendar->getLastMonth(thisMonth->getYear(), thisMonth->getMonth()); nextMonth = m_calendar->getNextMonth(thisMonth->getYear(), thisMonth->getMonth()); } } else if(m_am_Direction == 2){ subH = (6 - (m_am_ClickRowFrom - m_am_ClickRowTo)) * (dayButtonHeight / 6); toY = height - subH - headHeight; toY = toY * m_am_Tick / m_am_TotalTick; if(state == 1){ thisMonth = lastMonth; lastMonth = m_calendar->getLastMonth(thisMonth->getYear(), thisMonth->getMonth()); nextMonth = m_calendar->getNextMonth(thisMonth->getYear(), thisMonth->getMonth()); } } int buttonSize = 0; if(state == 0){ buttonSize = (int)m_dayButtons.size(); } else if(state == 1){ buttonSize = (int)m_dayButtons_am.size(); } int dheight = dayButtonHeight / 6; HashMap<int, CDay*> days = thisMonth->m_days; CDay *firstDay = days.get(1); int startDayOfWeek = m_calendar->dayOfWeek(firstDay->getYear(), firstDay->getMonth(), firstDay->getDay()); int todayYear = 0; int todayMonth = 0; int todayDay = 0; int i = 0; for (; i < buttonSize; i++){ DayButton *dayButton = 0; if(state == 0){ dayButton = m_dayButtons.get(i); buttonSize = (int)m_dayButtons.size(); } else if(state == 1){ dayButton = m_dayButtons_am.get(i); buttonSize = (int)m_dayButtons_am.size(); } if (i == 35){ dheight = height - top; } int vOffset = 0; if(state == 1){ if(m_am_Tick > 0){ dayButton->setVisible(true); if(m_am_Direction == 1){ vOffset = toY + dayButtonHeight; } else if(m_am_Direction == 2){ vOffset = toY - dayButtonHeight; } } else{ dayButton->setVisible(false); continue; } } else{ vOffset = toY; } if ((i + 1) % 7 == 0){ FCPoint dp = {left, top + vOffset}; FCSize ds = {width - left, dheight}; FCRect bounds = {dp.x, dp.y, dp.x + ds.cx, dp.y + ds.cy}; dayButton->setBounds(bounds); left = 0; if (i != 0 && i != buttonSize - 1){ top += dheight; } } else{ FCPoint dp = {left, top + vOffset}; FCSize ds = {width / 7 + ((i + 1) % 7) % 2, dheight}; FCRect bounds = {dp.x, dp.y, dp.x + ds.cx, dp.y + ds.cy}; dayButton->setBounds(bounds); left += ds.cx; } CDay *cDay = 0; dayButton->setThisMonth(false); if (i >= startDayOfWeek && i <= startDayOfWeek + (int)days.size() - 1){ cDay = days.get(i - startDayOfWeek + 1); dayButton->setThisMonth(true); } else if (i < startDayOfWeek){ cDay = lastMonth->m_days.get((int)lastMonth->m_days.size() - startDayOfWeek + i + 1); } else if (i > startDayOfWeek + (int)days.size() - 1){ cDay = nextMonth->m_days.get(i - startDayOfWeek - (int)days.size() + 1); } dayButton->setDay(cDay); if (state == 0 && dayButton->getDay() && dayButton->getDay() == m_calendar->getSelectedDay()){ dayButton->setSelected(true); } else{ dayButton->setSelected(false); } } } } void DayDiv::onTimer(){ if (m_am_Tick > 0){ m_am_Tick = (int)((double)m_am_Tick * 2 / 3); if(m_calendar){ m_calendar->update(); m_calendar->invalidate(); } } } void DayDiv::selectDay(CDay* selectedDay){ if(m_calendar){ CMonth *m = m_calendar->getYears()->getYear(selectedDay->getYear())->Months.get(selectedDay->getMonth()); CMonth *thisMonth = m_calendar->getMonth(); if(m != thisMonth){ if (thisMonth->getYear() * 12 + thisMonth->getMonth() > m->getYear() * 12 + m->getMonth()){ m_am_Direction = 1; } else{ m_am_Direction = 2; } int i = 0; int buttonSize = (int)m_dayButtons.size(); for (i = 0;i < buttonSize; i++){ DayButton *dayButton = m_dayButtons.get(i); if ((m_am_Direction == 1 && dayButton->getDay() == thisMonth->getFirstDay()) || m_am_Direction == 2 && dayButton->getDay() == thisMonth->getLastDay()){ m_am_ClickRowFrom = i / 7; if (i % 7 != 0){ m_am_ClickRowFrom += 1; } } } m_calendar->setMonth(m); onResetDiv(0); buttonSize = (int)m_dayButtons_am.size(); for (i = 0; i < buttonSize; i++){ DayButton *dayFCButtonm = m_dayButtons_am.get(i); if ((m_am_Direction == 1 && dayFCButtonm->getDay() == m->getLastDay()) || (m_am_Direction == 2 && dayFCButtonm->getDay() == m->getFirstDay())){ m_am_ClickRowTo = i / 7; if (i % 7 != 0){ m_am_ClickRowTo += 1; } } } if(m_calendar->useAnimation()){ m_am_Tick = m_am_TotalTick; } } else{ int dayButtonsSize = m_dayButtons.size(); for(int i = 0; i < dayButtonsSize; i++){ DayButton *dayButton = m_dayButtons.get(i); if(dayButton->getDay() != selectedDay){ dayButton->setSelected(false); } } m_calendar->setMonth(m); } } } void DayDiv::show(){ int dayButtonSize = (int)m_dayButtons.size(); for(int i = 0; i < dayButtonSize; i++){ DayButton *dayButton = m_dayButtons.get(i); dayButton->setVisible(true); } } void DayDiv::update(){ onResetDiv(0); onResetDiv(1); } }
felixshiftellecon/lets-go-snippetbox
node_modules/cli-truncate/index.js
<reponame>felixshiftellecon/lets-go-snippetbox 'use strict'; const sliceAnsi = require('slice-ansi'); const stringWidth = require('string-width'); function getIndexOfNearestSpace(string, index, shouldSearchRight) { if (string.charAt(index) === ' ') { return index; } for (let i = 1; i <= 3; i++) { if (shouldSearchRight) { if (string.charAt(index + i) === ' ') { return index + i; } } else if (string.charAt(index - i) === ' ') { return index - i; } } return index; } module.exports = (text, columns, options) => { options = { position: 'end', preferTruncationOnSpace: false, ...options }; const {position, space, preferTruncationOnSpace} = options; let ellipsis = '…'; let ellipsisWidth = 1; if (typeof text !== 'string') { throw new TypeError(`Expected \`input\` to be a string, got ${typeof text}`); } if (typeof columns !== 'number') { throw new TypeError(`Expected \`columns\` to be a number, got ${typeof columns}`); } if (columns < 1) { return ''; } if (columns === 1) { return ellipsis; } const length = stringWidth(text); if (length <= columns) { return text; } if (position === 'start') { if (preferTruncationOnSpace) { const nearestSpace = getIndexOfNearestSpace(text, length - columns + 1, true); return ellipsis + sliceAnsi(text, nearestSpace, length).trim(); } if (space === true) { ellipsis += ' '; ellipsisWidth = 2; } return ellipsis + sliceAnsi(text, length - columns + ellipsisWidth, length); } if (position === 'middle') { if (space === true) { ellipsis = ' ' + ellipsis + ' '; ellipsisWidth = 3; } const half = Math.floor(columns / 2); if (preferTruncationOnSpace) { const spaceNearFirstBreakPoint = getIndexOfNearestSpace(text, half); const spaceNearSecondBreakPoint = getIndexOfNearestSpace(text, length - (columns - half) + 1, true); return sliceAnsi(text, 0, spaceNearFirstBreakPoint) + ellipsis + sliceAnsi(text, spaceNearSecondBreakPoint, length).trim(); } return ( sliceAnsi(text, 0, half) + ellipsis + sliceAnsi(text, length - (columns - half) + ellipsisWidth, length) ); } if (position === 'end') { if (preferTruncationOnSpace) { const nearestSpace = getIndexOfNearestSpace(text, columns - 1); return sliceAnsi(text, 0, nearestSpace) + ellipsis; } if (space === true) { ellipsis = ' ' + ellipsis; ellipsisWidth = 2; } return sliceAnsi(text, 0, columns - ellipsisWidth) + ellipsis; } throw new Error(`Expected \`options.position\` to be either \`start\`, \`middle\` or \`end\`, got ${position}`); };
hmu332233/LetMeKnow.jbnu--ChatBot--
test/controllers/chat_controller_test.rb
require 'test_helper' class ChatControllerTest < ActionController::TestCase test "should get keyboard" do get :keyboard assert_response :success end test "should get message" do get :message assert_response :success end test "should get add_friend" do get :add_friend assert_response :success end test "should get delete_friend" do get :delete_friend assert_response :success end test "should get chat_room" do get :chat_room assert_response :success end end
Tenderize/audius-protocol
discovery-provider/src/solana/constants.py
WAUDIO_DECIMALS = 8
AutoMeter/AutoMeter-API
testcenterservice/src/main/java/com/zoctan/api/entity/ApicasesPerformancestatistics.java
package com.zoctan.api.entity; import javax.persistence.*; import java.util.Date; @Table(name = "apicases_performancestatistics") public class ApicasesPerformancestatistics { /** * Id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * 用例id */ private Long caseid; /** * 执行计划id */ private Long testplanid; /** * 批次 */ private String batchname; public String getExecuteplanname() { return executeplanname; } public void setExecuteplanname(String executeplanname) { this.executeplanname = executeplanname; } public String getCasename() { return casename; } public void setCasename(String casename) { this.casename = casename; } private String executeplanname; private String casename; /** * 运行时长,秒 */ private Double runtime; /** * 执行机id */ private Long slaverid; /** * 样本 */ private Long samples; /** * 错误次数 */ private Long errorcount; /** * 错误率 */ private Double errorrate; /** * 平均数 */ private Double average; /** * 最小值 */ private Double min; /** * 最大值 */ private Double max; /** * 中间值 */ private Double median; /** * 90pct */ private Double nzpct; /** * 95pct */ private Double nfpct; /** * 99pct */ private Double nnpct; /** * tps */ private Double tps; /** * 每秒接受Kb数 */ private Double receivekbsec; /** * 每秒发送Kb数 */ private Double sendkbsec; /** * 创建时间 */ @Column(name = "create_time") private Date createTime; /** * 上一次修改时间 */ @Column(name = "lastmodify_time") private Date lastmodifyTime; /** * 创建者 */ private String creator; /** * 获取Id * * @return id - Id */ public Long getId() { return id; } /** * 设置Id * * @param id Id */ public void setId(Long id) { this.id = id; } /** * 获取用例id * * @return caseid - 用例id */ public Long getCaseid() { return caseid; } /** * 设置用例id * * @param caseid 用例id */ public void setCaseid(Long caseid) { this.caseid = caseid; } /** * 获取执行计划id * * @return testplanid - 执行计划id */ public Long getTestplanid() { return testplanid; } /** * 设置执行计划id * * @param testplanid 执行计划id */ public void setTestplanid(Long testplanid) { this.testplanid = testplanid; } /** * 获取批次 * * @return batchname - 批次 */ public String getBatchname() { return batchname; } /** * 设置批次 * * @param batchname 批次 */ public void setBatchname(String batchname) { this.batchname = batchname; } /** * 获取运行时长,秒 * * @return runtime - 运行时长,秒 */ public Double getRuntime() { return runtime; } /** * 设置运行时长,秒 * * @param runtime 运行时长,秒 */ public void setRuntime(Double runtime) { this.runtime = runtime; } /** * 获取执行机id * * @return slaverid - 执行机id */ public Long getSlaverid() { return slaverid; } /** * 设置执行机id * * @param slaverid 执行机id */ public void setSlaverid(Long slaverid) { this.slaverid = slaverid; } /** * 获取样本 * * @return samples - 样本 */ public Long getSamples() { return samples; } /** * 设置样本 * * @param samples 样本 */ public void setSamples(Long samples) { this.samples = samples; } /** * 获取错误次数 * * @return errorcount - 错误次数 */ public Long getErrorcount() { return errorcount; } /** * 设置错误次数 * * @param errorcount 错误次数 */ public void setErrorcount(Long errorcount) { this.errorcount = errorcount; } /** * 获取错误率 * * @return errorrate - 错误率 */ public Double getErrorrate() { return errorrate; } /** * 设置错误率 * * @param errorrate 错误率 */ public void setErrorrate(Double errorrate) { this.errorrate = errorrate; } /** * 获取平均数 * * @return average - 平均数 */ public Double getAverage() { return average; } /** * 设置平均数 * * @param average 平均数 */ public void setAverage(Double average) { this.average = average; } /** * 获取最小值 * * @return min - 最小值 */ public Double getMin() { return min; } /** * 设置最小值 * * @param min 最小值 */ public void setMin(Double min) { this.min = min; } /** * 获取最大值 * * @return max - 最大值 */ public Double getMax() { return max; } /** * 设置最大值 * * @param max 最大值 */ public void setMax(Double max) { this.max = max; } /** * 获取中间值 * * @return median - 中间值 */ public Double getMedian() { return median; } /** * 设置中间值 * * @param median 中间值 */ public void setMedian(Double median) { this.median = median; } /** * 获取90pct * * @return nzpct - 90pct */ public Double getNzpct() { return nzpct; } /** * 设置90pct * * @param nzpct 90pct */ public void setNzpct(Double nzpct) { this.nzpct = nzpct; } /** * 获取95pct * * @return nfpct - 95pct */ public Double getNfpct() { return nfpct; } /** * 设置95pct * * @param nfpct 95pct */ public void setNfpct(Double nfpct) { this.nfpct = nfpct; } /** * 获取99pct * * @return nnpct - 99pct */ public Double getNnpct() { return nnpct; } /** * 设置99pct * * @param nnpct 99pct */ public void setNnpct(Double nnpct) { this.nnpct = nnpct; } /** * 获取tps * * @return tps - tps */ public Double getTps() { return tps; } /** * 设置tps * * @param tps tps */ public void setTps(Double tps) { this.tps = tps; } /** * 获取每秒接受Kb数 * * @return receivekbsec - 每秒接受Kb数 */ public Double getReceivekbsec() { return receivekbsec; } /** * 设置每秒接受Kb数 * * @param receivekbsec 每秒接受Kb数 */ public void setReceivekbsec(Double receivekbsec) { this.receivekbsec = receivekbsec; } /** * 获取每秒发送Kb数 * * @return sendkbsec - 每秒发送Kb数 */ public Double getSendkbsec() { return sendkbsec; } /** * 设置每秒发送Kb数 * * @param sendkbsec 每秒发送Kb数 */ public void setSendkbsec(Double sendkbsec) { this.sendkbsec = sendkbsec; } /** * 获取创建时间 * * @return create_time - 创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间 * * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取上一次修改时间 * * @return lastmodify_time - 上一次修改时间 */ public Date getLastmodifyTime() { return lastmodifyTime; } /** * 设置上一次修改时间 * * @param lastmodifyTime 上一次修改时间 */ public void setLastmodifyTime(Date lastmodifyTime) { this.lastmodifyTime = lastmodifyTime; } /** * 获取创建者 * * @return creator - 创建者 */ public String getCreator() { return creator; } /** * 设置创建者 * * @param creator 创建者 */ public void setCreator(String creator) { this.creator = creator; } }
ibiz4j/ibizlab-runtime
ibzrt/ibzrt-util/src/main/java/cn/ibizlab/util/domain/FileItem.java
<filename>ibzrt/ibzrt-util/src/main/java/cn/ibizlab/util/domain/FileItem.java package cn.ibizlab.util.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Data; @Data @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @AllArgsConstructor public class FileItem { private String id; private String name; private String fileid; private String filename; private long size; private String ext; }
arusinha/incubator-netbeans
java/java.platform/test/unit/src/org/netbeans/modules/java/platform/queries/PlatformSourceForBinaryQueryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.java.platform.queries; import java.io.File; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.java.platform.JavaPlatform; import org.netbeans.api.java.platform.Specification; import org.netbeans.api.java.platform.TestJavaPlatformProvider; import org.netbeans.api.java.queries.SourceForBinaryQuery; import org.netbeans.junit.MockServices; import org.netbeans.junit.NbTestCase; import org.netbeans.spi.java.classpath.support.ClassPathSupport; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.filesystems.test.TestFileUtils; import org.openide.modules.SpecificationVersion; import org.openide.util.Utilities; /** * @author <NAME> */ public class PlatformSourceForBinaryQueryTest extends NbTestCase { public PlatformSourceForBinaryQueryTest(String testName) { super(testName); } protected @Override void setUp() throws Exception { super.setUp(); clearWorkDir(); MockServices.setServices( PlatformSourceForBinaryQuery.class, TestJavaPlatformProvider.class); } public void testUnregisteredPlatform() throws Exception { File wd = getWorkDir(); FileObject wdo = FileUtil.toFileObject(wd); assertNotNull(wdo); FileObject p1 = wdo.createFolder("platform1"); FileObject fo = p1.createFolder("jre"); fo = fo.createFolder("lib"); FileObject rt1 = fo.createData("rt.jar"); FileObject src1 = FileUtil.getArchiveRoot(createSrcZip (p1)); FileObject p2 = wdo.createFolder("platform2"); fo = p2.createFolder("jre"); fo = fo.createFolder("lib"); FileObject rt2 = fo.createData("rt.jar"); PlatformSourceForBinaryQuery q = new PlatformSourceForBinaryQuery (); SourceForBinaryQuery.Result result = q.findSourceRoots(FileUtil.getArchiveRoot(rt1.getURL())); assertEquals(1, result.getRoots().length); assertEquals(src1, result.getRoots()[0]); result = q.findSourceRoots(FileUtil.getArchiveRoot(rt2.getURL())); assertNull(result); } public void testTwoPlatformsoverSameSDKSourcesChange() throws Exception { final File binDir = new File(getWorkDir(),"boot"); //NOI18N binDir.mkdir(); final File jdocFile1 = new File(getWorkDir(),"src1"); //NOI18N jdocFile1.mkdir(); final File jdocFile2 = new File(getWorkDir(),"src2"); //NOI18N jdocFile2.mkdir(); final TestJavaPlatformProvider provider = TestJavaPlatformProvider.getDefault(); provider.reset(); final URL binRoot = Utilities.toURI(binDir).toURL(); final ClassPath bootCp = ClassPathSupport.createClassPath(binRoot); final ClassPath src1 = ClassPathSupport.createClassPath(Utilities.toURI(jdocFile1).toURL()); final ClassPath src2 = ClassPathSupport.createClassPath(Utilities.toURI(jdocFile2).toURL()); final TestJavaPlatform platform1 = new TestJavaPlatform("platform1", bootCp); //NOI18N final TestJavaPlatform platform2 = new TestJavaPlatform("platform2", bootCp); //NOI18N platform2.setSources(src2); provider.addPlatform(platform1); provider.addPlatform(platform2); final SourceForBinaryQuery.Result result1 = SourceForBinaryQuery.findSourceRoots(binRoot); assertEquals(Arrays.asList(src2.getRoots()), Arrays.asList(result1.getRoots())); platform1.setSources(src1); assertEquals(Arrays.asList(src1.getRoots()), Arrays.asList(result1.getRoots())); final SourceForBinaryQuery.Result result2 = SourceForBinaryQuery.findSourceRoots(binRoot); assertEquals(Arrays.asList(src1.getRoots()), Arrays.asList(result2.getRoots())); platform1.setSources(ClassPath.EMPTY); assertEquals(Arrays.asList(src2.getRoots()), Arrays.asList(result1.getRoots())); assertEquals(Arrays.asList(src2.getRoots()), Arrays.asList(result2.getRoots())); } public void testTwoPlatformsoverSameSDKPlatformChange() throws Exception { final File binDir = new File(getWorkDir(),"boot"); //NOI18N binDir.mkdir(); final File jdocFile1 = new File(getWorkDir(),"src1"); //NOI18N jdocFile1.mkdir(); final File jdocFile2 = new File(getWorkDir(),"src2"); //NOI18N jdocFile2.mkdir(); final TestJavaPlatformProvider provider = TestJavaPlatformProvider.getDefault(); provider.reset(); final URL binRoot = Utilities.toURI(binDir).toURL(); final ClassPath bootCp = ClassPathSupport.createClassPath(binRoot); final ClassPath src1 = ClassPathSupport.createClassPath(Utilities.toURI(jdocFile1).toURL()); final ClassPath src2 = ClassPathSupport.createClassPath(Utilities.toURI(jdocFile2).toURL()); final TestJavaPlatform platform1 = new TestJavaPlatform("platform1", bootCp); //NOI18N final TestJavaPlatform platform2 = new TestJavaPlatform("platform2", bootCp); //NOI18N platform1.setSources(src1); platform2.setSources(src2); provider.addPlatform(platform1); provider.addPlatform(platform2); final SourceForBinaryQuery.Result result1 = SourceForBinaryQuery.findSourceRoots(binRoot); assertEquals(Arrays.asList(src1.getRoots()), Arrays.asList(result1.getRoots())); provider.removePlatform(platform1); assertEquals(Arrays.asList(src2.getRoots()), Arrays.asList(result1.getRoots())); final SourceForBinaryQuery.Result result2 = SourceForBinaryQuery.findSourceRoots(binRoot); assertEquals(Arrays.asList(src2.getRoots()), Arrays.asList(result2.getRoots())); provider.insertPlatform(platform2, platform1); assertEquals(Arrays.asList(src1.getRoots()), Arrays.asList(result1.getRoots())); assertEquals(Arrays.asList(src1.getRoots()), Arrays.asList(result2.getRoots())); } private static FileObject createSrcZip (FileObject pf) throws Exception { return TestFileUtils.writeZipFile(pf, "src.zip", "Test.java:class Test {}"); } }
mwk0408/codewars_solutions
5 kyu/Did I Finish my Sudoku.py
def done_or_not(board): #board[i][j] for row in range(0,len(board)): if len(set(board[row]))!=9: return 'Try again!' temp=[] for row in range(0,9): for col in range(0,9): temp.append(board[col][row]) if len(set(temp))!=9: return 'Try again!' temp=[] index1=0 index2=0 while True: try: for k in range(3): for l in range(3): for i in range(3): for j in range(3): temp.append(board[index1+i][index2+j]) if len(set(temp))!=9: return "Try again!" temp=[] index2+=3 index1+=3 index2=0 except: return "Finished!"
SalvadorRadaVaca/PHP-and-MySQL
wordpress/wp-includes/js/jquery/ui/effect-transfer.min.js
/*! * jQuery UI Effects Transfer 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ !function(e){"function"==typeof define&&define.amd?define(["jquery","./effect"],e):e(jQuery)}(function(n){var e;return e=!1!==n.uiBackCompat?n.effects.define("transfer",function(e,f){n(this).transfer(e,f)}):e});
carlosvquezada/lg_ros_nodes
lg_nav_to_device/src/lg_nav_to_device/device_writer.py
<gh_stars>0 from geometry_msgs.msg import Twist from lg_common.msg import ApplicationState from evdev import AbsInfo, UInput, InputEvent, ecodes as e import time class DeviceWriter: def __init__(self, scale): self.scale = scale # most values were taken from running # InputDevice('/dev/input/event$N').capabilities() vendor = 1133 product = 0 version = 273 bustype = 3 caps = { e.EV_KEY: [e.BTN_0, e.BTN_1], e.EV_REL: [e.REL_X, e.REL_Y, e.REL_Z, e.REL_RX, e.REL_RY, e.REL_RZ], } device_name = 'Virtual SpaceNav' self.state = True self.ui = UInput(caps, vendor=vendor, product=product, version=version, bustype=bustype, name=device_name) def make_event(self, data): if not self.state: return for v in (data.linear, data.angular): # We don't want to write zeroes because the real spacenav never does, # instead write a small value inside Earth's gutter to prevent drift. if v.x == 0: v.x = 1.0 / self.scale if v.y == 0: v.y = 1.0 / self.scale if v.z == 0: v.z = 1.0 / self.scale # write some event to self.ui based off of the twist data _time = time.time() stime = int(_time) utime = int((float(_time) - stime) * 10 ** 6) x = InputEvent(stime, utime, e.EV_REL, e.REL_X, -self.translate(data.linear.y)) y = InputEvent(stime, utime, e.EV_REL, e.REL_Y, -self.translate(data.linear.x)) z = InputEvent(stime, utime, e.EV_REL, e.REL_Z, -self.translate(data.linear.z)) ax = InputEvent(stime, utime, e.EV_REL, e.REL_RX, -self.translate(data.angular.y)) ay = InputEvent(stime, utime, e.EV_REL, e.REL_RY, -self.translate(data.angular.x)) az = InputEvent(stime, utime, e.EV_REL, e.REL_RZ, -self.translate(data.angular.z)) # write all events self.ui.write_event(x) self.ui.write_event(y) self.ui.write_event(z) self.ui.write_event(ax) self.ui.write_event(ay) self.ui.write_event(az) # syn to alert input subsystem self.ui.syn() def translate(self, n): return int(n * self.scale) # TODO find the translation... def set_state(self, msg): self.state = msg.state == ApplicationState.VISIBLE
watermint/Semester
semester-foundation-http/src/main/scala/semester/foundation/http/StatusCode.scala
<reponame>watermint/Semester package semester.foundation.http trait StatusCode { val code: Int val label: String } object StatusCode { def apply(code: Int): StatusCode = { code match { case 100 => StatusContinue() case 101 => StatusSwitchingProtocols() case c if c / 100 == 1 => StatusExtendedInformational(code) case 200 => StatusOK() case 201 => StatusCreated() case 202 => StatusAccepted() case 203 => StatusNonAuthoritativeInformation() case 204 => StatusNoContent() case 205 => StatusResetContent() case 206 => StatusPartialContent() case c if c / 100 == 2 => StatusExtendedSuccessful(code) case 300 => StatusMultipleChoices() case 301 => StatusMovedPermanently() case 302 => StatusFound() case 303 => StatusSeeOther() case 304 => StatusNotModified() case 305 => StatusUseProxy() case 307 => StatusTemporaryRedirect() case c if c / 100 == 3 => StatusExtendedRedirection(code) case 400 => StatusBadRequest() case 401 => StatusUnauthorized() case 402 => StatusPaymentRequired() case 403 => StatusForbidden() case 404 => StatusNotFound() case 405 => StatusMethodNotAllowed() case 406 => StatusNotAcceptable() case 407 => StatusProxyAuthenticationRequired() case 408 => StatusRequestTimeout() case 409 => StatusConflict() case 410 => StatusGone() case 411 => StatusLengthRequired() case 412 => StatusPreconditionFailed() case 413 => StatusRequestEntityTooLarge() case 414 => StatusRequestURITooLong() case 415 => StatusUnsupportedMediaType() case 416 => StatusRequestedRangeNotSatisfiable() case 417 => StatusExpectationFailed() case c if c / 100 == 4 => StatusExtendedClientError(code) case 500 => StatusInternalServerError() case 501 => StatusNotImplemented() case 502 => StatusBadGateway() case 503 => StatusServiceUnavailable() case 504 => StatusGatewayTimeout() case 505 => StatusHTTPVersionNotSupported() case c if c / 100 == 5 => StatusExtendedServerError(code) case _ => StatusUnknownCode(code) } } } trait StatusExtendedCode extends StatusCode { val label: String = "Extended Code" } case class StatusUnknownCode(code: Int) extends StatusCode { val label: String = "Unknown" } /* * RFC2616 - 1xx Informational */ trait StatusInformational extends StatusCode case class StatusExtendedInformational(code: Int) extends StatusCode with StatusExtendedCode case class StatusContinue() extends StatusInformational { val code: Int = 100 val label: String = "Continue" } case class StatusSwitchingProtocols() extends StatusInformational { val code: Int = 101 val label: String = "Switching Protocols" } /* * RFC2616 - 2xx Successful */ trait StatusSuccessful extends StatusCode case class StatusExtendedSuccessful(code: Int) extends StatusCode with StatusExtendedCode case class StatusOK() extends StatusSuccessful { val code: Int = 200 val label: String = "OK" } case class StatusCreated() extends StatusSuccessful { val code: Int = 201 val label: String = "Created" } case class StatusAccepted() extends StatusSuccessful { val code: Int = 202 val label: String = "Accepted" } case class StatusNonAuthoritativeInformation() extends StatusSuccessful { val code: Int = 203 val label: String = "Non-Authoritative Information" } case class StatusNoContent() extends StatusSuccessful { val code: Int = 204 val label: String = "No Content" } case class StatusResetContent() extends StatusSuccessful { val code: Int = 205 val label: String = "Reset Content" } case class StatusPartialContent() extends StatusSuccessful { val code: Int = 206 val label: String = "Partial Content" } /* * RFC2616 - 3xx Redirection */ trait StatusRedirection extends StatusCode case class StatusExtendedRedirection(code: Int) extends StatusCode with StatusExtendedCode case class StatusMultipleChoices() extends StatusRedirection { val code: Int = 300 val label: String = "Multiple Choices" } case class StatusMovedPermanently() extends StatusRedirection { val code: Int = 301 val label: String = "Moved Permanently" } case class StatusFound() extends StatusRedirection { val code: Int = 302 val label: String = "Found" } case class StatusSeeOther() extends StatusRedirection { val code: Int = 303 val label: String = "See Other" } case class StatusNotModified() extends StatusRedirection { val code: Int = 304 val label: String = "Not Modified" } case class StatusUseProxy() extends StatusRedirection { val code: Int = 305 val label: String = "Use Proxy" } case class StatusTemporaryRedirect() extends StatusRedirection { val code: Int = 307 val label: String = "Temporary Redirect" } /* * RFC2616 - 4xx Client Error */ trait StatusClientError extends StatusCode case class StatusExtendedClientError(code: Int) extends StatusCode with StatusExtendedCode case class StatusBadRequest() extends StatusClientError { val code: Int = 400 val label: String = "Bad Request" } case class StatusUnauthorized() extends StatusClientError { val code: Int = 401 val label: String = "Unauthorized" } case class StatusPaymentRequired() extends StatusClientError { val code: Int = 402 val label: String = "Payment Required" } case class StatusForbidden() extends StatusClientError { val code: Int = 403 val label: String = "Forbidden" } case class StatusNotFound() extends StatusClientError { val code: Int = 404 val label: String = "Not Found" } case class StatusMethodNotAllowed() extends StatusClientError { val code: Int = 405 val label: String = "Method Not Allowed" } case class StatusNotAcceptable() extends StatusClientError { val code: Int = 406 val label: String = "Not Acceptable" } case class StatusProxyAuthenticationRequired() extends StatusClientError { val code: Int = 407 val label: String = "Proxy Authentication Required" } case class StatusRequestTimeout() extends StatusClientError { val code: Int = 408 val label: String = "Request Timeout" } case class StatusConflict() extends StatusClientError { val code: Int = 409 val label: String = "Conflict" } case class StatusGone() extends StatusClientError { val code: Int = 410 val label: String = "Gone" } case class StatusLengthRequired() extends StatusClientError { val code: Int = 411 val label: String = "Length Required" } case class StatusPreconditionFailed() extends StatusClientError { val code: Int = 412 val label: String = "Precondition Failed" } case class StatusRequestEntityTooLarge() extends StatusClientError { val code: Int = 413 val label: String = "Request Entity Too Large" } case class StatusRequestURITooLong() extends StatusClientError { val code: Int = 414 val label: String = "Request-URI Too Long" } case class StatusUnsupportedMediaType() extends StatusClientError { val code: Int = 415 val label: String = "Unsupported Media Type" } case class StatusRequestedRangeNotSatisfiable() extends StatusClientError { val code: Int = 416 val label: String = "Requested Range Not Satisfiable" } case class StatusExpectationFailed() extends StatusClientError { val code: Int = 417 val label: String = "Expectation Failed" } /* * RFC2616 - 5xx Server Error */ trait StatusServerError extends StatusCode case class StatusExtendedServerError(code: Int) extends StatusCode with StatusExtendedCode case class StatusInternalServerError() extends StatusServerError { val code: Int = 500 val label: String = "Internal Server Error" } case class StatusNotImplemented() extends StatusServerError { val code: Int = 501 val label: String = "Not Implemented" } case class StatusBadGateway() extends StatusServerError { val code: Int = 502 val label: String = "Bad Gateway" } case class StatusServiceUnavailable() extends StatusServerError { val code: Int = 503 val label: String = "Service Unavailable" } case class StatusGatewayTimeout() extends StatusServerError { val code: Int = 504 val label: String = "Gateway Timeout" } case class StatusHTTPVersionNotSupported() extends StatusServerError { val code: Int = 505 val label: String = "HTTP Version Not Supported" }
FlashYoshi/UGentProjects
VOP/libs/functionalanalysis/src/org/aikodi/lang/funky/behavior/BranchingPoint.java
<reponame>FlashYoshi/UGentProjects package org.aikodi.lang.funky.behavior; import com.google.java.contract.Ensures; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.core.element.ElementImpl; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.core.reference.CrossReference; import org.aikodi.chameleon.util.association.Single; import org.aikodi.lang.funky.executors.ExecutingEntity; import org.aikodi.lang.funky.usecase.AbstractFlow; import org.aikodi.lang.funky.virtualmachine.VirtualProcess; /** * A branching point redirects the execution to another flow when the condition * of the flow is satisfied. The branching point keeps a cross-reference to * the other flow, and stores the behavior that must be executed when the condition * of the other flow is not satisfied. * * @author <NAME> * * @param <F> The type of the other flow. */ public class BranchingPoint<F extends AbstractFlow> extends ElementImpl implements Behavior { private Single<CrossReference<? extends F>> _target = new Single<>(this,true,"target flow"); private Single<Behavior> _behavior = new Single<>(this,true,"behavior"); /** * Create a new branching point with the given target reference and * normal behavior. * * @param targetReference A cross-reference to the alternative flow that * may be executed. * @param normalBehavior The normal behavior that is executed when the * condition of the alternative flow is not satisfied. */ public BranchingPoint(CrossReference<? extends F> targetReference, Behavior normalBehavior) { setTarget(targetReference); setNormalBehavior(normalBehavior); } /** * {@inheritDoc} * * @return The target flow referenced by the {@link #targetReference()}. If no * target reference is set, null is returned. * @throws LookupException * The target flow could not be resolved. */ @Ensures({"(targetReference() == null && result == null)" + "|| (targetReference() != null && result == targetReference().getElement())"}) public F target() throws LookupException { if (targetReference() != null) { return targetReference().getElement(); } else { return null; } } /** * Set the {@link CrossReference} to the target of this branching point. * * @param target * A cross-reference to the target of this branching point. */ public void setTarget(CrossReference<? extends F> target) { set(_target, target); } /** * @return A cross-reference to the target of this branching point. */ public CrossReference<? extends F> targetReference() { return _target.getOtherEnd(); } /** * {@inheritDoc} * * @return The initiator of the normal behavior. */ @Ensures({"result == normalBehavior().initiator()"}) @Override public ExecutingEntity executor() throws LookupException { return normalBehavior().executor(); } @Override public void execute(VirtualProcess parent) { // Execute both the normal flow and branch try { AbstractFlow target = target(); parent.advance(target.behavior(), target.condition(), this); } catch (LookupException | NullPointerException e) { // Do nothing } if (normalBehavior() != null) { parent.advance(normalBehavior()); } } /** * @return the normal behavior of this branching point. This behavior * is executed the condition of the target flow is not satisfied. */ public Behavior normalBehavior() { return _behavior.getOtherEnd(); } /** * Set the normal behavior of this branching point. * * @param behavior The normal behavior that is executed when the condition * of the target flow is not satisfied. */ @Ensures({"behavior() == behavior"}) public void setNormalBehavior(Behavior behavior) { set(_behavior,behavior); } @Override protected Element cloneSelf() { return new BranchingPoint<F>(null, null); } }
tonythomas01/quarantine_backend
authentication/tests.py
<reponame>tonythomas01/quarantine_backend<gh_stars>1-10 from unittest.mock import patch, MagicMock, Mock from django.test import TestCase from django.views import View from rest_framework import serializers from authentication.permissions import IsAffectedUser, IsHelperUser, IsOwnerOfRequest, IsAssigneeOfRequest from authentication.serializer import EmailAuthTokenSerializer from crisis.models.crisis_request import Request class MockUser: def __init__( self, is_authenticated: bool = False, ): self.is_authenticated = is_authenticated class MockRequest: pass class MockRelatedParticipant: def __init__(self, type: str = ""): self.type = type failure_authenticate_mock = MagicMock(return_value=None) success_authenticate_mock = MagicMock(return_value=MockUser()) class EmailAuthTokenSerializerTest(TestCase): def setUp(self) -> None: self.model = EmailAuthTokenSerializer() @patch("authentication.serializer.authenticate", failure_authenticate_mock) def test_failed_authentication_should_raise_validation_error(self): with self.assertRaisesMessage(serializers.ValidationError, 'Unable to log in with provided credentials.'): self.model.validate(attrs=dict(email="<EMAIL>", password="<PASSWORD>")) def test_missing_credentials_should_throw_exception(self): with self.assertRaisesMessage(serializers.ValidationError, 'Must include "email" and "password".'): self.model.validate(attrs=dict()) @patch("authentication.serializer.authenticate", success_authenticate_mock) def test_success_authentication_should_return_authenticate_result(self): result = self.model.validate(attrs=dict(email="<EMAIL>", password="<PASSWORD>")) self.assertEquals(type(result['user']), type(MockUser())) class IsAffectedUserTest(TestCase): def setUp(self) -> None: self.model = IsAffectedUser() def test_request_user_must_be_authenticated_and_affected(self): mock_request = MockRequest() mock_user = MockUser(is_authenticated=False) mock_user.related_participant = MockRelatedParticipant(type="AF") mock_request.user = mock_user self.assertFalse(self.model.has_permission(mock_request, None)) mock_request = MockRequest() mock_user = MockUser(is_authenticated=True) mock_user.related_participant = MockRelatedParticipant(type="SomethingElse") mock_request.user = mock_user self.assertFalse(self.model.has_permission(mock_request, None)) mock_request = MockRequest() mock_user = MockUser(is_authenticated=False) mock_user.related_participant = MockRelatedParticipant(type="SomethingElse") mock_request.user = mock_user self.assertFalse(self.model.has_permission(mock_request, None)) mock_request = MockRequest() mock_user = MockUser(is_authenticated=True) mock_user.related_participant = MockRelatedParticipant(type="AF") mock_request.user = mock_user self.assertTrue(self.model.has_permission(mock_request, None)) class IsHelperUserTest(TestCase): def setUp(self) -> None: self.model = IsHelperUser() def test_only_helper_can_assign_a_request(self): # test that all allowed types have permission as long as authenticated allowed_types = ["HL", "AU", "TP"] for allowed_type in allowed_types: mock_request = MockRequest() mock_user = MockUser(is_authenticated=True) mock_user.related_participant = MockRelatedParticipant(type=allowed_type) mock_request.user = mock_user self.assertTrue(self.model.has_permission(mock_request, None)) mock_request = MockRequest() mock_user = MockUser(is_authenticated=False) mock_user.related_participant = MockRelatedParticipant(type=allowed_type) mock_request.user = mock_user self.assertFalse(self.model.has_permission(mock_request, None)) # test that an authenticated user with an disallowed type does not have permission mock_request = MockRequest() mock_user = MockUser(is_authenticated=True) mock_user.related_participant = MockRelatedParticipant(type="AF") mock_request.user = mock_user self.assertFalse(self.model.has_permission(mock_request, None)) currentUser = MockUser() participant_request_mock = Mock() participant_request_mock.owner = Mock() participant_request_mock.owner.user = currentUser objects_mock = Mock() objects_mock.get.return_value = participant_request_mock success_request_mock = Mock(spec=Request) success_request_mock.objects = objects_mock found_but_wrong_participant_request_mock = Mock() found_but_wrong_participant_request_mock.owner = Mock() # here we return another mock user different from 'owner' found_but_wrong_participant_request_mock.user = MockUser() found_but_wrong_objects_mock = Mock() found_but_wrong_objects_mock.get.return_value = found_but_wrong_participant_request_mock found_but_wrong_request = Mock(spec=Request) found_but_wrong_request.objects = found_but_wrong_objects_mock class IsOwnerOfRequestTest(TestCase): def setUp(self) -> None: self.model = IsOwnerOfRequest() self.viewMock = Mock(spec=View) self.viewMock.kwargs = Mock() self.viewMock.kwargs.get.return_value = None @patch("authentication.permissions.Request", success_request_mock) def test_owners_should_have_permission(self): request = MockRequest() request.user = currentUser self.assertTrue(self.model.has_permission(request, self.viewMock)) @patch("authentication.permissions.Request", found_but_wrong_request) def test_non_owners_should_not_have_permission(self): request = MockRequest() request.user = currentUser self.assertFalse(self.model.has_permission(request, self.viewMock)) assignee_request = Mock() assignee_request.assignee = Mock() assignee_request.assignee.user = currentUser assignee_objects_mock = Mock() assignee_objects_mock.get.return_value = assignee_request assignee_success_request_mock = Mock(spec=Request) assignee_success_request_mock.objects = assignee_objects_mock class IsAssigneeOfRequestTest(TestCase): def setUp(self) -> None: self.model = IsAssigneeOfRequest() self.viewMock = Mock(spec=View) self.viewMock.kwargs = Mock() self.viewMock.kwargs.get.return_value = None @patch("authentication.permissions.Request", assignee_success_request_mock) def test_owners_should_have_permission(self): request = MockRequest() request.user = currentUser self.assertTrue(self.model.has_permission(request, self.viewMock))
rayworks/algorithms
src/main/java/org/sean/recursive/RootLeafSequenceValidator.java
<gh_stars>1-10 package org.sean.recursive; import org.sean.tree.TreeNode; import java.util.LinkedList; import java.util.List; // https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/532/week-5/3315/ public class RootLeafSequenceValidator { Boolean matched = false; boolean gatherAllPaths(TreeNode parent, TreeNode root, List<Integer> path, int[] arr) { if (root == null) { if (parent != null && parent.left == null && parent.right == null) { if (!path.isEmpty()) { if (isMatched(arr, path)) { matched = true; } } } return false; } path.add(root.val); boolean added = gatherAllPaths(root, root.left, path, arr); if (!matched) { if (added) { path.remove(path.size() - 1); } } if (!matched) { added = gatherAllPaths(root, root.right, path, arr); if (added) { path.remove(path.size() - 1); } } return true; } private boolean isMatched(int[] arr, List<Integer> p) { boolean matched; if (p.size() == arr.length) { matched = true; for (int i = 0; i < arr.length; i++) { if (p.get(i) != arr[i]) { matched = false; break; } } if (matched) { return true; } } return false; } // Valid Sequence from Root to Leaves Path in a Binary Tree public boolean isValidSequence(TreeNode root, int[] arr) { if (arr == null || arr.length == 0) return false; gatherAllPaths(root, root, new LinkedList<>(), arr); return matched; } }
AbstrLabs/gnark
std/algebra/twistededwards/point.go
<filename>std/algebra/twistededwards/point.go /* Copyright © 2020 ConsenSys 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 twistededwards import ( "math/big" "github.com/consensys/gnark/frontend" ) // Point point on a twisted Edwards curve in a Snark cs type Point struct { X, Y frontend.Variable } // Neg computes the negative of a point in SNARK coordinates func (p *Point) Neg(api frontend.API, p1 *Point) *Point { p.X = api.Neg(p1.X) p.Y = p1.Y return p } // MustBeOnCurve checks if a point is on the reduced twisted Edwards curve // a*x² + y² = 1 + d*x²*y². func (p *Point) MustBeOnCurve(api frontend.API, curve EdCurve) { one := big.NewInt(1) xx := api.Mul(p.X, p.X) yy := api.Mul(p.Y, p.Y) axx := api.Mul(xx, &curve.A) lhs := api.Add(axx, yy) dxx := api.Mul(xx, &curve.D) dxxyy := api.Mul(dxx, yy) rhs := api.Add(dxxyy, one) api.AssertIsEqual(lhs, rhs) } // Add Adds two points on a twisted edwards curve (eg jubjub) // p1, p2, c are respectively: the point to add, a known base point, and the parameters of the twisted edwards curve func (p *Point) Add(api frontend.API, p1, p2 *Point, curve EdCurve) *Point { // https://eprint.iacr.org/2008/013.pdf n11 := api.Mul(p1.X, p2.Y) n12 := api.Mul(p1.Y, p2.X) n1 := api.Add(n11, n12) n21 := api.Mul(p1.Y, p2.Y) n22 := api.Mul(p1.X, p2.X) an22 := api.Mul(n22, &curve.A) n2 := api.Sub(n21, an22) d11 := api.Mul(curve.D, n11, n12) d1 := api.Add(1, d11) d2 := api.Sub(1, d11) p.X = api.DivUnchecked(n1, d1) p.Y = api.DivUnchecked(n2, d2) return p } // Double doubles a points in SNARK coordinates func (p *Point) Double(api frontend.API, p1 *Point, curve EdCurve) *Point { u := api.Mul(p1.X, p1.Y) v := api.Mul(p1.X, p1.X) w := api.Mul(p1.Y, p1.Y) n1 := api.Mul(2, u) av := api.Mul(v, &curve.A) n2 := api.Sub(w, av) d1 := api.Add(w, av) d2 := api.Sub(2, d1) p.X = api.DivUnchecked(n1, d1) p.Y = api.DivUnchecked(n2, d2) return p } // ScalarMul computes the scalar multiplication of a point on a twisted Edwards curve // p1: base point (as snark point) // curve: parameters of the Edwards curve // scal: scalar as a SNARK constraint // Standard left to right double and add func (p *Point) ScalarMul(api frontend.API, p1 *Point, scalar frontend.Variable, curve EdCurve) *Point { // first unpack the scalar b := api.ToBinary(scalar) res := Point{} tmp := Point{} A := Point{} B := Point{} A.Double(api, p1, curve) B.Add(api, &A, p1, curve) n := len(b) - 1 res.X = api.Lookup2(b[n], b[n-1], 0, A.X, p1.X, B.X) res.Y = api.Lookup2(b[n], b[n-1], 1, A.Y, p1.Y, B.Y) for i := n - 2; i >= 1; i -= 2 { res.Double(api, &res, curve). Double(api, &res, curve) tmp.X = api.Lookup2(b[i], b[i-1], 0, A.X, p1.X, B.X) tmp.Y = api.Lookup2(b[i], b[i-1], 1, A.Y, p1.Y, B.Y) res.Add(api, &res, &tmp, curve) } if n%2 == 0 { res.Double(api, &res, curve) tmp.Add(api, &res, p1, curve) res.X = api.Select(b[0], tmp.X, res.X) res.Y = api.Select(b[0], tmp.Y, res.Y) } p.X = res.X p.Y = res.Y return p } // DoubleBaseScalarMul computes s1*P1+s2*P2 // where P1 and P2 are points on a twisted Edwards curve // and s1, s2 scalars. func (p *Point) DoubleBaseScalarMul(api frontend.API, p1, p2 *Point, s1, s2 frontend.Variable, curve EdCurve) *Point { // first unpack the scalars b1 := api.ToBinary(s1) b2 := api.ToBinary(s2) res := Point{} tmp := Point{} sum := Point{} sum.Add(api, p1, p2, curve) n := len(b1) res.X = api.Lookup2(b1[n-1], b2[n-1], 0, p1.X, p2.X, sum.X) res.Y = api.Lookup2(b1[n-1], b2[n-1], 1, p1.Y, p2.Y, sum.Y) for i := n - 2; i >= 0; i-- { res.Double(api, &res, curve) tmp.X = api.Lookup2(b1[i], b2[i], 0, p1.X, p2.X, sum.X) tmp.Y = api.Lookup2(b1[i], b2[i], 1, p1.Y, p2.Y, sum.Y) res.Add(api, &res, &tmp, curve) } p.X = res.X p.Y = res.Y return p }
jacob-grahn/futurism-multi
game/initAccounts.js
'use strict'; var _ = require('lodash'); var actions = require('../shared/actions'); var Player = require('./Player'); var nextCid = require('./nextCid'); /** * Create a card to represent the player * @param {object} account */ var makeAccountCard = function(account) { return { _id: 0, commander: true, userId: account._id, name: account.name, faction: 'no', attack: 1, health: 9, story: '', abilities: [actions.SUMMON, actions.FUTURE, actions.ATTACK], cid: nextCid(), moves: 1, pride: 0 }; }; /** * Fill an account with the data structure needed to play a match * @param {Array} accounts * @returns {Array.<Player>} players */ var InitAccounts = function(accounts) { var players = []; _.each(accounts, function(account) { var player = new Player(account); var commander = makeAccountCard(account); player.hand.push(commander); players.push(player); }); return players; }; /** * public interface */ module.exports = InitAccounts;
tommy91/Gazebo-Ardupilot
gazebo/common/Events.hh
<filename>gazebo/common/Events.hh /* * Copyright (C) 2012 Open Source Robotics Foundation * * 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. * */ #ifndef _EVENTS_HH_ #define _EVENTS_HH_ #include <string> #include <sdf/sdf.hh> #include "gazebo/common/Console.hh" #include "gazebo/common/UpdateInfo.hh" #include "gazebo/common/Event.hh" #include "gazebo/util/system.hh" namespace gazebo { namespace event { /// \addtogroup gazebo_event /// \{ /// \class Events Events.hh common/common.hh /// \brief An Event class to get notifications for simulator events class GZ_COMMON_VISIBLE Events { ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the pause signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectPause(T _subscriber) { return pause.Connect(_subscriber); } /// \brief Disconnect a callback from the pause signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectPause(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { pause.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the step signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectStep(T _subscriber) { return step.Connect(_subscriber); } /// \brief Disconnect a callback from the step signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectStep(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { step.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the stop signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectStop(T _subscriber) { return stop.Connect(_subscriber); } /// \brief Disconnect a callback from the stop signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectStop(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { stop.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the world created signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectWorldCreated(T _subscriber) { return worldCreated.Connect(_subscriber); } /// \brief Disconnect a callback from the world created signal /// \deprecated Use event::~Connection to disconnect public: static void DisconnectWorldCreated(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { worldCreated.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the add entity signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectCreateEntity(T _subscriber) { return entityCreated.Connect(_subscriber); } /// \brief Disconnect a callback from the add entity signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectCreateEntity(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { entityCreated.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the set selected entity signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectSetSelectedEntity(T _subscriber) { return setSelectedEntity.Connect(_subscriber); } /// \brief Disconnect a callback from the set selected entity signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectSetSelectedEntity(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { setSelectedEntity.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the delete entity signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectDeleteEntity(T _subscriber) { return deleteEntity.Connect(_subscriber); } /// \brief Disconnect a callback from the delete entity signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectDeleteEntity(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { deleteEntity.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the add entity signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectAddEntity(T _subscriber) { return addEntity.Connect(_subscriber); } /// \brief Disconnect a callback from the add entity signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectAddEntity(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { addEntity.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the world update start signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectWorldUpdateBegin(T _subscriber) { return worldUpdateBegin.Connect(_subscriber); } /// \brief Disconnect a callback from the world update start signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectWorldUpdateBegin( ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0); ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the before physics update signal /// \param[in] _subscriber the subscriber to this event /// \return a connection /// /// The signal is called after collision detection has finished and before /// the physics update step. So you can e.g. change some forces depending /// on the collisions that have occured. public: template<typename T> static ConnectionPtr ConnectBeforePhysicsUpdate(T _subscriber) { return beforePhysicsUpdate.Connect(_subscriber); } /// \brief Disconnect a callback from the before physics update signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectBeforePhysicsUpdate( ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { beforePhysicsUpdate.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the world update end signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectWorldUpdateEnd(T _subscriber) { return worldUpdateEnd.Connect(_subscriber); } /// \brief Disconnect a callback from the world update end signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectWorldUpdateEnd(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { worldUpdateEnd.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect to the world reset signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectWorldReset(T _subscriber) { return worldReset.Connect(_subscriber); } /// \brief Disconnect from the world reset signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectWorldReset(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { worldReset.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect to the time reset signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectTimeReset(T _subscriber) { return timeReset.Connect(_subscriber); } /// \brief Disconnect from the time reset signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectTimeReset(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { timeReset.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect to the remove sensor signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectRemoveSensor(T _subscriber) { return removeSensor.Connect(_subscriber); } /// \brief Disconnect from the remove sensor signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectRemoveSensor(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { removeSensor.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect to the create sensor signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectCreateSensor(T _subscriber) { return createSensor.Connect(_subscriber); } /// \brief Disconnect from the create sensor signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectCreateSensor(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { createSensor.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Render start signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectPreRender(T _subscriber) { return preRender.Connect(_subscriber); } /// \brief Disconnect a render start signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectPreRender(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { preRender.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the render update signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectRender(T _subscriber) { return render.Connect(_subscriber); } /// \brief Disconnect a callback from the render update signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectRender(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { render.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the post render update signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectPostRender(T _subscriber) { return postRender.Connect(_subscriber); } /// \brief Disconnect a callback from the post render update signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectPostRender(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { postRender.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the diagnostic timer start signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectDiagTimerStart(T _subscriber) { return diagTimerStart.Connect(_subscriber); } /// \brief Disconnect a callback from the diagnostic timer start signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectDiagTimerStart(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { diagTimerStart.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the diagnostic timer stop signal /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectDiagTimerStop(T _subscriber) { return diagTimerStop.Connect(_subscriber); } /// \brief Disconnect a callback from the diagnostic timer stop signal /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectDiagTimerStop(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { diagTimerStop.Disconnect(_subscriber->Id()); } ////////////////////////////////////////////////////////////////////////// /// \brief Connect a callback to the sigint event /// \param[in] _subscriber the subscriber to this event /// \return a connection public: template<typename T> static ConnectionPtr ConnectSigInt(T _subscriber) { return sigInt.Connect(_subscriber); } /// \brief Disconnect a callback from the sigint event /// \param[in] _subscriber the subscriber to this event /// \deprecated Use event::~Connection to disconnect public: static void DisconnectSigInt(ConnectionPtr _subscriber) GAZEBO_DEPRECATED(8.0) { sigInt.Disconnect(_subscriber->Id()); } /// \brief Pause signal public: static EventT<void (bool)> pause; /// \brief Step the simulation once signal public: static EventT<void ()> step; /// \brief Simulation stop signal public: static EventT<void ()> stop; /// \brief Simulation stop signal public: static EventT<void ()> sigInt; /// \brief A world has been created public: static EventT<void (std::string)> worldCreated; /// \brief An entity has been created public: static EventT<void (std::string)> entityCreated; /// \brief An entity has been selected public: static EventT<void (std::string, std::string)> setSelectedEntity; /// \brief An entity has been added public: static EventT<void (std::string)> addEntity; /// \brief An entity has been deleted public: static EventT<void (std::string)> deleteEntity; /// \brief World update has started public: static EventT<void (const common::UpdateInfo &)> worldUpdateBegin; /// \brief Collision detection has been done, physics update not yet public: static EventT<void (const common::UpdateInfo &)> beforePhysicsUpdate; /// \brief World update has ended public: static EventT<void ()> worldUpdateEnd; /// \brief World reset signal public: static EventT<void ()> worldReset; /// \brief Time reset signal public: static EventT<void ()> timeReset; /// \brief Pre-render public: static EventT<void ()> preRender; /// \brief Render public: static EventT<void ()> render; /// \brief Post-Render public: static EventT<void ()> postRender; /// \brief Diagnostic timer start public: static EventT<void (std::string)> diagTimerStart; /// \brief Diagnostic timer stop public: static EventT<void (std::string)> diagTimerStop; /// \brief Remove a sensor /// /// * Parameter 1 (string): Name of the sensor to remove. public: static EventT<void (std::string)> removeSensor; /// \brief Create a sensor /// * Parameter 1 (sdf::ElementPtr): The SDF element that describes /// the sensor. /// * Parameter 2 (std::string): Name of the world in which to create /// the sensor. /// * Parameter 3 (std::string): The scoped parent name /// (model::link). /// * Parameter 4 (uint32_t): ID of the sensor public: static EventT<void (sdf::ElementPtr, const std::string &, const std::string &, const uint32_t)> createSensor; }; /// \} } } #endif
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments
TheHunt/src/com/primalpond/hunt/TutorialRenderer.java
<gh_stars>0 package com.primalpond.hunt; import android.content.Context; import android.graphics.PointF; import android.util.Log; import android.view.MotionEvent; import com.primalpond.hunt.agent.prey.Prey; import com.primalpond.hunt.world.environment.Environment; import com.primalpond.hunt.world.environment.NAlgae; import com.primalpond.hunt.world.logic.TheHuntRenderer; import com.primalpond.hunt.world.tools.CatchNet; import d3kod.graphics.shader.ShaderProgramManager; import d3kod.graphics.sprite.SpriteManager; import d3kod.graphics.texture.TextureManager; public class TutorialRenderer extends TheHuntRenderer { private static final String TAG = "TutorialRenderer"; private static final int SHOULD_FEED = 200; private static final int INCR_ENERGY_AMOUNT = 20; private Demonstrator mDemonstrator; private int mUpdated; private boolean mToShowDemonstrator; private TutorialStep mTutorialStep; public enum TutorialStep { NET_TRAINING, FOOD_TRAINING, CUT_TRAINING; } public TutorialRenderer(Context context) { super(context, TAG); mToShowDemonstrator = true; mTutorialStep = TutorialStep.NET_TRAINING; } @Override protected SpriteManager loadSavedState(ShaderProgramManager shaderManager, TextureManager textureManager) { Log.v(TAG, "Loading saved state"); mD3GLES20 = new SpriteManager(shaderManager, textureManager, mContext); mEnv = new Environment(null, mD3GLES20, 0); // mEnv.addNewAlgae(10, new PointF(0, 0), 0); mPrey = new Prey(mEnv, null, mD3GLES20); return mD3GLES20; } @Override public void updateWorld() { super.updateWorld(); if (mTutorialStep == null) { return; } if (mTutorialStep.equals(TutorialStep.NET_TRAINING)) { mPrey.setPosition(new PointF(0, 0)); mUpdated ++; if (mUpdated > SHOULD_FEED) { // mEnv.putFoodGM(mPrey.getRadius(), 0); mPrey.increaseEnergy(INCR_ENERGY_AMOUNT); mUpdated = 0; } } if (mTutorialStep.equals(TutorialStep.FOOD_TRAINING)) { mPrey.reduceEnergy(100); } // if (mTutorialStep.equals(TutorialStep.FOOD_TRAINING)) { // mPrey.setStressLevel(StressLevel.PLOK_CLOSE); // } if (mDemonstrator != null) { mDemonstrator.update(); } if (mDemonstrator != null && mDemonstrator.isSatisfied()) { // mOnPauseListener.onToShowNavigation(); int nextTutStep = mTutorialStep.ordinal() + 1; mOnPauseListener.onToShowTutorialText(nextTutStep); if (nextTutStep < TutorialStep.values().length) { mTutorialStep = TutorialStep.values()[nextTutStep]; } else { mOnPauseListener.notifyTutorialFinished(); mTutorialStep = null; } // if (mTutorialStep.equals(TutorialStep.FOOD_TRAINING)) { // // } mToShowDemonstrator = true; if (mDemonstrator.getGraphic() != null) { mDemonstrator.clearGraphic(); } mDemonstrator = null; } else if (mDemonstrator != null && mDemonstrator.isFinished()) { mOnPauseListener.onToShowTutTryText(); mDemonstrator.monitorGoalProgress(); } } @Override protected void saveState() { Log.i(TAG, "Ignoring saveState call"); } // @Override // public void handleTouch(MotionEvent event, boolean doubleTouch) { // Log.i(TAG, "IMHERE"); // handleTouch(event, doubleTouch, false); // } @Override public void handleTouch(MotionEvent event, boolean doubleTouch, boolean nonDemonstratorTouch) { if (mTutorialStep == null) { return; } if (nonDemonstratorTouch) { if (mDemonstrator != null && !mDemonstrator.isFinished()) { Log.i(TAG, "Ignoring touch"); return; } if (mToShowDemonstrator) { // mOnPauseListener.onToHideNavigation(); // mOnPauseListener.onToHideTutorialText(); showDemonstrator(); mOnPauseListener.onToShowTutorialDescriptiveText(); mToShowDemonstrator = false; switch (mTutorialStep) { case NET_TRAINING: mDemonstrator = new NetTrainingDemonstrator(this, mD3GLES20); break; case FOOD_TRAINING: mDemonstrator = new FoodTrainingDemonstrator(this, mD3GLES20); NAlgae algae = mEnv.addNewAlgae(15, new PointF(0, 0), 0); mPrey.setPosition(new PointF(0, 0)); ((FoodTrainingDemonstrator)mDemonstrator).setAlgae(algae); break; case CUT_TRAINING: mDemonstrator = new CutDemonstrator(this, mD3GLES20); mTool = new CatchNet(mEnv, mD3GLES20); break; } //mDemonstrator.initGraphic(); return; } } super.handleTouch(event, doubleTouch, nonDemonstratorTouch); } public void showDemonstrator() { if (mTutorialStep == null) { return; } Log.i(TAG, "showDemonstrator"); // mOnPauseListener.onToHideNavigation(); if (mDemonstrator != null) { mDemonstrator.clearGraphic(); } mOnPauseListener.onToShowTutorialDescriptiveText(); mToShowDemonstrator = false; switch (mTutorialStep) { case NET_TRAINING: mDemonstrator = new NetTrainingDemonstrator(this, mD3GLES20); break; case FOOD_TRAINING: mDemonstrator = new FoodTrainingDemonstrator(this, mD3GLES20); NAlgae algae = mEnv.addNewAlgae(15, new PointF(0, 0), 0); mPrey.setPosition(new PointF(0, 0)); ((FoodTrainingDemonstrator)mDemonstrator).setAlgae(algae); break; case CUT_TRAINING: mDemonstrator = new CutDemonstrator(this, mD3GLES20); mTool = new CatchNet(mEnv, mD3GLES20); break; } //mDemonstrator.initGraphic(); return; } }
Dung2781993/fgm
FGM/FGM/obj/Release/Package/PackageTmp/js/Ballarat/Education/ballarat_tertiary.js
<reponame>Dung2781993/fgm<filename>FGM/FGM/obj/Release/Package/PackageTmp/js/Ballarat/Education/ballarat_tertiary.js var ballarat_tertiary = { "name": { "0": "Federation University", "1": "Australian Catholic University", }, "type": { "0": "Advanced Colleges", "1": "Advanced Colleges", }, "long": { "0": 143.891261, "1": 143.843209, }, "lat": { "0": -37.625884, "1": -37.467029, } }
Shisomo/leetcode_study
Offer_47_Max_Value_Of_Gifts/test.go
<reponame>Shisomo/leetcode_study<filename>Offer_47_Max_Value_Of_Gifts/test.go package main import "fmt" func main() { data := [][]int{{2, 3, 5, 13}, {15, 24, 33, 44}} result := maxValue(data) fmt.Println(result) } func maxValue(grid [][]int) int { for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[0]); j++ { if i == 0 && j == 0 { grid[i][j] = grid[i][j] } else if i == 0 && j != 0 { grid[i][j] += grid[i][j-1] } else if i != 0 && j == 0 { grid[i][j] += grid[i-1][j] } else { grid[i][j] += max(grid[i-1][j], grid[i][j-1]) } } } return grid[len(grid)-1][len(grid[0])-1] } func max(a, b int) int { if a < b { return b } return a }
BrnoPCmaniak/netbox
netbox/dcim/migrations/0064_remove_platform_rpc_client.py
# Generated by Django 2.0.8 on 2018-08-22 16:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dcim', '0063_device_local_context_data'), ] operations = [ migrations.RemoveField( model_name='platform', name='rpc_client', ), ]
j3270/SAMD_Experiments
xdk-asf-3.51.0/sam0/applications/adc_configurations_example/adc_configure.c
/** * \file * * \brief ADC Features Configuration file * * Copyright (c) 2015-2018 Microchip Technology Inc. and its subsidiaries. * * \asf_license_start * * \page License * * Subject to your compliance with these terms, you may use Microchip * software and any derivatives exclusively with Microchip products. * It is your responsibility to comply with third party license terms applicable * to your use of third party software (including open source software) that * may accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, * WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, * INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE * LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL * LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE * SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE * POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT * ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY * RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. * * \asf_license_stop * */ /** * Support and FAQ: visit <a href="https://www.microchip.com/support/">Microchip Support</a> */ #include <asf.h> #include "conf_example.h" #include "adc_configure.h" /* Structure for ADC module instance */ extern struct adc_module adc_instance; static bool correction_measures_done = false; /** * \brief ADC Configuration normal mode. * This function configures ADC as normal mode with below Settings * * GLCK for ADC -> GCLK_GENERATOR_1 (8MHz) * CLK_ADC -> 512 KHz * REFERENCE -> 1/2 VDDANA (1.65V) * POSITIVE INPUT -> PA02 * NEGATIVE INPUT -> GND */ void configure_adc(void) { struct adc_config conf_adc; adc_get_config_defaults(&conf_adc); conf_adc.clock_source = GCLK_GENERATOR_1; conf_adc.reference = ADC_REFERENCE_INTVCC1; conf_adc.clock_prescaler = ADC_CLOCK_PRESCALER_DIV16; conf_adc.positive_input = ADC_POSITIVE_INPUT_PIN0; conf_adc.negative_input = ADC_NEGATIVE_INPUT_GND; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); } /** * \brief ADC Differential mode configuration. * This function configures ADC as differential mode with below Settings * * GLCK for ADC -> GCLK_GENERATOR_1 (8MHz) * CLK_ADC -> 512 KHz * REFERENCE -> 1/2 VDDANA (1.65V) * POSITIVE INPUT -> PA02 * NEGATIVE INPUT -> PA04 */ void configure_adc_differential(void) { struct adc_config conf_adc; adc_get_config_defaults(&conf_adc); conf_adc.clock_source = GCLK_GENERATOR_1; conf_adc.reference = ADC_REFERENCE_INTVCC1; conf_adc.clock_prescaler = ADC_CLOCK_PRESCALER_DIV16; conf_adc.differential_mode = true; conf_adc.positive_input = ADC_POSITIVE_INPUT_PIN0; conf_adc.negative_input = ADC_NEGATIVE_INPUT_PIN4; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); } /** * \brief ADC Averaging mode configuration. * This function configures ADC as Averaging mode with below Settings * * GLCK for ADC -> GCLK_GENERATOR_1 (8MHz) * CLK_ADC -> 512 KHz * REFERENCE -> 1/2 VDDANA (1.65V) * POSITIVE INPUT -> PA02 * NEGATIVE INPUT -> GND * SAMPLES -> 1024 * RESULT_DIV -> 16 */ void configure_adc_averaging(void) { struct adc_config conf_adc; adc_get_config_defaults(&conf_adc); conf_adc.clock_source = GCLK_GENERATOR_1; conf_adc.reference = ADC_REFERENCE_INTVCC1; conf_adc.clock_prescaler = ADC_CLOCK_PRESCALER_DIV16; conf_adc.positive_input = ADC_POSITIVE_INPUT_PIN0; conf_adc.negative_input = ADC_NEGATIVE_INPUT_GND; conf_adc.resolution = ADC_RESOLUTION_CUSTOM; conf_adc.accumulate_samples = ADC_ACCUMULATE_SAMPLES_1024; conf_adc.divide_result = ADC_DIVIDE_RESULT_16; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); } /** * \brief ADC Oversampling mode configuration. * This function configures ADC as Oversampling mode with below Settings * * GLCK for ADC -> GCLK_GENERATOR_1 (8MHz) * CLK_ADC -> 512 KHz * REFERENCE -> 1/2 VDDANA (1.65V) * RESOLUTION -> 16 bit * POSITIVE INPUT -> PA02 * NEGATIVE INPUT -> GND */ void configure_adc_sampling(void) { struct adc_config conf_adc; adc_get_config_defaults(&conf_adc); conf_adc.clock_source = GCLK_GENERATOR_1; conf_adc.reference = ADC_REFERENCE_INTVCC1; conf_adc.clock_prescaler = ADC_CLOCK_PRESCALER_DIV16; conf_adc.positive_input = ADC_POSITIVE_INPUT_PIN0; conf_adc.negative_input = ADC_NEGATIVE_INPUT_GND; conf_adc.resolution = ADC_RESOLUTION_16BIT; conf_adc.reference_compensation_enable = true; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); } /** * \brief ADC Window Monitoring mode configuration. * This function configures ADC as Window Monitoring mode with below Settings * * GLCK for ADC -> GCLK_GENERATOR_1 (8MHz) * CLK_ADC -> 512 KHz * REFERENCE -> 1/2 VDDANA (1.65V) * POSITIVE INPUT -> PA02 * NEGATIVE INPUT -> GND * Threshold low level -> 0.75V * Monitor mode -> Above lower threshold */ void configure_adc_window_monitor(void) { struct adc_config conf_adc; adc_get_config_defaults(&conf_adc); conf_adc.clock_source = GCLK_GENERATOR_1; conf_adc.reference = ADC_REFERENCE_INTVCC1; conf_adc.clock_prescaler = ADC_CLOCK_PRESCALER_DIV16; conf_adc.positive_input = ADC_POSITIVE_INPUT_PIN0; conf_adc.negative_input = ADC_NEGATIVE_INPUT_GND; conf_adc.window.window_mode = ADC_WINDOW_MODE_ABOVE_LOWER; conf_adc.window.window_lower_value = ADC_WINDOW_LOWER_THERSOLD_VALUE; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); } /** * \brief ADC Offset and Gain mode configuration. * This function starts the ADC correction using offset calibration and gain calibration * * GLCK for ADC -> GCLK_GENERATOR_1 (8MHz) * CLK_ADC -> 512 KHz * REFERENCE -> 1/2 VDDANA (1.65V) * POSITIVE INPUT -> PA02 * NEGATIVE INPUT -> GND */ void adc_correction_start(void) { /* ADC channel configuration structure */ struct adc_config conf_adc; uint32_t gain_corr; static uint16_t offset_correction; /* Expected value for gain correction at 1.55V * expected_value = Max. range (12 bits unsigned) * 1.55V / 1.65) */ const uint16_t expected_value = ((ADC_12BIT_FULL_SCALE_VALUE + 1) * ADC_CALIBRATION_IN_VOLTAGE) / (ADC_CALIBRATION_REF_VOLTAGE); /* Captured value for gain correction */ static uint16_t captured_value; if (correction_measures_done == false) { printf("\n*ADC offset correction:\n"); printf("Set PA2 pin to 0 Volt(GND).\n"); printf("Press any key to trigger measurement.\n"); getchar(); /* Capture ADC result for 0 Volt */ offset_correction = adc_start_read_result(); adc_get_config_defaults(&conf_adc); printf("ADC Offset measurement in progress...\n"); gain_corr = ((ADC_12BIT_FULL_SCALE_VALUE + 1) * 1) / 1; /* Enable offset correction */ conf_adc.correction.correction_enable = true; conf_adc.correction.gain_correction = gain_corr; conf_adc.correction.offset_correction = offset_correction; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); printf("ADC Offset measurement complete.\n"); printf("*ADC Gain correction\n"); printf("Set PA2 pin to 1.55 Volt"); printf("Press a key to trigger measurement.\n"); getchar(); /* Capture ADC result for 1.55 Volts */ captured_value = adc_start_read_result(); correction_measures_done = true; } /* Enable offset & gain correction */ adc_get_config_defaults(&conf_adc); printf("ADC Gain correction in progress...\n"); gain_corr = (2048L * expected_value) / captured_value; conf_adc.correction.correction_enable = true; conf_adc.correction.gain_correction = gain_corr; conf_adc.correction.offset_correction = offset_correction; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); printf("ADC Gain correction is complete.\n"); printf("\n* ADC correction enabled: "); printf("\nOffset correction = %d, ", offset_correction); if (expected_value > captured_value) { printf("\nGain correction 1.%03u\n", (uint16_t) ((((uint32_t)expected_value - captured_value) * 1000) / captured_value)); } else { printf("\nGain correction 0.%03u\n", (uint16_t) (((uint32_t)expected_value * 1000) / captured_value)); } } /** * \brief ADC Offset and Gain mode configuration. * This function disable the ADC correction for offset * calibration and gain calibration * */ void adc_correction_stop(void) { struct adc_config conf_adc; adc_get_config_defaults(&conf_adc); conf_adc.correction.correction_enable = false; correction_measures_done = false; adc_init(&adc_instance, ADC, &conf_adc); adc_enable(&adc_instance); }
karajanyp/unityAds-src
src/js/adunit/AbstractAdUnit.js
<reponame>karajanyp/unityAds-src /** * Created by duo on 2016/9/1. */ CMD.register("adunit.AbstractAdUnit", function (require) { var Observable = require("util.Observable"); var FinishState = require("FinishState"); function AbstractAdUnit(nativeBridge, placement, campaign) { this.onStart = new Observable(); this.onNewAdRequestAllowed = new Observable(); this.onClose = new Observable(); this._showing = false; this._nativeBridge = nativeBridge; this._placement = placement; this._campaign = campaign; } AbstractAdUnit.prototype.getPlacement = function () { return this._placement; }; AbstractAdUnit.prototype.getCampaign = function () { return this._campaign; }; AbstractAdUnit.prototype.setFinishState = function (state) { if(this._finishState !== FinishState.COMPLETED){ this._finishState = state; } }; AbstractAdUnit.prototype.getFinishState = function () { return this._finishState; }; AbstractAdUnit.prototype.isShowing = function () { return this._showing; }; AbstractAdUnit.prototype.sendImpressionEvent = function (eventManager, sessionId) { }; AbstractAdUnit.prototype.sendTrackingEvent = function (eventManager, eventName, sessionId) { }; AbstractAdUnit.prototype.sendProgressEvents = function (eventManager, sessionId, n, i) { }; return AbstractAdUnit; });
helloShen/thinkinginjava
chapter13/Exercise15.java
<reponame>helloShen/thinkinginjava /** * Exercise 15 */ package com.ciaoshen.thinkinjava.chapter13; import java.util.*; import java.util.regex.*; import java.io.*; public class Exercise15 { private static final String SPLITER = "\n"; private static String readFile(String path){ //return the file content as a string, otherwise return null StringBuilder sb = new StringBuilder(); File f = new File(path); try{ BufferedReader br = new BufferedReader(new FileReader(new File(path))); try{ String line = null; while(true){ line = br.readLine(); if(line == null){break;} sb.append(line+SPLITER); } return sb.toString(); }finally{ br.close(); } }catch(IOException ioe){ System.out.println("IOException when openning file " + path); return null; } } public static void grep(String regex, String path, int flag){ String content = readFile(path); if(content == null){System.out.println("Check your file path: " + path);return;} Pattern p = Pattern.compile(regex, flag); Matcher m = p.matcher(""); Formatter f = new Formatter(System.out); int index=0; f.format("%1$5.5s %2$-15.15s %3$5.5s \n", "INDEX", "WORD", "POS"); for(String line : content.split(SPLITER)){ m.reset(line); while(m.find()){ f.format("%1$5d: %2$-15.15s %3$5d \n",++index, m.group(), m.start()); } } } private static void unitTestReadFile(){ //test readFile() String rightPath = "/Users/Wei/java/com/ciaoshen/thinkinjava/chapter13/Exercise15.java"; String wrongPath = "/Users/Wei/java/com/ciaoshen/thinkinjava/chapter13/Exercise.java"; System.out.println(readFile(rightPath)); System.out.println(readFile(wrongPath)); } private static void unitTestGrep(String regex){ //test grep() String rightPath = "/Users/Wei/java/com/ciaoshen/thinkinjava/chapter13/Exercise15.java"; String wrongPath = "/Users/Wei/java/com/ciaoshen/thinkinjava/chapter13/Exercise.java"; int flag = Pattern.CASE_INSENSITIVE; grep(regex, rightPath, flag); grep(regex, wrongPath, flag); } public static void main(String[] args){ //单元测试 //Exercise15.unitTestReadFile(); //Exercise15.unitTestGrep("s\\w*"); Exercise15.unitTestGrep("(?)(^|\\W)(s\\w*)(\\W|$)"); } }
metux/chromium-deb
third_party/WebKit/Source/core/paint/TextPainterTest.cpp
// Copyright 2014 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. #include "core/paint/TextPainter.h" #include "core/CSSPropertyNames.h" #include "core/CSSValueKeywords.h" #include "core/css/CSSPrimitiveValue.h" #include "core/frame/Settings.h" #include "core/layout/LayoutTestHelper.h" #include "core/layout/api/LineLayoutText.h" #include "core/paint/PaintInfo.h" #include "core/style/ShadowData.h" #include "core/style/ShadowList.h" #include "platform/graphics/paint/PaintController.h" #include "testing/gtest/include/gtest/gtest.h" #include <memory> namespace blink { namespace { class TextPainterTest : public RenderingTest { public: TextPainterTest() : layout_text_(nullptr), paint_controller_(PaintController::Create()), context_(*paint_controller_) {} protected: LineLayoutText GetLineLayoutText() { return LineLayoutText(layout_text_); } PaintInfo CreatePaintInfo(bool uses_text_as_clip, bool is_printing) { return PaintInfo( context_, IntRect(), uses_text_as_clip ? kPaintPhaseTextClip : kPaintPhaseSelfBlockBackgroundOnly, is_printing ? kGlobalPaintPrinting : kGlobalPaintNormalPhase, 0); } private: void SetUp() override { RenderingTest::SetUp(); SetBodyInnerHTML("Hello world"); layout_text_ = ToLayoutText(GetDocument().body()->firstChild()->GetLayoutObject()); ASSERT_TRUE(layout_text_); ASSERT_EQ("Hello world", layout_text_->GetText()); } LayoutText* layout_text_; std::unique_ptr<PaintController> paint_controller_; GraphicsContext context_; }; TEST_F(TextPainterTest, TextPaintingStyle_Simple) { GetDocument().body()->SetInlineStyleProperty(CSSPropertyColor, CSSValueBlue); GetDocument().View()->UpdateAllLifecyclePhases(); TextPainter::Style text_style = TextPainter::TextPaintingStyle( GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(), CreatePaintInfo(false /* usesTextAsClip */, false /* isPrinting */)); EXPECT_EQ(Color(0, 0, 255), text_style.fill_color); EXPECT_EQ(Color(0, 0, 255), text_style.stroke_color); EXPECT_EQ(Color(0, 0, 255), text_style.emphasis_mark_color); EXPECT_EQ(0, text_style.stroke_width); EXPECT_EQ(nullptr, text_style.shadow); } TEST_F(TextPainterTest, TextPaintingStyle_AllProperties) { GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextFillColor, CSSValueRed); GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextStrokeColor, CSSValueLime); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitTextEmphasisColor, CSSValueBlue); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitTextStrokeWidth, 4, CSSPrimitiveValue::UnitType::kPixels); GetDocument().body()->SetInlineStyleProperty(CSSPropertyTextShadow, "1px 2px 3px yellow"); GetDocument().View()->UpdateAllLifecyclePhases(); TextPainter::Style text_style = TextPainter::TextPaintingStyle( GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(), CreatePaintInfo(false /* usesTextAsClip */, false /* isPrinting */)); EXPECT_EQ(Color(255, 0, 0), text_style.fill_color); EXPECT_EQ(Color(0, 255, 0), text_style.stroke_color); EXPECT_EQ(Color(0, 0, 255), text_style.emphasis_mark_color); EXPECT_EQ(4, text_style.stroke_width); ASSERT_NE(nullptr, text_style.shadow); EXPECT_EQ(1u, text_style.shadow->Shadows().size()); EXPECT_EQ(1, text_style.shadow->Shadows()[0].X()); EXPECT_EQ(2, text_style.shadow->Shadows()[0].Y()); EXPECT_EQ(3, text_style.shadow->Shadows()[0].Blur()); EXPECT_EQ(Color(255, 255, 0), text_style.shadow->Shadows()[0].GetColor().GetColor()); } TEST_F(TextPainterTest, TextPaintingStyle_UsesTextAsClip) { GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextFillColor, CSSValueRed); GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextStrokeColor, CSSValueLime); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitTextEmphasisColor, CSSValueBlue); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitTextStrokeWidth, 4, CSSPrimitiveValue::UnitType::kPixels); GetDocument().body()->SetInlineStyleProperty(CSSPropertyTextShadow, "1px 2px 3px yellow"); GetDocument().View()->UpdateAllLifecyclePhases(); TextPainter::Style text_style = TextPainter::TextPaintingStyle( GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(), CreatePaintInfo(true /* usesTextAsClip */, false /* isPrinting */)); EXPECT_EQ(Color::kBlack, text_style.fill_color); EXPECT_EQ(Color::kBlack, text_style.stroke_color); EXPECT_EQ(Color::kBlack, text_style.emphasis_mark_color); EXPECT_EQ(4, text_style.stroke_width); EXPECT_EQ(nullptr, text_style.shadow); } TEST_F(TextPainterTest, TextPaintingStyle_ForceBackgroundToWhite_NoAdjustmentNeeded) { GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextFillColor, CSSValueRed); GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextStrokeColor, CSSValueLime); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitTextEmphasisColor, CSSValueBlue); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitPrintColorAdjust, CSSValueEconomy); GetDocument().GetSettings()->SetShouldPrintBackgrounds(false); GetDocument().SetPrinting(Document::kPrinting); GetDocument().View()->UpdateAllLifecyclePhases(); TextPainter::Style text_style = TextPainter::TextPaintingStyle( GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(), CreatePaintInfo(false /* usesTextAsClip */, true /* isPrinting */)); EXPECT_EQ(Color(255, 0, 0), text_style.fill_color); EXPECT_EQ(Color(0, 255, 0), text_style.stroke_color); EXPECT_EQ(Color(0, 0, 255), text_style.emphasis_mark_color); } TEST_F(TextPainterTest, TextPaintingStyle_ForceBackgroundToWhite_Darkened) { GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextFillColor, "rgb(255, 220, 220)"); GetDocument().body()->SetInlineStyleProperty(CSSPropertyWebkitTextStrokeColor, "rgb(220, 255, 220)"); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitTextEmphasisColor, "rgb(220, 220, 255)"); GetDocument().body()->SetInlineStyleProperty( CSSPropertyWebkitPrintColorAdjust, CSSValueEconomy); GetDocument().GetSettings()->SetShouldPrintBackgrounds(false); GetDocument().SetPrinting(Document::kPrinting); GetDocument().View()->UpdateAllLifecyclePhases(); TextPainter::Style text_style = TextPainter::TextPaintingStyle( GetLineLayoutText().GetDocument(), GetLineLayoutText().StyleRef(), CreatePaintInfo(false /* usesTextAsClip */, true /* isPrinting */)); EXPECT_EQ(Color(255, 220, 220).Dark(), text_style.fill_color); EXPECT_EQ(Color(220, 255, 220).Dark(), text_style.stroke_color); EXPECT_EQ(Color(220, 220, 255).Dark(), text_style.emphasis_mark_color); } } // namespace } // namespace blink
LaserSrl/KrakeAndroid
core/src/main/java/com/krake/core/collection/FixedSizeList.java
<reponame>LaserSrl/KrakeAndroid package com.krake.core.collection; import androidx.annotation.NonNull; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public final class FixedSizeList<E> implements Collection<E> { final int maxSize; final List<E> delegate; public FixedSizeList(int maxSize) { delegate = new ArrayList<>(maxSize + 1); this.maxSize = maxSize; } public int remainingCapacity() { return maxSize - size(); } public boolean add(E e) { if (maxSize == 0) { return true; } if (size() == maxSize) { delegate.remove(0); } delegate.add(e); return true; } @Override public boolean addAll(Collection<? extends E> collection) { throw new NoSuchMethodError(); } @Override public void clear() { delegate.clear(); } @Override public boolean contains(Object object) { return delegate.contains(object); } @Override public boolean containsAll(Collection<?> collection) { return delegate.containsAll(collection); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @NonNull @Override public Iterator<E> iterator() { return delegate.iterator(); } @Override public boolean remove(Object object) { return delegate.remove(object); } @Override public boolean removeAll(Collection<?> collection) { return delegate.removeAll(collection); } @Override public boolean retainAll(Collection<?> collection) { return delegate.retainAll(collection); } @Override public int size() { return delegate.size(); } @NonNull @Override public Object[] toArray() { return delegate.toArray(); } @NonNull @Override public <T> T[] toArray(T[] array) { return delegate.toArray(array); } }
fredsiika/jluxdesign
src/components/Sections/OurTeamSection.js
<reponame>fredsiika/jluxdesign import React from 'react' import { Col, Container, Row } from 'reactstrap' import TeamMember from '../../components/Teams/TeamMember' const OurTeamSection = (props) => { return ( <section className="section section-lg"> <Container> <Row className="justify-content-center text-center mb-lg"> <Col lg="8"> <h2 className="display-3">The amazing Team</h2> <p className="lead text-muted"> What makes us special is a direct result of our hard working team who work tirelessley to deliver the best quality work. </p> </Col> </Row> <Row> <TeamMember name="<NAME>" jobTitle="Founder/CEO" src={require('assets/img/theme/team-1-800x800.jpg')} facebook="jmoraa" twitter="jmoraa" instagram="jmoraa" linkedin="jmoraa" /> <TeamMember name="<NAME>" jobTitle="Business Partner" src={require('assets/img/theme/team-2-800x800.jpg')} facebook="senquires" twitter="senquires" instagram="senquires" linkedin="senquires" /> <TeamMember name="<NAME>" jobTitle="Stone Distribution Specialist" src={require('assets/img/theme/team-3-800x800.jpg')} facebook="aliu" twitter="aliu" instagram="aliu" linkedin="aliu" /> <TeamMember name="<NAME>" jobTitle="Husband Murderer" src="https://pagesix.com/wp-content/uploads/sites/3/2020/09/91020-carole-baskin-main.jpg?quality=90&strip=all&w=1200" facebook="apoelinitz" twitter="apoelinitz" instagram="apoelinitz" linkedin="apoelinitz" /> <TeamMember name="<NAME>" jobTitle="Stone Fabricator" src={require('assets/img/theme/team-4-800x800.jpg')} facebook="loliver" twitter="loliver" instagram="loliver" linkedin="loliver" /> </Row> </Container> </section> ) } export default OurTeamSection
NightRunner/api-manager
src/main/java/com/cehome/apimanager/model/dto/AmImportTemplateQueryReqDto.java
package com.cehome.apimanager.model.dto; import com.cehome.apimanager.model.po.AmImportTemplate; public class AmImportTemplateQueryReqDto extends AmImportTemplate { private static final long serialVersionUID = -5426976098282932696L; private Integer pageIndex = 1; private Integer pageSize = 20; public Integer getPageIndex() { return pageIndex; } public void setPageIndex(Integer pageIndex) { this.pageIndex = pageIndex; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } }
zhouwentong1993/qmq
qmq-client/src/main/java/qunar/tc/qmq/consumer/pull/PushConsumerParam.java
<reponame>zhouwentong1993/qmq<gh_stars>1000+ package qunar.tc.qmq.consumer.pull; import qunar.tc.qmq.consumer.register.RegistParam; /** * TODO completion javadoc. * * @author xiao.liang * @since 14 January 2020 */ public class PushConsumerParam { private String subject; private String group; private RegistParam registParam; public PushConsumerParam(String subject, String group, RegistParam registParam) { this.subject = subject; this.group = group; this.registParam = registParam; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public RegistParam getRegistParam() { return registParam; } public void setRegistParam(RegistParam registParam) { this.registParam = registParam; } }
ankurshukla1993/IOT-test
coeey/kotlin/_Assertions.java
<filename>coeey/kotlin/_Assertions.java package kotlin; import kotlin.jvm.JvmField; @Metadata(bv = {1, 0, 2}, d1 = {"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\u000b\n\u0002\b\u0002\bÁ\u0002\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002R\u0016\u0010\u0003\u001a\u00020\u00048\u0000X\u0004¢\u0006\b\n\u0000\u0012\u0004\b\u0005\u0010\u0002¨\u0006\u0006"}, d2 = {"Lkotlin/_Assertions;", "", "()V", "ENABLED", "", "ENABLED$annotations", "kotlin-stdlib"}, k = 1, mv = {1, 1, 7}) @PublishedApi /* compiled from: AssertionsJVM.kt */ public final class _Assertions { @JvmField public static final boolean ENABLED = false; public static final _Assertions INSTANCE = null; @PublishedApi public static /* synthetic */ void ENABLED$annotations() { } static { _Assertions kotlin__Assertions = new _Assertions(); } private _Assertions() { INSTANCE = this; ENABLED = getClass().desiredAssertionStatus(); } }
CyberFlameGO/fbme
code/library/src/main/java/org/fbme/lib/iec61499/fbnetwork/FunctionBlockDeclaration.java
package org.fbme.lib.iec61499.fbnetwork; import org.fbme.lib.common.Reference; import org.fbme.lib.iec61499.declarations.FBTypeDeclaration; import org.fbme.lib.iec61499.declarations.ParameterAssignment; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public interface FunctionBlockDeclaration extends FunctionBlockDeclarationBase { @Nullable FBNetwork getContainer(); @NotNull Reference<FBTypeDeclaration> getTypeReference(); }
aleksandarb99/Apoteka_Projekat
Backend/PharmacyProject/src/main/java/com/team11/PharmacyProject/dto/appointment/AppointmentDTO.java
package com.team11.PharmacyProject.dto.appointment; import com.team11.PharmacyProject.dto.pharmacy.PharmacyWorkerDTO; import com.team11.PharmacyProject.enums.AppointmentState; import com.team11.PharmacyProject.enums.AppointmentType; public class AppointmentDTO { private Long id; private Long startTime; private Long endTime; private int duration; private AppointmentState appointmentState; private String info; private double price; private PharmacyWorkerDTO worker; private AppointmentType appointmentType; public AppointmentDTO(Long id, Long startTime, Long endTime, int duration, AppointmentState appointmentState, String info, double price, PharmacyWorkerDTO worker, AppointmentType appointmentType) { this.id = id; this.startTime = startTime; this.endTime = endTime; this.duration = duration; this.appointmentState = appointmentState; this.info = info; this.price = price; this.worker = worker; this.appointmentType = appointmentType; } public AppointmentDTO() { } public PharmacyWorkerDTO getWorker() { return worker; } public void setWorker(PharmacyWorkerDTO worker) { this.worker = worker; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getStartTime() { return startTime; } public void setStartTime(Long startTime) { this.startTime = startTime; } public Long getEndTime() { return endTime; } public void setEndTime(Long endTime) { this.endTime = endTime; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public AppointmentState getAppointmentState() { return appointmentState; } public void setAppointmentState(AppointmentState appointmentState) { this.appointmentState = appointmentState; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public AppointmentType getAppointmentType() { return appointmentType; } public void setAppointmentType(AppointmentType appointmentType) { this.appointmentType = appointmentType; } }
obrienben/openwayback
wayback-cdx-server-core/src/main/java/org/archive/cdxserver/HowManyController.java
package org.archive.cdxserver; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.archive.cdxserver.auth.AuthToken; import org.archive.cdxserver.filter.CDXAccessFilter; import org.archive.format.gzip.zipnum.ZipNumCluster; import org.archive.url.UrlSurtRangeComputer.MatchType; import org.archive.util.ArchiveUtils; import org.archive.util.binsearch.SortedTextFile.CachedStringIterator; import org.archive.util.iterator.CloseableIterator; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class HowManyController extends BaseCDXServer { protected ZipNumCluster mainCluster; protected Map<String, ArrayList<ZipNumCluster>> allClusters; final static String PART_PREFIX = "part-a-"; @Override public void afterPropertiesSet() throws Exception { // This controller only works with SURT-sorted CDXs! this.setSurtMode(true); super.afterPropertiesSet(); } protected long countLines(ZipNumCluster cluster, String start, String end, String[] dates) throws IOException { long numLines = 0; if (cluster.isDisabled()) { return 0; } // optimize for full range lookup if (start.isEmpty() && end.isEmpty()) { numLines = cluster.getTotalLines(); if (numLines > 0) { return numLines; } } // String[] splits = mainCluster.getSummary().getNthSplit(start, end, // split, numSplits) String[] startAndEndBlocks = cluster.getSummary().getRange(start, end); numLines = cluster.getNumLines(startAndEndBlocks); if (numLines <= 1) { numLines = 0; } else { numLines--; } long adjustment = 0; // If less than one block in size, just count the one block if (startAndEndBlocks[0].equals(startAndEndBlocks[1])) { numLines = 0; startAndEndBlocks[1] = null; } else { String startTokens[] = startAndEndBlocks[0].split("\t"); String endTokens[] = startAndEndBlocks[1].split("\t"); int startPart = Integer.parseInt(startTokens[1] .substring(PART_PREFIX.length())); int endPart = Integer.parseInt(endTokens[1].substring(PART_PREFIX .length())); if (startPart < endPart) { adjustment = cluster.getLastBlockDiff(startTokens[0], startPart, endPart); } } int count = 0; CloseableIterator<String> blocklines = null; String firstline = null; String lastline = null; try { blocklines = cluster.getCDXIterator(new CachedStringIterator( startAndEndBlocks[0], startAndEndBlocks[1]), start, end, 0, 1); if (blocklines.hasNext()) { count++; lastline = firstline = blocklines.next(); } while (blocklines.hasNext()) { count++; lastline = blocklines.next(); } } finally { if (blocklines != null) { blocklines.close(); } } numLines *= cluster.getCdxLinesPerBlock(); numLines += count; numLines += adjustment; if (dates != null) { if (firstline != null) { dates[0] = firstline.split(" ")[1]; } if (lastline != null) { dates[1] = lastline.split(" ")[1]; } } return numLines; } public static class FormCommand { private MatchType matchType = MatchType.domain; public FormCommand() { } public FormCommand(MatchType matchType) { this.matchType = matchType; } public MatchType getMatchType() { return matchType; } public void setMatchType(MatchType matchType) { this.matchType = matchType; } } @RequestMapping(value = { "/howmany/{clusterId}" }) public String getHowManyCluster( HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "url", defaultValue = "") String url, @RequestParam(value = "from", defaultValue = "") String from, @RequestParam(value = "to", defaultValue = "") String to, @RequestParam(value = "matchType", defaultValue = "domain") MatchType matchType, @RequestParam(value = "format", defaultValue = "") String format, @PathVariable String clusterId, ModelMap model) throws URISyntaxException, IOException { return getHowMany(request, response, url, from, to, matchType, clusterId, format, model); } @RequestMapping(value = { "/howmany" }) public String getHowMany( HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "url", defaultValue = "") String url, @RequestParam(value = "from", defaultValue = "") String from, @RequestParam(value = "to", defaultValue = "") String to, @RequestParam(value = "matchType", defaultValue = "domain") MatchType matchType, @RequestParam(value = "clusterId", defaultValue = "all") String clusterId, @RequestParam(value = "format", defaultValue = "") String format, ModelMap model) throws URISyntaxException, IOException { String start, end; String host; long numLines = 0; boolean restricted = false; handleAjax(request, response); if (url.isEmpty()) { start = url; end = url; host = "*"; } else { AuthToken authToken = super.createAuthToken(request); CDXAccessFilter accessChecker = null; if (!authChecker.isAllUrlAccessAllowed(authToken)) { accessChecker = authChecker.createAccessFilter(authToken); } String[] startEnd = urlSurtRangeComputer.determineRange(url, matchType, from, to); start = startEnd[0]; end = startEnd[1]; host = startEnd[2]; if (accessChecker != null && !accessChecker.includeUrl(start, url)) { restricted = true; } } String[] firstLastDate = null; if (matchType == MatchType.exact) { firstLastDate = new String[2]; } if (!restricted) { numLines = countAllClusters(clusterId, start, end, firstLastDate); } model.addAttribute("count", Long.valueOf(numLines)); if (format.equals("count")) { return "count"; } FormCommand fcmd = new FormCommand(matchType); model.addAttribute("command", fcmd); model.addAttribute("url", url); model.addAttribute("start", start); model.addAttribute("end", end); model.addAttribute("from", from); model.addAttribute("to", to); if ((matchType == MatchType.exact) && (firstLastDate != null)) { model.addAttribute("first", ArchiveUtils.getDate(firstLastDate[0], new Date())); model.addAttribute("last", ArchiveUtils.getDate(firstLastDate[1], new Date())); } model.addAttribute("host", host); model.addAttribute("matchType", matchType); return "howmany"; } protected long countAllClusters(String clusterId, String start, String end, String[] firstLastDate) throws IOException { List<ZipNumCluster> clusters = null; if (!clusterId.isEmpty() && (allClusters != null)) { clusters = allClusters.get(clusterId); } long numLines; if (clusters == null) { numLines = this.countLines(mainCluster, start, end, firstLastDate); } else { numLines = 0; for (ZipNumCluster cluster : clusters) { long clusterLines = this.countLines(cluster, start, end, firstLastDate); numLines += clusterLines; } } return numLines; } public ZipNumCluster getMainCluster() { return mainCluster; } public void setMainCluster(ZipNumCluster mainCluster) { this.mainCluster = mainCluster; } public Map<String, ArrayList<ZipNumCluster>> getAllClusters() { return allClusters; } public void setAllClusters(Map<String, ArrayList<ZipNumCluster>> allClusters) { this.allClusters = allClusters; } }
qq573011406/FASTBuild_UnrealEngine
Code/Tools/FBuild/FBuildCore/BFF/Functions/FunctionLibrary.h
// FunctionLibrary //------------------------------------------------------------------------------ #pragma once // Includes //------------------------------------------------------------------------------ #include "Function.h" #include "FunctionObjectList.h" // FunctionLibrary //------------------------------------------------------------------------------ class FunctionLibrary : public FunctionObjectList { public: explicit FunctionLibrary(); inline virtual ~FunctionLibrary() override = default; protected: virtual bool AcceptsHeader() const override; virtual bool NeedsHeader() const override; virtual Node * CreateNode() const override; }; //------------------------------------------------------------------------------
KZzizzle/osparc-simcore
services/api-server/src/simcore_service_api_server/db/repositories/_base.py
<filename>services/api-server/src/simcore_service_api_server/db/repositories/_base.py<gh_stars>0 from aiopg.sa.connection import SAConnection class BaseRepository: """ Repositories are pulled at every request All queries to db within that request use same connection """ def __init__(self, conn: SAConnection) -> None: self._conn = conn @property def connection(self) -> SAConnection: return self._conn
sarang-apps/darshan_browser
chrome/browser/previews/previews_lite_page_redirect_url_loader_interceptor.h
<reponame>sarang-apps/darshan_browser<gh_stars>0 // Copyright 2019 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. #ifndef CHROME_BROWSER_PREVIEWS_PREVIEWS_LITE_PAGE_REDIRECT_URL_LOADER_INTERCEPTOR_H_ #define CHROME_BROWSER_PREVIEWS_PREVIEWS_LITE_PAGE_REDIRECT_URL_LOADER_INTERCEPTOR_H_ #include <stdint.h> #include <memory> #include <set> #include "base/memory/scoped_refptr.h" #include "base/sequence_checker.h" #include "chrome/browser/previews/previews_lite_page_redirect_serving_url_loader.h" #include "chrome/browser/previews/previews_lite_page_redirect_url_loader.h" #include "components/previews/content/previews_user_data.h" #include "content/public/browser/url_loader_request_interceptor.h" #include "net/http/http_request_headers.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "url/gurl.h" namespace content { class BrowserContext; class NavigationHandle; } // namespace content class PreviewsLitePageRedirectDecider; namespace previews { // Reasons that a navigation is blacklisted from a lite page redirect preview. // This enum must remain synchronized with the enum // |PreviewsServerLitePageBlacklistReason| in // tools/metrics/histograms/enums.xml. enum class LitePageRedirectBlacklistReason { // DEPRECATED: kPathSuffixBlacklisted = 0, kNavigationToPreviewsDomain = 1, kNavigationToPrivateDomain = 2, kHostBypassBlacklisted = 3, kMaxValue = kHostBypassBlacklisted, }; // Reasons that a navigation is not eligible for a lite page redirect preview. // This enum must remain synchronized with the enum // |PreviewsServerLitePageIneligibleReason| in // tools/metrics/histograms/enums.xml. enum class LitePageRedirectIneligibleReason { kNonHttpsScheme = 0, // DEPRECATED: kHttpPost = 1, kSubframeNavigation = 2, kServerUnavailable = 3, kInfoBarNotSeen = 4, // DEPRECATED: kNetworkNotSlow = 5, kLoadOriginalReload = 6, kCookiesBlocked = 7, // DEPRECATED: kECTUnknown = 8, kExceededMaxNavigationRestarts = 9, // DEPRECATED: kPreviewsState = 10, kInvalidProxyHeaders = 11, kServiceProbeIncomplete = 12, kServiceProbeFailed = 13, kAPIPageTransition = 14, kForwardBackPageTransition = 15, kMaxValue = kForwardBackPageTransition, }; // The response type from the previews server. This enum must // remain synchronized with the enum |PreviewsServerLitePageServerResponse| in // tools/metrics/histograms/enums.xml. enum class LitePageRedirectServerResponse { // A preview was served (HTTP 200). kOk = 0, // The client was redirected to another page (HTTP 307). kRedirect = 1, // The requested preview was not available (HTTP 307). kPreviewUnavailable = 2, // The previews server is not available (HTTP 503). kServiceUnavailable = 3, // The previews server responded with some other HTTP code. kOther = 4, // There was some network error and we did not get a response from the // previews server. kFailed = 5, // The previews server did not respond after a timeout. kTimeout = 6, // The previews server rejected our authentication (HTTP 403). kAuthFailure = 7, // No response headers were available from the preview server. kNoResponseHeaders = 8, // The connection was closed without getting a response. kOnCompleteBeforeOnResponse = 9, // There was an error connecting to the previews server. kConnectionError = 10, kMaxValue = kConnectionError, }; // Records an entry in the lite page redirect ineligibility histogram. void LogLitePageRedirectIneligibleReason( LitePageRedirectIneligibleReason reason); // If the given URL is a LitePage Preview URL, this returns true but does not // change the |url|. This will set |update_virtual_url_with_url| on // NavigationEntry so that |HandlePreviewsLitePageRedirectURLRewriteReverse| is // called when the navigation finishes. Note: This means the virtual URL will // not be set during the navigation load. This is handled separately in UI on // Android. bool HandlePreviewsLitePageRedirectURLRewrite( GURL* url, content::BrowserContext* browser_context); // Handles translating the given Lite Page URL to the original URL. Returns true // if the given |url| was a preview, otherwise returns false and does not change // |url|. bool HandlePreviewsLitePageRedirectURLRewriteReverse( GURL* url, content::BrowserContext* browser_context); // Returns the URL for a preview given by the url. GURL GetLitePageRedirectURLForURL(const GURL& original_url); // A class that attempts to intercept requests and fetch the Lite Page version // of the request. Its lifetime matches that of the content/ navigation loader // code. class PreviewsLitePageRedirectURLLoaderInterceptor : public content::URLLoaderRequestInterceptor { public: PreviewsLitePageRedirectURLLoaderInterceptor( const scoped_refptr<network::SharedURLLoaderFactory>& network_loader_factory, uint64_t page_id, int frame_tree_node_id); ~PreviewsLitePageRedirectURLLoaderInterceptor() override; // Gets the ServerLitePageInfo struct from an existing attempted lite page // navigation, if there is one. If not, returns a new ServerLitePageInfo // initialized with metadata from navigation_handle() and |this| that is owned // by the PreviewsUserData associated with navigation_handle(). static PreviewsUserData::ServerLitePageInfo* GetOrCreateServerLitePageInfo( content::NavigationHandle* navigation_handle, PreviewsLitePageRedirectDecider* manager); // content::URLLaoderRequestInterceptor: void MaybeCreateLoader( const network::ResourceRequest& tentative_resource_request, content::BrowserContext* browser_context, content::URLLoaderRequestInterceptor::LoaderCallback callback) override; private: // Begins an attempt at fetching the lite page version of the URL. void CreateRedirectLoader( const network::ResourceRequest& tentative_resource_request, content::BrowserContext* browser_context, content::URLLoaderRequestInterceptor::LoaderCallback callback); // Creates a redirect URL loader that immediately serves a redirect to // |original_url|. void CreateOriginalURLLoader( const network::ResourceRequest& tentative_resource_request, const GURL& original_url, content::URLLoaderRequestInterceptor::LoaderCallback callback); // Runs |callback| with |handler| and stores |serving_url_loader|. void HandleRedirectLoader( content::URLLoaderRequestInterceptor::LoaderCallback callback, std::unique_ptr<PreviewsLitePageRedirectServingURLLoader> serving_url_loader, RequestHandler handler); // Checks if the pending navigation is a forward/back nav and should be // disallowed according to experiment parameters. bool IsDisallowedFwdBackNavigation(); // All URLs already seen in this navigation. This prevents redirect loops, // etc. std::set<GURL> urls_processed_; // While attempting to fetch a lite page, this object manages communication // with the lite page server and serving redirects. Once, a decision has been // made regarding serving the preview, this object will be null. std::unique_ptr<PreviewsLitePageRedirectURLLoader> redirect_url_loader_; // Once a decision to serve the lite page has been made (based on server // response), this object will exist until a redirect to the lite page URL has // been handed off to the navigation stack and the next request is being // handled. std::unique_ptr<PreviewsLitePageRedirectServingURLLoader> serving_url_loader_; // Factory to create a network service URLLoader. scoped_refptr<network::SharedURLLoaderFactory> network_loader_factory_; // Used in the chrome-proxy header if a preview is attempted. uint64_t page_id_; // Used to create the network service URLLoader. int frame_tree_node_id_; SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(PreviewsLitePageRedirectURLLoaderInterceptor); }; } // namespace previews #endif // CHROME_BROWSER_PREVIEWS_PREVIEWS_LITE_PAGE_REDIRECT_URL_LOADER_INTERCEPTOR_H_
lycheng/leetcode-go
str/code_20.go
<reponame>lycheng/leetcode-go<filename>str/code_20.go package str // Stack use for FILO type Stack struct { Data []string } func newStack() *Stack { s := Stack{} s.Data = make([]string, 0) return &s } func (s *Stack) push(item string) { s.Data = append(s.Data, item) } func (s *Stack) pop() bool { l := len(s.Data) if l <= 0 { return false } s.Data = s.Data[:l-1] return true } func (s *Stack) top() string { l := len(s.Data) if l <= 0 { return "" } return s.Data[l-1] } func (s *Stack) isEmpty() bool { return len(s.Data) == 0 } // https://leetcode.com/problems/valid-parentheses/description/ func isValid(s string) bool { pair := map[string]string{ ")": "(", "}": "{", "]": "[", } stack := newStack() for _, c := range s { symbol := string(c) pairSymbol := pair[symbol] if pairSymbol == "" { stack.push(symbol) } else if stack.isEmpty() { return false } else { if stack.top() != pairSymbol { return false } stack.pop() } } return stack.isEmpty() }
shiruizhao/swift
src/predecl/DirichletDistrDecl.cpp
<reponame>shiruizhao/swift #include "DirichletDistrDecl.h" #include "../ir/ArrayTy.h" #include "../ir/DoubleLiteral.h" #include "../ir/IntLiteral.h" namespace swift { namespace predecl { DirichletDistrDecl::DirichletDistrDecl() : PreDecl(std::string("Dirichlet")) { } DirichletDistrDecl::~DirichletDistrDecl() { } std::shared_ptr<ir::Expr> DirichletDistrDecl::getNew( std::vector<std::shared_ptr<ir::Expr>>& args, fabrica::TypeFactory* fact) const { // Type Checking if (args.size() < 1) return nullptr; // Two Kinds of Accepted Arguments // 1. vector<double> // 2. all double type // 3. matrix // check vector<double> auto dbl = fact->getTy(ir::IRConstString::DOUBLE); auto ary_dbl = fact->getUpdateTy(new ir::ArrayTy(dbl, 1)); auto mtrx = fact->getTy(ir::IRConstString::MATRIX); if (args.size() == 1 && (args[0]->getTyp() == ary_dbl || args[0]->getTyp() == mtrx)) { auto ret = std::make_shared<ir::Distribution>(this->getName(), this); ret->setArgs(args); ret->setTyp(mtrx); ret->processArgRandomness(); ret->setRandom(true); return ret; } // check all double arguments bool okay = true; for (auto a : args) { if (a->getTyp() != dbl) { okay = false; break; } } if (okay) { auto ret = std::make_shared<ir::Distribution>(this->getName(), this); auto arg_n = std::make_shared<ir::IntLiteral>(args.size()); // Note: we need to set ret type for the new argument arg_n->setTyp(fact->getTy(ir::IRConstString::INT)); args.insert(args.begin(), arg_n); ret->setArgs(args); ret->setTyp(ary_dbl); ret->processArgRandomness(); ret->setRandom(true); return ret; } return nullptr; } } }
pdf4j/icepdf
core/src/main/java/org/icepdf/core/pobjects/acroform/DocMDPTransferParam.java
<gh_stars>1-10 /* * Copyright 2006-2016 ICEsoft Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.icepdf.core.pobjects.acroform; import org.icepdf.core.pobjects.Dictionary; import org.icepdf.core.pobjects.Name; import org.icepdf.core.util.Library; import java.util.HashMap; /** * The DocMDP transform method shall be used to detect modifications relative to a signature field that is signed by * the author of a document (the person applying the first signature). A document can contain only one signature field * that contains a DocMDP transform method; it shall be the first signed field in the document. It enables the author * to specify what changes shall be permitted to be made the document and what changes invalidate the author's signature. * <p/> * NOTE <br /> * As discussed earlier, MDP stands for modification detection and prevention. Certification signatures that use the * DocMDP transform method enable detection of disallowed changes specified by the author. In addition, disallowed * changes can also be prevented when the signature dictionary is referred to by the DocMDP entry in the permissions * dictionary (see 12.8.4, Permissions). * <p/> * A certification signature should have a legal attestation dictionary (see 12.8.5, Legal Content Attestations) that * specifies all content that might result in unexpected rendering of the document contents, along with the author's * attestation to such content. This dictionary may be used to establish an author's intent if the integrity of the * document is questioned. * <p/> * The P entry in the DocMDP transform parameters dictionary (see Table 254) shall indicate the author's specification * of which changes to the document will invalidate the signature. (These changes to the document shall also be * prevented if the signature dictionary is referred from the DocMDP entry in the permissions dictionary.) A value of 1 * for P indicates that the document shall be final; that is, any changes shall invalidate the signature. The values 2 * and 3 shall permit modifications that are appropriate for form field or comment work flows. */ public class DocMDPTransferParam extends Dictionary implements TransformParams { /** * The access permissions granted for this document. * Default value: 2. */ public static final Name PERMISSION_KEY = new Name("P"); /** * No changes to the document shall be permitted; any change to the document shall invalidate the signature. */ public static final int PERMISSION_VALUE_NO_CHANGES = 1; /** * 2Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall * invalidate the signature. */ public static final int PERMISSION_VALUE_FORMS_SIGNING = 2; /** * Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other * changes shall invalidate the signature. */ public static final int PERMISSION_VALUE_ANNOTATION_CRUD = 3; public DocMDPTransferParam(Library library, HashMap entries) { super(library, entries); } /** * Get the access permissions granted for this document. * * @return PERMISSION_VALUE_NO_CHANGES, PERMISSION_VALUE_FORMS_SIGNING, PERMISSION_VALUE_ANNOTATION_CRUD or zero * if not set. */ public int getPermissions() { return library.getInt(entries, PERMISSION_KEY); } /** * Gets the DocMDP transform parameters dictionary version. The only valid value shall be 1.2. * NOTE<br /> * this value is a name object, not a number. * * @return always returns 1.2 as a name. */ public Name getVersion() { return new Name("1.2"); } }
gfis/joeis-alt
src/irvine/oeis/a267/A267046.java
<gh_stars>0 package irvine.oeis.a267; // Generated by gen_pattern.pl - DO NOT EDIT here! import irvine.oeis.GeneratingFunctionSequence; /** * A267046 Number of ON (black) cells in the n-th iteration of the "Rule 91" elementary cellular automaton starting with a single ON (black) cell. * @author <NAME> */ public class A267046 extends GeneratingFunctionSequence { // WARNING Conjectural formula: do not use this implementation to extend the sequence. /** Construct the sequence. */ public A267046() { super(0, new long[] {1, 2, 0, 0, 2, 2, -3}, new long[] {1, 0, -2, 0, 1}); } }
little-forest/dbflute-test-active-dockside
src/test/java/org/docksidestage/dockside/dbflute/whitebox/bhv/WxBhvBatchInsertTest.java
package org.docksidestage.dockside.dbflute.whitebox.bhv; import java.util.ArrayList; import java.util.List; import org.dbflute.cbean.result.ListResultBean; import org.dbflute.hook.CallbackContext; import org.dbflute.hook.SqlLogHandler; import org.dbflute.hook.SqlLogInfo; import org.dbflute.hook.SqlResultHandler; import org.dbflute.hook.SqlResultInfo; import org.dbflute.util.Srl; import org.docksidestage.dockside.dbflute.exbhv.MemberBhv; import org.docksidestage.dockside.dbflute.exentity.Member; import org.docksidestage.dockside.unit.UnitContainerTestCase; /** * @author jflute * @since 0.9.7.8 (2010/12/21 Tuesday) */ public class WxBhvBatchInsertTest extends UnitContainerTestCase { // =================================================================================== // Attribute // ========= private MemberBhv memberBhv; // =================================================================================== // After Care // ========== @Override public void tearDown() throws Exception { super.tearDown(); clearSqlLogHandler(); } protected void clearSqlLogHandler() { CallbackContext.clearSqlLogHandlerOnThread(); CallbackContext.clearSqlResultHandlerOnThread(); assertFalse(CallbackContext.isExistCallbackContextOnThread()); assertFalse(CallbackContext.isExistBehaviorCommandHookOnThread()); assertFalse(CallbackContext.isExistSqlLogHandlerOnThread()); assertFalse(CallbackContext.isExistSqlResultHandlerOnThread()); } // =================================================================================== // Same Set // ======== public void test_batchInsert_sameSet_newCreated_basic() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = new Member(); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Provisional(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName3"); member.setMemberAccount("testAccount3"); member.setMemberStatusCode_Withdrawal(); memberList.add(member); } // ## Act ## int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(3, result.length); ListResultBean<Member> actualList = memberBhv.selectList(cb -> { cb.query().setMemberAccount_LikeSearch("testAccount", op -> op.likePrefix()); }); assertEquals(3, actualList.size()); assertEquals("testName1", actualList.get(0).getMemberName()); assertEquals("testName2", actualList.get(1).getMemberName()); assertEquals("testName3", actualList.get(2).getMemberName()); for (Member member : memberList) { // after process if (member.asDBMeta().hasIdentity()) { assertFalse(member.hasPrimaryKeyValue()); } else { assertTrue(member.hasPrimaryKeyValue()); } assertEquals(Long.valueOf(0), member.getVersionNo()); } } public void test_batchInsert_sameSet_selected_basic() { // ## Arrange ## List<Member> memberList; { memberList = memberBhv.selectList(cb -> { cb.query().setMemberId_InScope(newArrayList(1, 3, 7)); }); } { Member member = memberList.get(0); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); } { Member member = memberList.get(1); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Provisional(); } { Member member = memberList.get(2); member.setMemberName("testName3"); member.setMemberAccount("testAccount3"); member.setMemberStatusCode_Withdrawal(); } // ## Act ## int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(3, result.length); ListResultBean<Member> actualList = memberBhv.selectList(cb -> { cb.query().setMemberAccount_LikeSearch("testAccount", op -> op.likePrefix()); }); assertEquals(3, actualList.size()); assertEquals("testName1", actualList.get(0).getMemberName()); assertEquals("testName2", actualList.get(1).getMemberName()); assertEquals("testName3", actualList.get(2).getMemberName()); assertNotSame(memberList.get(0), actualList.get(0)); assertNotSame(memberList.get(1), actualList.get(1)); assertNotSame(memberList.get(2), actualList.get(2)); for (Member member : memberList) { // after process assertEquals(Long.valueOf(0), member.getVersionNo()); } } // =================================================================================== // Fragmented // ========== public void test_batchInsert_fragmented_newCreated() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = new Member(); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Formalized(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName3"); member.setMemberAccount("testAccount3"); member.setMemberStatusCode_Withdrawal(); member.setBirthdate(currentLocalDate()); memberList.add(member); } // ## Act ## memberBhv.batchInsert(memberList); // ## Assert ## { Member member = memberBhv.selectEntityWithDeletedCheck(cb -> { cb.query().setMemberAccount_Equal("testAccount2"); }); assertNull(member.getBirthdate()); } { Member member = memberBhv.selectEntityWithDeletedCheck(cb -> { cb.query().setMemberAccount_Equal("testAccount3"); }); assertNotNull(member.getBirthdate()); } } public void test_batchInsert_fragmented_selected() { // ## Arrange ## List<Member> memberList; { memberList = memberBhv.selectList(cb -> { cb.query().setMemberId_InScope(newArrayList(1, 3, 7)); }); } { Member member = memberList.get(0); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); } { Member member = memberList.get(1); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Formalized(); } { Member member = memberList.get(2); member.setMemberName("testName3"); member.setMemberAccount("testAccount3"); member.setMemberStatusCode_Withdrawal(); member.setBirthdate(currentLocalDate()); } // ## Act ## memberBhv.batchInsert(memberList); // ## Assert ## { Member member = memberBhv.selectEntityWithDeletedCheck(cb -> { cb.query().setMemberAccount_Equal("testAccount2"); }); assertNull(member.getBirthdate()); } { Member member = memberBhv.selectEntityWithDeletedCheck(cb -> { cb.query().setMemberAccount_Equal("testAccount3"); }); assertNotNull(member.getBirthdate()); } ListResultBean<Member> actualList = memberBhv.selectList(cb -> { cb.query().setMemberAccount_LikeSearch("testAccount", op -> op.likePrefix()); }); assertEquals(memberList.get(0).getFormalizedDatetime(), actualList.get(0).getFormalizedDatetime()); assertEquals(memberList.get(1).getFormalizedDatetime(), actualList.get(1).getFormalizedDatetime()); assertEquals(memberList.get(2).getFormalizedDatetime(), actualList.get(2).getFormalizedDatetime()); } // =================================================================================== // Compatible // ========== public void test_batchInsert_compatible_defaultEveryColumn() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); { Member member = new Member(); member.setMemberName("testName1"); member.setMemberAccount("testAccount1"); member.setMemberStatusCode_Formalized(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName2"); member.setMemberAccount("testAccount2"); member.setMemberStatusCode_Formalized(); memberList.add(member); } { Member member = new Member(); member.setMemberName("testName3"); member.setMemberAccount("testAccount3"); member.setMemberStatusCode_Withdrawal(); member.setBirthdate(currentLocalDate()); memberList.add(member); } final List<String> displaySqlList = new ArrayList<String>(); CallbackContext.setSqlLogHandlerOnThread(new SqlLogHandler() { public void handle(SqlLogInfo info) { displaySqlList.add(info.getDisplaySql()); } }); // ## Act ## memberBhv.varyingBatchInsert(memberList, op -> op.xtoBeCompatibleBatchInsertDefaultEveryColumn()); // ## Assert ## assertHasAnyElement(displaySqlList); for (String sql : displaySqlList) { assertTrue(Srl.containsIgnoreCase(sql, "FORMALIZED_DATETIME")); } } // =================================================================================== // Batch Logging // ============= public void test_batchInsert_batchLogging_one() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); for (int i = 0; i < 1; i++) { Member member = new Member(); member.setMemberName("testName" + i); member.setMemberAccount("testAccount" + i); member.setMemberStatusCode_Formalized(); memberList.add(member); } // ## Act ## final List<String> displaySqlList = new ArrayList<String>(); CallbackContext.setSqlLogHandlerOnThread(new SqlLogHandler() { public void handle(SqlLogInfo info) { displaySqlList.add(info.getDisplaySql()); } }); final List<SqlResultInfo> sqlResultList = new ArrayList<SqlResultInfo>(); CallbackContext.setSqlResultHandlerOnThread(new SqlResultHandler() { public void handle(SqlResultInfo info) { sqlResultList.add(info); } }); int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(1, result.length); assertEquals(1, displaySqlList.size()); assertEquals(1, sqlResultList.size()); String sqlResultDisplaySql = sqlResultList.get(0).getSqlLogInfo().getDisplaySql(); assertEquals(1, Srl.count(sqlResultDisplaySql, "insert into")); assertFalse(Srl.startsWith(sqlResultDisplaySql, ln())); } public void test_batchInsert_batchLogging_few() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); for (int i = 0; i < 24; i++) { Member member = new Member(); member.setMemberName("testName" + i); member.setMemberAccount("testAccount" + i); member.setMemberStatusCode_Formalized(); memberList.add(member); } // ## Act ## final List<String> displaySqlList = new ArrayList<String>(); CallbackContext context = new CallbackContext(); context.setSqlLogHandler(new SqlLogHandler() { public void handle(SqlLogInfo info) { displaySqlList.add(info.getDisplaySql()); } }); final List<SqlResultInfo> sqlResultList = new ArrayList<SqlResultInfo>(); context.setSqlResultHandler(new SqlResultHandler() { public void handle(SqlResultInfo info) { sqlResultList.add(info); } }); CallbackContext.setCallbackContextOnThread(context); int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(24, result.length); assertEquals(24, displaySqlList.size()); assertEquals(1, sqlResultList.size()); assertEquals(24, Srl.count(sqlResultList.get(0).getSqlLogInfo().getDisplaySql(), "insert into")); } public void test_batchInsert_batchLogging_just() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); for (int i = 0; i < 100; i++) { Member member = new Member(); member.setMemberName("testName" + i); member.setMemberAccount("testAccount" + i); member.setMemberStatusCode_Formalized(); memberList.add(member); } // ## Act ## final List<String> displaySqlList = new ArrayList<String>(); CallbackContext context = new CallbackContext(); context.setSqlLogHandler(new SqlLogHandler() { public void handle(SqlLogInfo info) { displaySqlList.add(info.getDisplaySql()); } }); final List<SqlResultInfo> sqlResultList = new ArrayList<SqlResultInfo>(); context.setSqlResultHandler(new SqlResultHandler() { public void handle(SqlResultInfo info) { sqlResultList.add(info); } }); CallbackContext.setCallbackContextOnThread(context); int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(100, result.length); assertEquals(100, displaySqlList.size()); assertEquals(1, sqlResultList.size()); assertEquals(100, Srl.count(sqlResultList.get(0).getSqlLogInfo().getDisplaySql(), "insert into")); } public void test_batchInsert_batchLogging_plusOne() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); for (int i = 0; i < 101; i++) { Member member = new Member(); member.setMemberName("testName" + i); member.setMemberAccount("testAccount" + i); member.setMemberStatusCode_Formalized(); memberList.add(member); } // ## Act ## final List<String> displaySqlList = new ArrayList<String>(); CallbackContext context = new CallbackContext(); context.setSqlLogHandler(new SqlLogHandler() { public void handle(SqlLogInfo info) { displaySqlList.add(info.getDisplaySql()); } }); final List<SqlResultInfo> sqlResultList = new ArrayList<SqlResultInfo>(); context.setSqlResultHandler(new SqlResultHandler() { public void handle(SqlResultInfo info) { sqlResultList.add(info); } }); CallbackContext.setCallbackContextOnThread(context); int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(101, result.length); assertEquals(101, displaySqlList.size()); assertEquals(1, sqlResultList.size()); assertEquals(100, Srl.count(sqlResultList.get(0).getSqlLogInfo().getDisplaySql(), "insert into")); } public void test_batchInsert_batchLogging_thousand() { // ## Arrange ## List<Member> memberList = new ArrayList<Member>(); for (int i = 0; i < 1000; i++) { Member member = new Member(); member.setMemberName("testName" + i); member.setMemberAccount("testAccount" + i); member.setMemberStatusCode_Formalized(); memberList.add(member); } // ## Act ## final List<String> displaySqlList = new ArrayList<String>(); CallbackContext context = new CallbackContext(); context.setSqlLogHandler(new SqlLogHandler() { public void handle(SqlLogInfo info) { displaySqlList.add(info.getDisplaySql()); } }); final List<SqlResultInfo> sqlResultList = new ArrayList<SqlResultInfo>(); context.setSqlResultHandler(new SqlResultHandler() { public void handle(SqlResultInfo info) { sqlResultList.add(info); } }); CallbackContext.setCallbackContextOnThread(context); int[] result = memberBhv.batchInsert(memberList); // ## Assert ## assertEquals(1000, result.length); assertEquals(1000, displaySqlList.size()); assertEquals(1, sqlResultList.size()); assertEquals(100, Srl.count(sqlResultList.get(0).getSqlLogInfo().getDisplaySql(), "insert into")); } }
florianjacob/gpuocelot
ocelot/ocelot/translator/test/PtxToIlTranslator.h
/*! \file PtxToIlTranslator.h * \author <NAME> <<EMAIL>> * \date August 9, 2010 * \brief The header file for the PtxToIlTranslator class. */ #ifndef PTX_TO_IL_TRANSLATOR_BIN_H_INCLUDED #define PTX_TO_IL_TRANSLATOR_BIN_H_INCLUDED /*! \brief A class used to transform a PTX file into an IL equivalent */ class PtxToIlTranslator { public: std::string input; public: void translate(); }; #endif
samvera-labs/chimera
app/actors/hyrax/actors/interpret_visibility_actor.rb
require File.join(Gem::Specification.find_by_name("hyrax").full_gem_path, "app/actors/hyrax/actors/interpret_visibility_actor.rb") module Hyrax module Actors # monkey patch to allow embargo_release_date to be in the past class InterpretVisibilityActor < AbstractActor private # When specified, validate embargo is a future date that complies with AdminSet template requirements (if any) def validate_embargo(env, intention, attributes, template) return true unless intention.wants_embargo? embargo_release_date = parse_date(attributes[:embargo_release_date]) # Deepblue::LoggingHelper.bold_debug [ Deepblue::LoggingHelper.here, # Deepblue::LoggingHelper.called_from, # "before test", # "attributes=#{attributes}", # "embargo_release_date=#{embargo_release_date}" ] valid_embargo_release_date = DeepBlueDocs::Application.config.embargo_enforce_future_release_date ? valid_future_date?(env, embargo_release_date) : true # valid_template_embargo_date = valid_template_embargo_date?(env, embargo_release_date, template) # valid_template_visibility_after_embargo = valid_template_visibility_after_embargo?(env, attributes, template) # Deepblue::LoggingHelper.bold_debug [ Deepblue::LoggingHelper.here, # Deepblue::LoggingHelper.called_from, # "after test", # "valid_embargo_release_date=#{valid_embargo_release_date}", # "valid_template_embargo_date=#{valid_template_embargo_date}", # "valid_template_visibility_after_embargo=#{valid_template_visibility_after_embargo}" ] # When embargo required, date must be in future AND matches any template requirements return true if valid_embargo_release_date && valid_template_embargo_date?(env, embargo_release_date, template) && valid_template_visibility_after_embargo?(env, attributes, template) env.curation_concern.errors.add(:visibility, 'When setting visibility to "embargo" you must also specify embargo release date.') if embargo_release_date.blank? false end end end end
aliqin/atui
src/widgets/index.js
import AddressSelect from './AddressSelect/' const VueWidget = { AddressSelect } // require.ensure([], function(require) { // VueWidget.AddressSelect = require('./AddressSelect/') // console.log(VueWidget.AddressSelect) // }) module.exports = VueWidget
ArtisanCloud/PowerWeChat
src/work/invoice/client.go
<gh_stars>10-100 package invoice import ( "github.com/ArtisanCloud/PowerLibs/v2/object" "github.com/ArtisanCloud/PowerWeChat/v2/src/kernel" response2 "github.com/ArtisanCloud/PowerWeChat/v2/src/kernel/response" "github.com/ArtisanCloud/PowerWeChat/v2/src/work/invoice/request" "github.com/ArtisanCloud/PowerWeChat/v2/src/work/invoice/response" ) type Client struct { *kernel.BaseClient } // 查询电子发票 // https://open.work.weixin.qq.com/api/doc/90000/90135/90284 func (comp *Client) GetInvoiceInfo(cardID string, encryptCode string) (*response.ResponseInvoiceGetInfo, error) { result := &response.ResponseInvoiceGetInfo{} data := &object.HashMap{ "card_id": cardID, "encrypt_code": encryptCode, } _, err := comp.HttpPostJson("cgi-bin/card/invoice/reimburse/getinvoiceinfo", data, nil, nil, result) return result, err } // 批量查询电子发票 // https://open.work.weixin.qq.com/api/doc/90000/90135/90287 func (comp *Client) GetInvoiceInfoBatch(invoiceList []*request.RequestCardInvoice) (*response.ResponseInvoiceGetInfoBatch, error) { result := &response.ResponseInvoiceGetInfoBatch{} data := &object.HashMap{ "item_list": invoiceList, } _, err := comp.HttpPostJson("cgi-bin/card/invoice/reimburse/getinvoiceinfobatch", data, nil, nil, result) return result, err } // 更新发票状态 // https://open.work.weixin.qq.com/api/doc/90000/90135/90285 func (comp *Client) UpdateInvoiceStatus(cardID string, encryptCode string, status string) (*response2.ResponseWork, error) { result := &response2.ResponseWork{} data := &object.HashMap{ "card_id": cardID, "encrypt_code": encryptCode, "reimburse_status": status, } _, err := comp.HttpPostJson("cgi-bin/card/invoice/reimburse/updateinvoicestatus", data, nil, nil, result) return result, err } // 批量更新发票状态 // https://open.work.weixin.qq.com/api/doc/90000/90135/90286 func (comp *Client) UpdateStatusBatch(openid string, status string, invoiceList []*request.RequestCardInvoice) (*response2.ResponseWork, error) { result := &response2.ResponseWork{} data := &object.HashMap{ "openid": openid, "reimburse_status": status, "invoice_list": invoiceList, } _, err := comp.HttpPostJson("cgi-bin/card/invoice/reimburse/updatestatusbatch", data, nil, nil, result) return result, err }
andreimironenko/graphics-sdk
GFX_Linux_KM/services4/3rdparty/linux_drm/drm.mod.c
<gh_stars>0 #include <linux/module.h> #include <linux/vermagic.h> #include <linux/compiler.h> MODULE_INFO(vermagic, VERMAGIC_STRING); struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif .arch = MODULE_ARCH_INIT, }; static const struct modversion_info ____versions[] __used __attribute__((section("__versions"))) = { { 0xf004d205, "module_layout" }, { 0x6bc3fbc0, "__unregister_chrdev" }, { 0xe90dcae0, "__request_module" }, { 0x2e81bcd5, "device_remove_file" }, { 0xad41728, "kmalloc_caches" }, { 0x12da5bb2, "__kmalloc" }, { 0xd5b037e1, "kref_put" }, { 0xff178f6, "__aeabi_idivmod" }, { 0xfbc74f64, "__copy_from_user" }, { 0xd4ef51c0, "sysfs_remove_bin_file" }, { 0x5b48a10e, "debugfs_create_dir" }, { 0xaf52d7d8, "mem_map" }, { 0xd6ee688f, "vmalloc" }, { 0x983a81d5, "single_open" }, { 0xa90c928a, "param_ops_int" }, { 0x67c2fa54, "__copy_to_user" }, { 0xd8f795ca, "del_timer" }, { 0x97255bdf, "strlen" }, { 0x91637264, "dev_set_drvdata" }, { 0xc8b57c27, "autoremove_wake_function" }, { 0x3f29cb33, "send_sig" }, { 0x8ea4e672, "single_release" }, { 0xa8cde9a7, "remove_wait_queue" }, { 0x322df6fb, "i2c_transfer" }, { 0xf7802486, "__aeabi_uidivmod" }, { 0x170ec140, "seq_printf" }, { 0xc8a1767d, "remove_proc_entry" }, { 0x353e3fa5, "__get_user_4" }, { 0x20bd24a5, "__register_chrdev" }, { 0xf0ef15b4, "list_sort" }, { 0x74c86cc0, "init_timer_key" }, { 0x62b72b0d, "mutex_unlock" }, { 0x999e8297, "vfree" }, { 0xa2487e0, "unblock_all_signals" }, { 0x87614e23, "debugfs_create_file" }, { 0xc45ef616, "idr_for_each" }, { 0x3c2c5af5, "sprintf" }, { 0x9a1b9fe7, "seq_read" }, { 0x7d11c268, "jiffies" }, { 0xda1a7335, "kasprintf" }, { 0xf6288e02, "__init_waitqueue_head" }, { 0xffd5a395, "default_wake_function" }, { 0xe707d823, "__aeabi_uidiv" }, { 0x407136b1, "__put_user_8" }, { 0xfa2a45e, "__memzero" }, { 0x5f754e5a, "memset" }, { 0xb4689dc9, "proc_mkdir" }, { 0x302c48b, "idr_destroy" }, { 0xc3122819, "device_register" }, { 0x34908c14, "print_hex_dump_bytes" }, { 0xdc798d37, "__mutex_init" }, { 0xea147363, "printk" }, { 0x42224298, "sscanf" }, { 0x71c90087, "memcmp" }, { 0x328a05f1, "strncpy" }, { 0x2414f09c, "fasync_helper" }, { 0x1b1f7f51, "dma_free_coherent" }, { 0x84b183ae, "strncmp" }, { 0xe724dfaf, "debugfs_remove" }, { 0x8e3c9cc3, "vprintk" }, { 0x16305289, "warn_slowpath_null" }, { 0xe16b893b, "mutex_lock" }, { 0xaaf8368d, "vga_client_register" }, { 0x2b13143c, "class_remove_file" }, { 0x6d798e0, "noop_llseek" }, { 0x9a6221c5, "mod_timer" }, { 0x859c6dc7, "request_threaded_irq" }, { 0x7014409d, "class_create_file" }, { 0x4c56dc3f, "i2c_unregister_device" }, { 0xadb3d81e, "up_write" }, { 0xb1b22911, "down_write" }, { 0x9d158ad6, "fput" }, { 0x493f2b7e, "shmem_file_setup" }, { 0x2196324, "__aeabi_idiv" }, { 0x789cfb6a, "kobject_uevent_env" }, { 0x22dfa95, "dma_alloc_coherent" }, { 0x80de231a, "idr_remove" }, { 0x7525431b, "do_mmap_pgoff" }, { 0x8310bd97, "device_create_file" }, { 0x221dfde0, "idr_pre_get" }, { 0x49a1cb68, "module_put" }, { 0x7dceceac, "capable" }, { 0x3ff62317, "local_bh_disable" }, { 0xcd91aa11, "kmem_cache_alloc" }, { 0x813ed040, "idr_remove_all" }, { 0xbc10dd97, "__put_user_4" }, { 0x5635a60a, "vmalloc_user" }, { 0xe0c7d410, "___dma_page_cpu_to_dev" }, { 0x1000e51, "schedule" }, { 0xd62c833f, "schedule_timeout" }, { 0x8a7d1c31, "high_memory" }, { 0xf25cb6ba, "___dma_page_dev_to_cpu" }, { 0xe9ce8b95, "omap_ioremap" }, { 0x799aca4, "local_bh_enable" }, { 0x15331242, "omap_iounmap" }, { 0xc27487dd, "__bug" }, { 0xa0b04675, "vmalloc_32" }, { 0x4b34fbf5, "block_all_signals" }, { 0xc2e058a4, "idr_get_new_above" }, { 0xb9e52429, "__wake_up" }, { 0x1d2e87c6, "do_gettimeofday" }, { 0xfc0a1694, "proc_create_data" }, { 0xfe634f58, "add_wait_queue" }, { 0xa8980339, "seq_lseek" }, { 0x83800bfa, "kref_init" }, { 0x37a0cba, "kfree" }, { 0x2afe192b, "remap_pfn_range" }, { 0x9d669763, "memcpy" }, { 0x75a17bed, "prepare_to_wait" }, { 0x9775cdc, "kref_get" }, { 0x7820b0d2, "sysfs_create_bin_file" }, { 0xe87ed1ce, "idr_replace" }, { 0xd23873fc, "class_destroy" }, { 0x8893fa5d, "finish_wait" }, { 0xb881a0f9, "dev_warn" }, { 0x9c2dd267, "device_unregister" }, { 0x82e5a238, "vm_get_page_prot" }, { 0xb95f98d6, "_memset_io" }, { 0x701d0ebd, "snprintf" }, { 0xa211d7ee, "platform_get_irq" }, { 0x11e985f0, "vmalloc_to_page" }, { 0xb6cc3d16, "dev_set_name" }, { 0x4347b971, "idr_init" }, { 0xb81fd3be, "idr_find" }, { 0x76b141b6, "__class_create" }, { 0xbe75efe0, "i2c_new_device" }, { 0x9288d4b3, "show_class_attr_string" }, { 0xb859f38b, "krealloc" }, { 0xf20dabd8, "free_irq" }, }; static const char __module_depends[] __used __attribute__((section(".modinfo"))) = "depends=";
talos/caustic
test/test/net/caustic/http/ResponseHeadersTest.java
<filename>test/test/net/caustic/http/ResponseHeadersTest.java package net.caustic.http; import static org.junit.Assert.*; import static net.caustic.util.TestUtils.*; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import net.caustic.http.JavaNetResponseHeaders; import net.caustic.http.ResponseHeaders; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ResponseHeadersTest { private final Constructor<ResponseHeaders> constructor; public ResponseHeadersTest(Class<ResponseHeaders> klass) throws Exception { this.constructor = klass.getConstructor(Map.class); } @Parameters public static Collection<Class<?>[]> implementations() { return Arrays.asList(new Class<?>[][] { { JavaNetResponseHeaders.class } }); } @Test public void testGetHeaderNamesIsZeroLengthOnEmpty() throws Exception { ResponseHeaders empty = constructor.newInstance(Collections.emptyMap()); assertEquals(0, empty.getHeaderNames().length); } @Test public void testGetHeaderValuesForNonexistentHeaderIsNull() throws Exception { ResponseHeaders empty = constructor.newInstance(Collections.emptyMap()); assertNull(empty.getHeaderValues(randomString())); } @Test public void testHeaderNames() throws Exception { String headerName = randomString(); String headerValue = randomString(); Map<String, List<String>> map = new HashMap<String, List<String>>(); map.put(headerName, Arrays.asList(headerValue)); ResponseHeaders headers = constructor.newInstance(map); assertEquals(1, headers.getHeaderNames().length); assertEquals(headerName, headers.getHeaderNames()[0]); } @Test public void testHeaderGet() throws Exception { String headerName = randomString(); String headerValue = randomString(); Map<String, List<String>> map = new HashMap<String, List<String>>(); map.put(headerName, Arrays.asList(headerValue)); ResponseHeaders headers = constructor.newInstance(map); assertEquals(1, headers.getHeaderValues(headerName).length); assertEquals(headerValue, headers.getHeaderValues(headerName)[0]); } @Test public void testHeaderGetMultiple() throws Exception { String headerName = randomString(); String headerValue = randomString(); String headerValue2 = randomString(); Map<String, List<String>> map = new HashMap<String, List<String>>(); map.put(headerName, Arrays.asList(headerValue, headerValue2)); ResponseHeaders headers = constructor.newInstance(map); assertEquals(2, headers.getHeaderValues(headerName).length); assertEquals(headerValue, headers.getHeaderValues(headerName)[0]); assertEquals(headerValue2, headers.getHeaderValues(headerName)[1]); } }
ozaytsev86/cartodb
lib/assets/javascripts/dashboard/views/dashboard/list-view/placeholder/placeholder-item-view.js
<reponame>ozaytsev86/cartodb const CoreView = require('backbone/core-view'); const template = require('./placeholder-item-view.tpl'); const AssetsVersion = require('dashboard/helpers/assets-version'); const checkAndBuildOpts = require('builder/helpers/required-opts'); const REQUIRED_OPTS = [ 'configModel' ]; /** * Represents a map card on dashboard. */ module.exports = CoreView.extend({ className: 'MapsList-item', tagName: 'li', initialize: function (opts) { checkAndBuildOpts(opts, REQUIRED_OPTS, this); }, render: function () { this.clearSubViews(); this.$el.html( template({ assetsBase: this._configModel.get('app_assets_base_url'), assetsVersion: AssetsVersion.getAssetsVersion(), desc: this.model.get('short_description'), url: this.model.get('guide_url'), icon: this.model.get('icon') }) ); return this; } });
razzaghi/JTeleBot
api/src/main/java/co/vandenham/telegram/botapi/MessageHandler.java
<filename>api/src/main/java/co/vandenham/telegram/botapi/MessageHandler.java package co.vandenham.telegram.botapi; import co.vandenham.telegram.botapi.types.Message; import java.lang.annotation.*; @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MessageHandler { Message.Type[] contentTypes() default Message.Type.TEXT; }
Farfetch/notarizer
notarizer/test/mocked_data.py
class MockedData: @staticmethod def get_public_key_bytes(): return bytes("dummyPublicKey", "utf-8") @staticmethod def get_private_key_bytes(): return bytes("dummyPrivateKey", "utf-8") @staticmethod def get_fake_valid_history_content(label): history = [ {"CreatedBy": "/bin/sh -c #(nop) LABEL {label}=dummyb64".format(label=label)}, {"CreatedBy": '/bin/sh -c #(nop) CMD ["/hello"]'}, {"CreatedBy": "/bin/sh -c #(nop) COPY file:dummysha in / "}, ] return [hline["CreatedBy"] for hline in history] @staticmethod def get_fake_invalid_history_content(label): history = [ {"CreatedBy": "/bin/sh -c #(nop) LABEL {label}=dummyb64".format(label=label)}, {"CreatedBy": "/bin/sh -c #(nop) COPY file:dummysha in / "}, ] return [hline["CreatedBy"] for hline in history]
i-obraztsov/rambler-ui
src/constants/overlay.js
<gh_stars>100-1000 export const POINTS_X = ['left', 'right', 'center'] export const POINTS_Y = ['top', 'bottom', 'center'] /** * Правила переноса контента, если он выходит за пределы видимости */ export const MAPPING_POINTS = { right: 'left', left: 'right', center: 'center', bottom: 'top', top: 'bottom' }
TurkMvc/lol
src/easymesh/csgbsp.cpp
// // EasyMesh-Csg: The code belonging to CSG operations // // Copyright: (c) 2010-2013 <NAME> <<EMAIL>> // (c) 2010-2013 Benjamin "Touky" Huet <<EMAIL>> // This program is free software; you can redistribute it and/or // modify it under the terms of the Do What The Fuck You Want To // Public License, Version 2, as published by Sam Hocevar. See // http://www.wtfpl.net/ for more details. // #include <lol/engine-internal.h> namespace lol { //-- int CsgBsp::AddLeaf(int leaf_type, vec3 origin, vec3 normal, int above_idx) { if (leaf_type > 2 && leaf_type < -1) return -1; if ((m_tree.count() == 0 && above_idx == -1) || (above_idx >= 0 && above_idx < m_tree.count() && leaf_type > LEAF_CURRENT && leaf_type < LEAF_ABOVE && m_tree[above_idx].m_leaves[leaf_type] == -1)) { if (m_tree.count() != 0) m_tree[above_idx].m_leaves[leaf_type] = (int32_t)m_tree.count(); m_tree.push(CsgBspLeaf(origin, normal, above_idx)); return m_tree.count() - 1; } return -1; } int CsgBsp::TestPoint(int leaf_idx, vec3 point) { if (leaf_idx >= 0 && leaf_idx < m_tree.count()) { vec3 p2o = point - m_tree[leaf_idx].m_origin; if (length(p2o) < TestEpsilon::Get()) return LEAF_CURRENT; float p2o_dot = dot(normalize(p2o), m_tree[leaf_idx].m_normal); if (p2o_dot > TestEpsilon::Get()) return LEAF_FRONT; else if (p2o_dot < -TestEpsilon::Get()) return LEAF_BACK; } return LEAF_CURRENT; } void CsgBsp::AddTriangleToTree(int const &tri_idx, vec3 const &tri_p0, vec3 const &tri_p1, vec3 const &tri_p2) { //<Leaf_Id, v0, v1, v2> array< int, vec3, vec3, vec3 > tri_to_process; //<FW/BW, Leaf_Id, v0, v1, v2, twin_leaf> array< int, int, vec3, vec3, vec3, int > Leaf_to_add; //Tree is empty, so this leaf is the first if (m_tree.count() == 0) { AddLeaf(LEAF_CURRENT, tri_p0, cross(normalize(tri_p1 - tri_p0), normalize(tri_p2 - tri_p1)), LEAF_CURRENT); m_tree.last().m_tri_list.push(tri_idx, tri_p0, tri_p1, tri_p2); return; } tri_to_process.reserve(20); tri_to_process.push(0, tri_p0, tri_p1, tri_p2); while (tri_to_process.count()) { int leaf_idx = tri_to_process.last().m1; vec3 v[3] = { tri_to_process.last().m2, tri_to_process.last().m3, tri_to_process.last().m4 }; int res_nb[3] = { 0, 0, 0 }; int res_side[3] = { -1, -1, -1 }; //Check where each point is located for (int i = 0; i < 3; i++) { int result = TestPoint(leaf_idx, v[i]); if (result != LEAF_CURRENT) { res_nb[result]++; res_side[i] = result; } } //Points are located on each sides, let's do the mumbo-jumbo if (res_nb[LEAF_BACK] && res_nb[LEAF_FRONT]) { //there are two intersections, no more. vec3 isec_v[2] = { vec3(.0f), vec3(.0f) }; int isec_base = 0; int isec_idx = 0; for (int i = 0; i < 3; i++) { vec3 ray = v[(i + 1) % 3] - v[i]; if (TestRayVsPlane(v[i], v[(i + 1) % 3], m_tree[leaf_idx].m_origin, m_tree[leaf_idx].m_normal, isec_v[isec_idx])) ++isec_idx; else isec_base = i; } int v_idx0 = (isec_base == 1)?(1):(0); int v_idx1 = (isec_base == 1)?(0):(1); int leaf_type = res_side[(isec_base + 2) % 3]; tri_to_process.pop(); #if 1 if (m_tree[leaf_idx].m_leaves[leaf_type] == LEAF_CURRENT) Leaf_to_add.push(leaf_type, leaf_idx, v[((isec_base + 2) % 3)], isec_v[v_idx1], isec_v[v_idx0], -1); else tri_to_process.push(leaf_idx, v[((isec_base + 2) % 3)], isec_v[v_idx1], isec_v[v_idx0]); if (m_tree[leaf_idx].m_leaves[1 - leaf_type] == LEAF_CURRENT) { Leaf_to_add.push(1 - leaf_type, leaf_idx, v[isec_base], v[((isec_base + 1) % 3)], isec_v[v_idx0], -1); Leaf_to_add.push(1 - leaf_type, leaf_idx, v[isec_base], isec_v[v_idx0], isec_v[v_idx1], Leaf_to_add.count() - 1); } else { tri_to_process.push(m_tree[leaf_idx].m_leaves[1 - leaf_type], v[isec_base], v[((isec_base + 1) % 3)], isec_v[v_idx0]); tri_to_process.push(m_tree[leaf_idx].m_leaves[1 - leaf_type], v[isec_base], isec_v[v_idx0], isec_v[v_idx1]); } #else vec3 new_v[9] = { v[((isec_base + 2) % 3)], isec_v[v_idx1], isec_v[v_idx0], v[isec_base], v[((isec_base + 1) % 3)], isec_v[v_idx0], v[isec_base], isec_v[v_idx0], isec_v[v_idx1] }; //Error check : Skip the triangle where two points are on the same location. //it fixes the problem of having an intersection with one of the isec-point being on one of the triangle vertices. //(the problem being a very funny infinite loop) for(int k = 0; k < 9; k += 3) { bool skip_tri = false; for(int l = 0; l < 3; l++) { if (length(new_v[k + l] - new_v[k + (l + 1) % 3]) < TestEpsilon::Get()) { skip_tri = true; break; } } if (skip_tri) continue; tri_to_process.push(0, new_v[k], new_v[k + 1], new_v[k + 2]); } #endif } //All points are on one side, transfer to the next leaf else if (res_nb[LEAF_BACK] || res_nb[LEAF_FRONT]) { int new_leaf_type = ((res_nb[LEAF_FRONT])?(LEAF_FRONT):(LEAF_BACK)); int new_leaf = m_tree[leaf_idx].m_leaves[new_leaf_type]; //No leaf exist, so add a new one if (new_leaf == LEAF_CURRENT) { tri_to_process.pop(); Leaf_to_add.push(new_leaf_type, leaf_idx, v[0], v[1], v[2], -1); } else tri_to_process.last().m1 = new_leaf; } //All points are on the current leaf, add the tri_idx to the list of this leaf. else { tri_to_process.pop(); bool already_exist = false; for (int i = 0; !already_exist && i < m_tree[leaf_idx].m_tri_list.count(); i++) already_exist = (m_tree[leaf_idx].m_tri_list[i].m1 == tri_idx); if (!already_exist) m_tree[leaf_idx].m_tri_list.push(tri_idx, tri_p0, tri_p1, tri_p2); } } //Add all leaves to the tree. for (int i = 0; i < Leaf_to_add.count(); i++) { //If we had it to an already existing leaf. if (Leaf_to_add[i].m2 < m_tree.count() && m_tree[Leaf_to_add[i].m2].m_leaves[Leaf_to_add[i].m1] == LEAF_CURRENT) { AddLeaf(Leaf_to_add[i].m1, tri_p0, cross(normalize(tri_p1 - tri_p0), normalize(tri_p2 - tri_p1)), Leaf_to_add[i].m2); m_tree.last().m_tri_list.push(tri_idx, tri_p0, tri_p1, tri_p2); } /* if (Leaf_to_add[i].m6 == -1) { AddLeaf(Leaf_to_add[i].m1, tri_p0, cross(normalize(tri_p1 - tri_p0), normalize(tri_p2 - tri_p1)), Leaf_to_add[i].m2); m_tree.last().m_tri_list.push(tri_idx, tri_p0, tri_p1, tri_p2); } else m_tree[Leaf_to_add[i].m6].m_tri_list.push(tri_idx, tri_p0, tri_p1, tri_p2); */ } } //return 0 when no split has been done. //return 1 when split has been done. //return -1 when error. int CsgBsp::TestTriangleToTree(vec3 const &tri_p0, vec3 const &tri_p1, vec3 const &tri_p2, //In order to easily build the actual vertices list afterward, this list stores each Vertices location and its source vertices & Alpha. //<Point_Loc, Src_V0, Src_V1, Alpha> as { Point_Loc = Src_V0 + (Src_V1 - Src_V0) * Alpha; } array< vec3, int, int, float > &vert_list, //This is the final triangle list : If Side_Status is LEAF_CURRENT, a new test will be done point by point. //<{IN|OUT}side_status, v0, v1, v2> array< int, int, int, int > &tri_list) { //This list stores the current triangles to process. //<Leaf_Id_List, v0, v1, v2, Should_Point_Test> array< array< int >, int, int, int, int > tri_to_process; //Tree is empty, ABORT ! if (m_tree.count() == 0) return -1; //Let's push the source vertices in here. vert_list.push(tri_p0, -1, -1, .0f); vert_list.push(tri_p1, -1, -1, .0f); vert_list.push(tri_p2, -1, -1, .0f); //Let's push the triangle in here. tri_to_process.reserve(20); tri_to_process.push( array< int >(), 0, 1, 2, 0); tri_to_process.last().m1.push(0); while (tri_to_process.count()) { while (tri_to_process.count()) { int leaf_idx = tri_to_process.last().m1.last(); int t[3] = { tri_to_process.last().m2, tri_to_process.last().m3, tri_to_process.last().m4 }; vec3 v[3] = { vert_list[t[0]].m1, vert_list[t[1]].m1, vert_list[t[2]].m1 }; int res_nb[3] = { 0, 0, 0 }; int res_side[3] = { -1, -1, -1 }; //Check where each point is located for (int i = 0; i < 3; i++) { int result = TestPoint(leaf_idx, v[i]); if (result != LEAF_CURRENT) { res_nb[result]++; res_side[i] = result; } } //Points are located on each sides, let's do the mumbo-jumbo if (res_nb[LEAF_BACK] && res_nb[LEAF_FRONT]) { //there are two intersections, no more. vec3 isec_v[2] = { vec3(.0f), vec3(.0f) }; int isec_i[2] = { 0, 0 }; int new_v_idx[2] = { 0, 0 }; int isec_base = 0; int i = 0; for (; i < m_tree[leaf_idx].m_tri_list.count(); i++) { if (TestTriangleVsTriangle(v[0], v[1], v[2], m_tree[leaf_idx].m_tri_list[i].m2, m_tree[leaf_idx].m_tri_list[i].m3, m_tree[leaf_idx].m_tri_list[i].m4, isec_v[0], isec_v[1])) break; } //There was no triangle intersection, the complex case. if (i == m_tree[leaf_idx].m_tri_list.count()) { if (m_tree[leaf_idx].m_leaves[LEAF_FRONT] == LEAF_CURRENT && m_tree[leaf_idx].m_leaves[LEAF_BACK] == LEAF_CURRENT && tri_to_process.last().m1.count() == 1) { tri_list.push(LEAF_CURRENT, tri_to_process.last().m2, tri_to_process.last().m3, tri_to_process.last().m4); tri_to_process.pop(); } else { tri_to_process.last().m1.pop(); //Register the triangle as needing to intersect with Front & back leaves. if (m_tree[leaf_idx].m_leaves[LEAF_FRONT] != LEAF_CURRENT) tri_to_process.last().m1.push(m_tree[leaf_idx].m_leaves[LEAF_FRONT]); if (m_tree[leaf_idx].m_leaves[LEAF_BACK] != LEAF_CURRENT) tri_to_process.last().m1.push(m_tree[leaf_idx].m_leaves[LEAF_BACK]); //Mark the triangle as needing point by point test tri_to_process.last().m5 = 1; } } //there was an intersection, so let's split the triangle. else { //Get intersection on actual triangle sides. if (TestRayVsTriangleSide(v[0], v[1], v[2], isec_v[0], isec_v[1], isec_v[0], isec_i[0], isec_v[1], isec_i[1])) { { for(int k = 0; k < 2; k++) { if (isec_base == isec_i[k]) isec_base++; #if 1 //Skip point creation if it's on the same location a one of the triangle. bool skip_point = false; int l = 0; for(; l < 3; l++) { if (length(v[l] - isec_v[k]) < TestEpsilon::Get()) { skip_point = true; new_v_idx[k] = t[l]; break; } } if (skip_point) continue; #endif new_v_idx[k] = vert_list.count(); vec3 PmV0 = (isec_v[k] - vert_list[t[isec_i[k]]].m1); vec3 V1mV0 = (vert_list[t[(isec_i[k] + 1) % 3]].m1 - vert_list[t[isec_i[k]]].m1); float alpha = length(PmV0) / length(V1mV0); vert_list.push(isec_v[k], t[isec_i[k]], t[(isec_i[k] + 1) % 3], //Alpha = length((Point_Loc - Src_V0) / (Src_V1 - Src_V0)); alpha); } int v_idx0 = (isec_base == 1)?(1):(0); int v_idx1 = (isec_base == 1)?(0):(1); int tri_to_remove = tri_to_process.count() - 1; #if 0 //Leaf_type is the type for the triangle that is alone on its side. int leaf_type = res_side[(isec_base + 2) % 3]; if (m_tree[leaf_idx].m_leaves[leaf_type] == LEAF_CURRENT && tri_to_process.last().m1.last() == 1) tri_list.push(leaf_type, t[(isec_base + 2) % 3], new_v_idx[v_idx1], new_v_idx[v_idx0]); else { tri_to_process.push(array< int >(), t[(isec_base + 2) % 3], new_v_idx[v_idx1], new_v_idx[v_idx0], 0); tri_to_process.last().m1.push(0); } if (m_tree[leaf_idx].m_leaves[1 - leaf_type] == LEAF_CURRENT && tri_to_process.last().m1.last() == 1) { tri_list.push((tri_to_process.last().m5)?(LEAF_CURRENT):(1 - leaf_type), t[isec_base], new_v_idx[((isec_base + 1) % 3)], new_v_idx[v_idx0]); tri_list.push((tri_to_process.last().m5)?(LEAF_CURRENT):(1 - leaf_type), t[isec_base], new_v_idx[v_idx0], new_v_idx[v_idx1]); } else { tri_to_process.push(array< int >(), t[isec_base], t[((isec_base + 1) % 3)], new_v_idx[v_idx0], 0); tri_to_process.last().m1.push(0); tri_to_process.push(array< int >(), t[isec_base], new_v_idx[v_idx0], new_v_idx[v_idx1], 0); tri_to_process.last().m1.push(0); } #else int new_t[9] = { t[(isec_base + 2) % 3], new_v_idx[v_idx1], new_v_idx[v_idx0], t[isec_base], t[((isec_base + 1) % 3)], new_v_idx[v_idx0], t[isec_base], new_v_idx[v_idx0], new_v_idx[v_idx1] }; int new_side[3] = { res_side[(isec_base + 2) % 3], (res_side[isec_base] == LEAF_CURRENT)?(res_side[((isec_base + 1) % 3)]):(res_side[isec_base]), res_side[isec_base] }; //Error check : Skip the triangle where two points are on the same location. //it fixes the problem of having an intersection with one of the isec-point being on one of the triangle vertices. //(the problem being a very funny infinite loop) for(int k = 0; k < 9; k += 3) { #if 1 //Error check bool skip_tri = false; for(int l = 0; l < 3; l++) { if (length(vert_list[new_t[k + l]].m1 - vert_list[new_t[k + (l + 1) % 3]].m1) < TestEpsilon::Get()) { skip_tri = true; break; } } if (skip_tri) continue; #endif #if 0 //Send the newly created triangle back to the beginning tri_to_process.push(array< int >(), new_t[k], new_t[k + 1], new_t[k + 2], 0); tri_to_process.last().m1.push(0); #else //Inherit parent tree if (m_tree[leaf_idx].m_leaves[new_side[k / 3]] == LEAF_CURRENT && tri_to_process[tri_to_remove].m1.count() == 1) tri_list.push(new_side[k / 3], new_t[k], new_t[k + 1], new_t[k + 2]); else { tri_to_process.push(array< int >(), new_t[k], new_t[k + 1], new_t[k + 2], 0); tri_to_process.last().m1 = tri_to_process[tri_to_remove].m1; if (m_tree[leaf_idx].m_leaves[new_side[k / 3]] == LEAF_CURRENT) tri_to_process.last().m1.pop(); else tri_to_process.last().m1.last() = m_tree[leaf_idx].m_leaves[new_side[k / 3]]; } #endif } #endif tri_to_process.remove(tri_to_remove); } } } } //All points are on one side, transfer to the next leaf else if (res_nb[LEAF_BACK] || res_nb[LEAF_FRONT]) { int new_leaf_type = ((res_nb[LEAF_FRONT])?(LEAF_FRONT):(LEAF_BACK)); int new_leaf = m_tree[leaf_idx].m_leaves[new_leaf_type]; //No leaf exist, we're at the end if (new_leaf == LEAF_CURRENT) { //We still need to test other leaves. if (tri_to_process.last().m1.count() > 1) tri_to_process.last().m1.pop(); else { tri_list.push((tri_to_process.last().m5)?(LEAF_CURRENT):(new_leaf_type), tri_to_process.last().m2, tri_to_process.last().m3, tri_to_process.last().m4); tri_to_process.pop(); } } else tri_to_process.last().m1.last() = new_leaf; } //All points are on the current leaf, add the tri_idx to the list of this leaf. else { //TODO : Special case, handle coplanar cut. tri_list.push(LEAF_CURRENT, tri_to_process.last().m2, tri_to_process.last().m3, tri_to_process.last().m4); tri_to_process.pop(); } } //Now that we have all the split points, let's double-check the results for (int i = 0; i < tri_list.count(); i++) { #define TEST_MAX 4 int t[3] = { tri_list[i].m2, tri_list[i].m3, tri_list[i].m4 }; vec3 v[4] = { vert_list[t[0]].m1, vert_list[t[1]].m1, vert_list[t[2]].m1, (vert_list[t[0]].m1 + vert_list[t[1]].m1 + vert_list[t[2]].m1) / 3.0f }; int res_total = 0; int res_nb[3] = { 0, 0, 0 }; int res_Leaf[4] = { 0, 0, 0, 0 }; int res_side[4] = { -1, -1, -1, -1 }; while (res_total < TEST_MAX) { for (int k = 0; k < TEST_MAX; k++) { if (res_Leaf[k] != LEAF_CURRENT) { int result = TestPoint(res_Leaf[k], v[k]); if (result != LEAF_CURRENT) { res_Leaf[k] = m_tree[res_Leaf[k]].m_leaves[result]; res_side[k] = result; if (res_Leaf[k] == LEAF_CURRENT) { res_total++; res_nb[result]++; } } else { res_Leaf[k] = LEAF_CURRENT; res_side[k] = LEAF_CURRENT; res_total++; } } } } int k = 0; if (res_nb[LEAF_BACK] && res_nb[LEAF_FRONT]) { res_total = res_total; tri_list[i].m1 = LEAF_BACK; #if 0 tri_to_process.push( array< int >(), tri_list[i].m2, tri_list[i].m3, tri_list[i].m4, 0); tri_to_process.last().m1.push(0); tri_list.remove(i--); break; #endif } else { for (; k < TEST_MAX; k++) { if (res_side[k] != LEAF_CURRENT) { tri_list[i].m1 = res_side[k]; break; } } if (k == TEST_MAX) tri_list[i].m1 = LEAF_FRONT; } } } if (tri_list.count() == 1) return 0; return 1; } } /* namespace lol */
shaojiankui/iOS10-Runtime-Headers
protocols/_UILayoutEngineSuspending.h
/* Generated by RuntimeBrowser. */ @protocol _UILayoutEngineSuspending <NSObject> @required - (bool)_isLayoutEngineSuspended; - (void)_setLayoutEngineSuspended:(bool)arg1; @end
phamngocson1408/rocket-chip-learn-scala
firrtl/src/main/scala/logger/LoggerAnnotations.scala
<filename>firrtl/src/main/scala/logger/LoggerAnnotations.scala // See LICENSE for license details. package logger import firrtl.annotations.{Annotation, NoTargetAnnotation} import firrtl.options.{HasShellOptions, ShellOption} /** An annotation associated with a Logger command line option */ sealed trait LoggerOption { this: Annotation => } /** Describes the verbosity of information to log * - set with `-ll/--log-level` * - if unset, a [[LogLevelAnnotation]] with the default log level will be emitted * @param level the level of logging */ case class LogLevelAnnotation(globalLogLevel: LogLevel.Value = LogLevel.None) extends NoTargetAnnotation with LoggerOption object LogLevelAnnotation extends HasShellOptions { val options = Seq( new ShellOption[String]( longOption = "log-level", toAnnotationSeq = (a: String) => Seq(LogLevelAnnotation(LogLevel(a))), helpText = s"Set global logging verbosity (default: ${new LoggerOptions().globalLogLevel}", shortOption = Some("ll"), helpValueName = Some("{error|warn|info|debug|trace}") ) ) } /** Describes a mapping of a class to a specific log level * - set with `-cll/--class-log-level` * @param name the class name to log * @param level the verbosity level */ case class ClassLogLevelAnnotation(className: String, level: LogLevel.Value) extends NoTargetAnnotation with LoggerOption object ClassLogLevelAnnotation extends HasShellOptions { val options = Seq( new ShellOption[Seq[String]]( longOption = "class-log-level", toAnnotationSeq = (a: Seq[String]) => a.map { aa => val className :: levelName :: _ = aa.split(":").toList val level = LogLevel(levelName) ClassLogLevelAnnotation(className, level) }, helpText = "Set per-class logging verbosity", shortOption = Some("cll"), helpValueName = Some("<FullClassName:{error|warn|info|debug|trace}>...") ) ) } /** Enables logging to a file (as opposed to STDOUT) * - maps to [[LoggerOptions.logFileName]] * - enabled with `--log-file` */ case class LogFileAnnotation(file: Option[String]) extends NoTargetAnnotation with LoggerOption object LogFileAnnotation extends HasShellOptions { val options = Seq( new ShellOption[String]( longOption = "log-file", toAnnotationSeq = (a: String) => Seq(LogFileAnnotation(Some(a))), helpText = "Log to a file instead of STDOUT", helpValueName = Some("<file>") ) ) } /** Enables class names in log output * - enabled with `-lcn/--log-class-names` */ case object LogClassNamesAnnotation extends NoTargetAnnotation with LoggerOption with HasShellOptions { val options = Seq( new ShellOption[Unit]( longOption = "log-class-names", toAnnotationSeq = (a: Unit) => Seq(LogClassNamesAnnotation), helpText = "Show class names and log level in logging output", shortOption = Some("lcn") ) ) }
skrzj-dev/libxccc
libxccc/xc/include/xc/common/xc_tc_common.h
/* * Copyright block: * * Source file of libxccc project * * Copyright (c) 2018 <NAME>, <EMAIL> * * Licensed under: MIT license; See the file "LICENSE" of libxccc project for more information. * * Copyright block: end */ #ifndef _XC_TC_COMMON_H_ #define _XC_TC_COMMON_H_ /* --- --- --- */ #ifdef __cplusplus extern "C" { #endif /* --- --- --- */ #include <limits.h> #include <stddef.h> #define xc_tc_isValid_idx_staticRange(_VAL_PUBLIC_IDX_) ( ( (_VAL_PUBLIC_IDX_) >= 0 ) && ( (_VAL_PUBLIC_IDX_) < INT_MAX ) ) #define xc_tc_isValid_capacity_staticRange_int(_VAL_PUBLIC_IDX_) ( ( (_VAL_PUBLIC_IDX_) > 0 ) && ( (_VAL_PUBLIC_IDX_) <= INT_MAX ) ) #define xc_tc_isValid_capacity_staticRange_uint(_VAL_PUBLIC_IDX_) ( ( (_VAL_PUBLIC_IDX_) > 0 ) && ( (_VAL_PUBLIC_IDX_) <= INT_MAX ) ) int xc_tc_validate_arrayStaticSize(const size_t capacity, const size_t item_bytesize); int xc_tc_calc_overflow(const size_t dest_initial_capacity, const size_t src_length, size_t* refp_result); typedef struct xc_tc_LLII_idx_t { int idx0; } xc_tc_LLII_idx_t; #define xc_tc_LLII_idx_itz_invalid() {-1} xc_tc_LLII_idx_t xc_tc_LLII_idx_itz(const int idx0 ); #define xc_tc_LLII_idx_isInvalid(_REFP_SELF_) ( -1 == (_REFP_SELF_)->idx0 ) /* --- --- --- */ /* --- --- --- */ #ifdef __cplusplus } #endif /* --- --- --- */ #endif
addstone/derby
java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/ModifyColumnNode.java
<gh_stars>100-1000 /* Derby - Class org.apache.derby.impl.sql.compile.ModifyColumnNode Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.impl.sql.compile; import org.apache.derby.catalog.UUID; import org.apache.derby.catalog.types.DefaultInfoImpl; import org.apache.derby.shared.common.error.StandardException; import org.apache.derby.shared.common.reference.SQLState; import org.apache.derby.iapi.services.context.ContextManager; import org.apache.derby.shared.common.sanity.SanityManager; import org.apache.derby.iapi.sql.dictionary.ColumnDescriptor; import org.apache.derby.iapi.sql.dictionary.ConstraintDescriptor; import org.apache.derby.iapi.sql.dictionary.ConstraintDescriptorList; import org.apache.derby.iapi.sql.dictionary.DataDictionary; import org.apache.derby.iapi.sql.dictionary.DefaultDescriptor; import org.apache.derby.iapi.sql.dictionary.KeyConstraintDescriptor; import org.apache.derby.iapi.sql.dictionary.TableDescriptor; import org.apache.derby.iapi.types.DataTypeDescriptor; import org.apache.derby.iapi.types.TypeId; import org.apache.derby.impl.sql.execute.ColumnInfo; /** * A ModifyColumnNode represents a modify column in an ALTER TABLE statement. * */ class ModifyColumnNode extends ColumnDefinitionNode { int columnPosition = -1; UUID oldDefaultUUID; // Allowed kinds final static int K_MODIFY_COLUMN_TYPE = 0; final static int K_MODIFY_COLUMN_DEFAULT = 1; final static int K_MODIFY_COLUMN_CONSTRAINT = 2; final static int K_MODIFY_COLUMN_CONSTRAINT_NOT_NULL = 3; final static int K_DROP_COLUMN = 4; final static int K_MODIFY_COLUMN_GENERATED_ALWAYS = 5; final static int K_MODIFY_COLUMN_GENERATED_BY_DEFAULT = 6; /** * This class is used to hold logically different objects for * space efficiency. {@code kind} represents the logical object * type. See also {@link ValueNode#isSameNodeKind}. */ final int kind; ModifyColumnNode(int kind, String name, ValueNode defaultNode, DataTypeDescriptor dataTypeServices, long[] autoIncrementInfo, ContextManager cm) throws StandardException { super(name, defaultNode, dataTypeServices, autoIncrementInfo, cm); this.kind = kind; } /** * Get the UUID of the old column default. * * @return The UUID of the old column default. */ @Override UUID getOldDefaultUUID() { return oldDefaultUUID; } /** * Get the column position for the column. * * @return The column position for the column. */ int getColumnPosition() { if (SanityManager.DEBUG) { SanityManager.ASSERT(columnPosition > 0, "columnPosition expected to be > 0"); } return columnPosition; } /** * Check the validity of a user type. Checks that * 1. the column type is either varchar, .... * 2. is the same type after the alter. * 3. length is greater than the old length. * * @exception StandardException Thrown on error */ @Override void checkUserType(TableDescriptor td) throws StandardException { if (kind != K_MODIFY_COLUMN_TYPE) { return; // nothing to do if user not changing length } ColumnDescriptor cd = td.getColumnDescriptor(name); if (cd == null) { throw StandardException.newException( SQLState.LANG_COLUMN_NOT_FOUND_IN_TABLE, name, td.getName()); } DataTypeDescriptor oldType = cd.getType(); setNullability(oldType.isNullable()); // can't change types yet. if (!(oldType.getTypeId().equals(getType().getTypeId()))) { throw StandardException.newException( SQLState.LANG_MODIFY_COLUMN_CHANGE_TYPE, name); } // can only alter the length of varchar, bitvarying columns String typeName = getType().getTypeName(); if (!(typeName.equals(TypeId.VARCHAR_NAME)) && !(typeName.equals(TypeId.VARBIT_NAME))&& !(typeName.equals(TypeId.BLOB_NAME))&& !(typeName.equals(TypeId.CLOB_NAME))) { throw StandardException.newException( SQLState.LANG_MODIFY_COLUMN_INVALID_TYPE); } // cannot decrease the length of a column if (getType().getMaximumWidth() < oldType.getMaximumWidth()) { throw StandardException.newException( SQLState.LANG_MODIFY_COLUMN_INVALID_LENGTH, name); } } /** * Check if the the column can be modified, and throw error if not. * * If the type of a column is being changed (for instance if the length * of the column is being increased) then make sure that this does not * violate any key constraints; * the column being altered is * 1. part of foreign key constraint * ==&gt; ERROR. This references a Primary Key constraint and the * type and lengths of the pkey/fkey must match exactly. * 2. part of a unique/primary key constraint * ==&gt; OK if no fkey references this constraint. * ==&gt; ERROR if any fkey in the system references this constraint. * * @param td The Table Descriptor on which the ALTER is being done. * * @exception StandardException Thrown on Error. * */ void checkExistingConstraints(TableDescriptor td) throws StandardException { if ((kind != K_MODIFY_COLUMN_TYPE) && (kind != K_MODIFY_COLUMN_CONSTRAINT) && (kind != K_MODIFY_COLUMN_CONSTRAINT_NOT_NULL)) return; DataDictionary dd = getDataDictionary(); ConstraintDescriptorList cdl = dd.getConstraintDescriptors(td); int intArray[] = new int[1]; intArray[0] = columnPosition; for (int index = 0; index < cdl.size(); index++) { ConstraintDescriptor existingConstraint = cdl.elementAt(index); if (!(existingConstraint instanceof KeyConstraintDescriptor)) continue; if (!existingConstraint.columnIntersects(intArray)) continue; int constraintType = existingConstraint.getConstraintType(); // cannot change the length of a column that is part of a // foreign key constraint. Must be an exact match between pkey // and fkey columns. if ((constraintType == DataDictionary.FOREIGNKEY_CONSTRAINT) && (kind == K_MODIFY_COLUMN_TYPE)) { throw StandardException.newException( SQLState.LANG_MODIFY_COLUMN_FKEY_CONSTRAINT, name, existingConstraint.getConstraintName()); } else { if (!dd.checkVersion( DataDictionary.DD_VERSION_DERBY_10_4, null)) { // If a column is part of unique constraint it can't be // made nullable in soft upgrade mode from a pre-10.4 db. if (kind == K_MODIFY_COLUMN_CONSTRAINT && (existingConstraint.getConstraintType() == DataDictionary.UNIQUE_CONSTRAINT)) { throw StandardException.newException( SQLState.LANG_MODIFY_COLUMN_EXISTING_CONSTRAINT, name); } } // A column that is part of a primary key // is being made nullable; can't be done. if ((kind == K_MODIFY_COLUMN_CONSTRAINT) && ((existingConstraint.getConstraintType() == DataDictionary.PRIMARYKEY_CONSTRAINT))) { String errorState = (getLanguageConnectionContext().getDataDictionary() .checkVersion(DataDictionary.DD_VERSION_DERBY_10_4, null)) ? SQLState.LANG_MODIFY_COLUMN_EXISTING_PRIMARY_KEY : SQLState.LANG_MODIFY_COLUMN_EXISTING_CONSTRAINT; throw StandardException.newException(errorState, name); } // unique key or primary key. ConstraintDescriptorList refcdl = dd.getForeignKeys(existingConstraint.getUUID()); if (refcdl.size() > 0) { throw StandardException.newException( SQLState.LANG_MODIFY_COLUMN_REFERENCED, name, refcdl.elementAt(0).getConstraintName()); } // Make the statement dependent on the primary key constraint. getCompilerContext().createDependency(existingConstraint); } } } /** * If the column being modified is of character string type, then it should * get its collation from the corresponding column in the TableDescriptor. * This will ensure that at alter table time, the existing character string * type columns do not loose their collation type. If the alter table is * doing a drop column, then we do not need to worry about collation info. * * @param td Table Descriptor that holds the column which is being altered * @throws StandardException */ void useExistingCollation(TableDescriptor td) throws StandardException { ColumnDescriptor cd; // First verify that the column exists cd = td.getColumnDescriptor(name); if (cd == null) { throw StandardException.newException(SQLState.LANG_COLUMN_NOT_FOUND_IN_TABLE, name, td.getName()); } //getType() == null means we are dealing with drop column and hence //no need to worry about collation info if (getType() != null) { if (getType().getTypeId().isStringTypeId()) { setCollationType(cd.getType().getCollationType()); } } } /** * Get the action associated with this node. * * @return The action associated with this node. */ @Override int getAction() { switch (kind) { case K_MODIFY_COLUMN_DEFAULT: if (autoinc_create_or_modify_Start_Increment == ColumnDefinitionNode.MODIFY_AUTOINCREMENT_RESTART_VALUE) { return ColumnInfo.MODIFY_COLUMN_DEFAULT_RESTART; } else if (autoinc_create_or_modify_Start_Increment == ColumnDefinitionNode.MODIFY_AUTOINCREMENT_INC_VALUE) { return ColumnInfo.MODIFY_COLUMN_DEFAULT_INCREMENT; } else if (autoinc_create_or_modify_Start_Increment == ColumnDefinitionNode.MODIFY_AUTOINCREMENT_CYCLE_VALUE) { return ColumnInfo.MODIFY_COLUMN_DEFAULT_CYCLE; } else { return ColumnInfo.MODIFY_COLUMN_DEFAULT_VALUE; } case K_MODIFY_COLUMN_TYPE: return ColumnInfo.MODIFY_COLUMN_TYPE; case K_MODIFY_COLUMN_CONSTRAINT: return ColumnInfo.MODIFY_COLUMN_CONSTRAINT; case K_MODIFY_COLUMN_CONSTRAINT_NOT_NULL: return ColumnInfo.MODIFY_COLUMN_CONSTRAINT_NOT_NULL; case K_DROP_COLUMN: return ColumnInfo.DROP; case K_MODIFY_COLUMN_GENERATED_ALWAYS: return ColumnInfo.MODIFY_COLUMN_GENERATED_ALWAYS; case K_MODIFY_COLUMN_GENERATED_BY_DEFAULT: return ColumnInfo.MODIFY_COLUMN_GENERATED_BY_DEFAULT; default: if (SanityManager.DEBUG) { SanityManager.THROWASSERT("Unexpected type = " + kind); } return 0; } } /** * Check the validity of the default, if any, for this node. * * @param dd The DataDictionary. * @param td The TableDescriptor. * * @exception StandardException Thrown on error */ @Override void bindAndValidateDefault(DataDictionary dd, TableDescriptor td) throws StandardException { ColumnDescriptor cd; // First verify that the column exists cd = td.getColumnDescriptor(name); if (cd == null) { throw StandardException.newException(SQLState.LANG_COLUMN_NOT_FOUND_IN_TABLE, name, td.getName()); } // Get the UUID for the old default DefaultDescriptor defaultDescriptor = cd.getDefaultDescriptor(dd); oldDefaultUUID = (defaultDescriptor == null) ? null : defaultDescriptor.getUUID(); // Remember the column position columnPosition = cd.getPosition(); // No other work to do if no user specified default if (kind != K_MODIFY_COLUMN_DEFAULT) { return; } // If the statement is not setting the column's default, then // recover the old default and re-use it. If the statement is // changing the start value for the auto-increment, then recover // the old increment-by value and re-use it. If the statement is // changing the increment-by value, then recover the old start value // and re-use it. This way, the column alteration only changes the // aspects of the autoincrement settings that it intends to change, // and does not lose the other aspecs. if (keepCurrentDefault) { defaultInfo = (DefaultInfoImpl)cd.getDefaultInfo(); } else { if ( cd.hasGenerationClause() || cd.isAutoincrement() ) { throw StandardException.newException( SQLState.LANG_GEN_COL_DEFAULT, cd.getColumnName() ); } } if (autoinc_create_or_modify_Start_Increment == ColumnDefinitionNode.MODIFY_AUTOINCREMENT_RESTART_VALUE){ autoincrementIncrement = cd.getAutoincInc(); autoincrementCycle = cd.getAutoincCycle(); } if (autoinc_create_or_modify_Start_Increment == ColumnDefinitionNode.MODIFY_AUTOINCREMENT_INC_VALUE){ autoincrementStart = cd.getAutoincStart(); autoincrementCycle = cd.getAutoincCycle(); } if (autoinc_create_or_modify_Start_Increment == ColumnDefinitionNode.MODIFY_AUTOINCREMENT_CYCLE_VALUE){ autoincrementIncrement = cd.getAutoincInc(); autoincrementStart = cd.getAutoincStart(); } /* Fill in the DataTypeServices from the DataDictionary */ type = cd.getType(); // Now validate the default validateDefault(dd, td); } private ColumnDescriptor getLocalColumnDescriptor(String name, TableDescriptor td) throws StandardException { ColumnDescriptor cd; // First verify that the column exists cd = td.getColumnDescriptor(name); if (cd == null) { throw StandardException.newException( SQLState.LANG_COLUMN_NOT_FOUND_IN_TABLE, name, td.getName()); } return cd; } /** * check the validity of autoincrement values in the case that we are * modifying an existing column (includes checking if autoincrement is set * when making a column nullable) */ @Override void validateAutoincrement(DataDictionary dd, TableDescriptor td, int tableType) throws StandardException { ColumnDescriptor cd; // only autoincrement columns can have their generation property changed if ( (kind == K_MODIFY_COLUMN_GENERATED_ALWAYS) || (kind == K_MODIFY_COLUMN_GENERATED_BY_DEFAULT) ) { cd = getLocalColumnDescriptor(name, td); if (!cd.isAutoincrement()) { throw StandardException.newException(SQLState.LANG_AI_CANNOT_ALTER_IDENTITYNESS, getColumnName()); } if (kind == K_MODIFY_COLUMN_GENERATED_BY_DEFAULT) { defaultInfo = createDefaultInfoOfAutoInc(); } // nothing more to do here return; } // a column that has an autoincrement default can't be made nullable if (kind == K_MODIFY_COLUMN_CONSTRAINT) { cd = getLocalColumnDescriptor(name, td); if (cd.isAutoincrement()) { throw StandardException.newException(SQLState.LANG_AI_CANNOT_NULL_AI, getColumnName()); } } if (autoincrementVerify) { cd = getLocalColumnDescriptor(name, td); if (!cd.isAutoincrement()) throw StandardException.newException(SQLState.LANG_INVALID_ALTER_TABLE_ATTRIBUTES, td.getQualifiedName(), name); } if (isAutoincrement == false) return; super.validateAutoincrement(dd, td, tableType); if (getType().isNullable()) throw StandardException.newException(SQLState.LANG_AI_CANNOT_ADD_AI_TO_NULLABLE, getColumnName()); } }
cjh10644/SLIP_LU
SLIP_LU/Source/slip_get_nonzero_pivot.c
<reponame>cjh10644/SLIP_LU<gh_stars>0 //------------------------------------------------------------------------------ // SLIP_LU/slip_get_nonzero_pivot: find a nonzero pivot in a column //------------------------------------------------------------------------------ // SLIP_LU: (c) 2019, <NAME>, <NAME>, <NAME>, // <NAME>, Texas A&M University. All Rights Reserved. See // SLIP_LU/License for the license. //------------------------------------------------------------------------------ # include "SLIP_LU_internal.h" /* This function obtains the first eligible nonzero pivot * This is enabled if the user sets option->pivot = SLIP_FIRST_NONZERO * NOTE: This pivoting scheme is not recommended * * On output, the kth pivot is returned * */ int32_t slip_get_nonzero_pivot // find the first eligible nonzero pivot ( int32_t *pivot, // the index of first eligible nonzero pivot mpz_t* x, // kth column of L and U int32_t* pivs, // vector indicating which rows are pivotal int32_t n, // size of x int32_t top, // nonzero pattern is located in xi[top..n-1] int32_t* xi // nonzero pattern of x ) { if (!x || !pivs || !xi) {return SLIP_INCORRECT_INPUT;} int32_t inew, sgn; *pivot = -1; // used later to check for singular matrix SLIP_info ok; //-------------------------------------------------------------------------- // Iterate accross the nonzeros in x //-------------------------------------------------------------------------- for (int32_t i = top; i < n; i++) { // inew is the location of the ith nonzero inew = xi[i]; // check if x[inew] is an eligible pivot ok = SLIP_mpz_sgn(&sgn, x[inew]); if (ok != SLIP_OK) {return ok;} if (sgn != 0 && pivs [inew] < 0) { *pivot = inew; // End the loop break; } } if (*pivot == -1) { return SLIP_SINGULAR; } else { return SLIP_OK; } }
chenhui0228/sfcsm
sfcsmCtrl/writeLog.py
<gh_stars>1-10 #-*- coding: UTF-8 -*- # author 01107267 # date 2017-05-24 import time class OperateLog: def writeOperateLog(operator, optype, destip, loginfo, opstatus, db): oplog = {} # oplog['operator'] = current_user oplog['operator'] = operator oplog['optype'] = optype oplog['destip'] = destip oplog['description'] = loginfo oplog['operateTime'] = int(round(time.time() * 1000)) oplog['opstatus'] = opstatus db.operationlog.insert(oplog)
Grigory526/2019-fall-polytech-cs
Processing/Section 6/Listing32/Listing32.pyde
i = 0 k = 1 def setup (): size(500, 500) smooth() strokeWeight(30) background(0) def draw (): global i,k stroke(i, 20) line(mouseX -50,mouseY -50, 100+mouseX -50, 100+mouseY -50) line(100+mouseX -50,mouseY -50, mouseX -50, 100+mouseY -50) i +=k if(i == 255): k=-1 if(i == 0): k=1
rds0751/fec-cms
fec/data/jinja2.py
import jinja2 from compressor.contrib.jinja2ext import CompressorExtension def environment(**options): """Create a jinja2 environment with the CompressorExtension added in""" options['extensions'] += [CompressorExtension] env = jinja2.Environment(**options) return env
ScottWinkler/github-api-app
react-ui/src/actions/compare.js
import {getURL} from '../utilities/xmlhttp.js'; var esprima=require('esprima'); var atob = require('atob'); export function setFirstUser(user){ return{ type:"SET_FIRST_USER", user } } export function setSecondUser(user){ return{ type:"SET_SECOND_USER", user } } export function aggregateFirstUserTokens(payload){ return{ type: "AGG_FIRST_USER_TOKENS", payload } } export function aggregateSecondUserTokens(payload){ return{ type: "AGG_SECOND_USER_TOKENS", payload } } export function resetFirstUserData(){ return{ type: "RESET_FIRST_USER_DATA", payload:null } } export function resetSecondUserData(){ return{ type: "RESET_SECOND_USER_DATA", payload:null } } export function aggregateFirstUserCommits(payload){ return{ type: "AGG_FIRST_USER_COMMITS", payload} } export function aggregateSecondUserCommits(payload){ return{ type: "AGG_SECOND_USER_COMMITS", payload} } export function compareLoading(bool){ return{ type: "COMPARE_LOADING", payload:bool } } export function setUser(user, index) { var times = 0; var max_times = 50; return (dispatch) => { dispatch(compareLoading(true)); if (index === 1) { dispatch(setFirstUser(user)) dispatch(resetFirstUserData()); } else { dispatch(setSecondUser(user)) dispatch(resetSecondUserData()); }; var owner = user.profile.login; var repos = user.repos.map((repo) => { return repo.name }); var authtoken = "?access_token=cd9c32832dbe6ca2b0a186ddb04bd1b50b098a82"; repos.forEach((repo) => { //commit data getURL("https://api.github.com/repos/" + owner + "/" + repo + "/stats/participation" + authtoken).then((JSON_commit_count) => { var commit_count = JSON.parse(JSON_commit_count); var total_commits = commit_count.owner.reduce((acc, cur) => acc + cur,0); if (index === 1) { dispatch(aggregateFirstUserCommits(total_commits)); } else { dispatch(aggregateSecondUserCommits(total_commits)); } }, (err) => { console.log(err); }) if (times <= max_times) { getURL("https://api.github.com/repos/" + owner + "/" + repo + "/contents" + authtoken).then((JSON_root_contents) => { var root_contents = JSON.parse(JSON_root_contents); var dir_shas = root_contents.filter((content) => { return content.type === "dir" }).map((dir) => { return dir.sha }); dir_shas.forEach((sha) => { if (times <= max_times) { getURL("https://api.github.com/repos/" + owner + "/" + repo + "/git/trees/" + sha + "?recursive=1" + authtoken) .then((JSON_dir_contents) => { var dir_contents = JSON.parse(JSON_dir_contents); var dir_urls = dir_contents.tree .filter((file) => { return file.path.match(/\.js/); }) .map((file) => { return file.url; }); dir_urls.forEach((url) => { if (times <= max_times) { times++; getURL(url + authtoken).then((JSON_blob) => { var blob = JSON.parse(JSON_blob); var bin = atob(blob.content); var tokens = esprima.tokenize(bin); var total_tokens = tokens.length; var ifs = tokens.filter((token) => { return token.type = "Keyword" && token.value === "if" }).length; var fors = tokens.filter((token) => { return token.type = "Keyword" && token.value === "for" }).length; if (index === 1) { dispatch(aggregateFirstUserTokens({ total_tokens, ifs, fors })) } else { dispatch(aggregateSecondUserTokens({ total_tokens, ifs, fors })) }; }, (err) => { console.log(err); }) } }) }, (err) => { console.log(err); } ); } } ); }, (err) => { console.log(err); } ) } }) setTimeout( ()=>{dispatch(compareLoading(false))},5000); } }
BuildForSDG/Team-250-Backends
src/zerohunger/accounts/tests/test_account_models.py
from rest_framework.test import APITestCase from accounts.models import Farmer, Customer, User class AccountModelsTestCase(APITestCase): def test_farmer_model(self): farmer = Farmer.objects.create_farmer( email="<EMAIL>", phone_number="08075985865", business_name="Davinci 00<NAME>", password="<PASSWORD>" ) self.assertEquals(str(farmer), '<EMAIL>') def test_customer_model(self): customer = Customer.objects.create_customer( email="<EMAIL>", phone_number="08075985865", first_name="<NAME>", last_name="<NAME>", password="<PASSWORD>" ) self.assertEquals(str(customer), '<EMAIL>') def test_user_model(self): user = User.objects.create( email="<EMAIL>", password="<PASSWORD>" ) self.assertEquals(str(user), '<EMAIL>')
gabrielolivrp/design-patterns
java/templatemethod/Basketball.java
package templatemethod; class Basketball extends Game { @Override public void initialize() { System.out.println("5 players"); } @Override public void startPlay() { System.out.println("Start a basketball game."); } @Override public void endPlay() { System.out.println("End a basketball game."); } }
limianwang/goexamples
datastructures/queue/queue.go
package queue import "sync" // Item the type of the queue type Item interface{} //Queue the queue of Items type Queue struct { items []Item lock sync.Mutex } // New creates a new Queue func New() *Queue { s := &Queue{} s.items = []Item{} return s } // Enqueue adds an Item to the end of the queue func (s *Queue) Enqueue(t Item) { s.lock.Lock() defer s.lock.Unlock() s.items = append(s.items, t) } // Dequeue removes an Item from the front func (s *Queue) Dequeue() *Item { s.lock.Lock() defer s.lock.Unlock() item := s.items[0] s.items = s.items[1:len(s.items)] return &item } // Peek returns the Item in the front without removing it func (s *Queue) Peek() *Item { s.lock.Lock() defer s.lock.Unlock() item := s.items[0] return &item } // IsEmpty returns true when the queue is empty func (s *Queue) IsEmpty() bool { return len(s.items) == 0 }
SaiKai/elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/preprocessing/MultiTests.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.core.ml.inference.preprocessing; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Stream; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.XContentParser; public class MultiTests extends PreProcessingTests<Multi> { @Override protected Multi doParseInstance(XContentParser parser) throws IOException { return lenient ? Multi.fromXContentLenient(parser, PreProcessor.PreProcessorParseContext.DEFAULT) : Multi.fromXContentStrict(parser, PreProcessor.PreProcessorParseContext.DEFAULT); } @Override protected Predicate<String> getRandomFieldsExcludeFilter() { return field -> !field.isEmpty(); } @Override protected Multi createTestInstance() { return createRandom(); } public static Multi createRandom() { return createRandom(randomBoolean() ? null : randomBoolean()); } public static Multi createRandom(Boolean isCustom) { final PreProcessor[] processors; if (isCustom == null || isCustom == false) { NGram nGram = NGramTests.createRandom(isCustom); List<PreProcessor> preProcessorList = new ArrayList<>(); preProcessorList.add(nGram); Stream.generate(() -> randomFrom( FrequencyEncodingTests.createRandom(isCustom, randomFrom(nGram.outputFields())), TargetMeanEncodingTests.createRandom(isCustom, randomFrom(nGram.outputFields())), OneHotEncodingTests.createRandom(isCustom, randomFrom(nGram.outputFields())) )).limit(randomIntBetween(1, 10)).forEach(preProcessorList::add); processors = preProcessorList.toArray(PreProcessor[]::new); } else { processors = randomArray( 2, 10, PreProcessor[]::new, () -> randomFrom( FrequencyEncodingTests.createRandom(isCustom), TargetMeanEncodingTests.createRandom(isCustom), OneHotEncodingTests.createRandom(isCustom), NGramTests.createRandom(isCustom) ) ); } return new Multi(processors, isCustom); } @Override protected Writeable.Reader<Multi> instanceReader() { return Multi::new; } public void testReverseLookup() { String field = "text"; NGram nGram = new NGram(field, Collections.singletonList(1), 0, 2, null, "f"); OneHotEncoding oneHotEncoding = new OneHotEncoding("f.10", MapBuilder.<String, String>newMapBuilder() .put("a", "has_a") .put("b", "has_b") .map(), true); Multi multi = new Multi(new PreProcessor[]{nGram, oneHotEncoding}, true); assertThat(multi.reverseLookup(), allOf(hasEntry("has_a", field), hasEntry("has_b", field), hasEntry("f.11", field))); OneHotEncoding oneHotEncodingOutside = new OneHotEncoding("some_other", MapBuilder.<String, String>newMapBuilder() .put("a", "has_3_a") .put("b", "has_3_b") .map(), true); multi = new Multi(new PreProcessor[]{nGram, oneHotEncoding, oneHotEncodingOutside}, true); expectThrows(IllegalArgumentException.class, multi::reverseLookup); } public void testProcessWithFieldPresent() { String field = "text"; NGram nGram = new NGram(field, Collections.singletonList(1), 0, 2, null, "f"); OneHotEncoding oneHotEncoding1 = new OneHotEncoding("f.10", MapBuilder.<String, String>newMapBuilder() .put("a", "has_a") .put("b", "has_b") .map(), true); OneHotEncoding oneHotEncoding2 = new OneHotEncoding("f.11", MapBuilder.<String, String>newMapBuilder() .put("a", "has_2_a") .put("b", "has_2_b") .map(), true); Multi multi = new Multi(new PreProcessor[]{nGram, oneHotEncoding1, oneHotEncoding2}, true); Map<String, Object> fields = randomFieldValues("text", "cat"); multi.process(fields); assertThat(fields, hasEntry("has_a", 0)); assertThat(fields, hasEntry("has_b", 0)); assertThat(fields, hasEntry("has_2_a", 1)); assertThat(fields, hasEntry("has_2_b", 0)); } public void testInputOutputFields() { String field = "text"; NGram nGram = new NGram(field, Collections.singletonList(1), 0, 3, null, "f"); OneHotEncoding oneHotEncoding1 = new OneHotEncoding("f.10", MapBuilder.<String, String>newMapBuilder() .put("a", "has_a") .put("b", "has_b") .map(), true); OneHotEncoding oneHotEncoding2 = new OneHotEncoding("f.11", MapBuilder.<String, String>newMapBuilder() .put("a", "has_2_a") .put("b", "has_2_b") .map(), true); OneHotEncoding oneHotEncoding3 = new OneHotEncoding("some_other", MapBuilder.<String, String>newMapBuilder() .put("a", "has_3_a") .put("b", "has_3_b") .map(), true); Multi multi = new Multi(new PreProcessor[]{nGram, oneHotEncoding1, oneHotEncoding2, oneHotEncoding3}, true); assertThat(multi.inputFields(), contains(field, "some_other")); assertThat(multi.outputFields(), contains( "f.12", "has_a", "has_b", "has_2_a", "has_2_b", "has_3_a", "has_3_b") ); assertThat(multi.getOutputFieldType("f.12"), equalTo("text")); for (String fieldName : new String[]{"has_a", "has_b", "has_2_a", "has_2_b", "has_3_a", "has_3_b"}) { assertThat(multi.getOutputFieldType(fieldName), equalTo("integer")); } } }
viditsethi13/org
tensorflow/src/gen/java/org/bytedeco/tensorflow/OpInputList.java
// Targeted by JavaCPP version 1.5.1-SNAPSHOT: DO NOT EDIT THIS FILE package org.bytedeco.tensorflow; import org.bytedeco.tensorflow.Allocator; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.tensorflow.global.tensorflow.*; // Utility class for representing a list of immutable input tensors // that are passed to the op as a single named argument. @Namespace("tensorflow") @NoOffset @Properties(inherit = org.bytedeco.tensorflow.presets.tensorflow.class) public class OpInputList extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public OpInputList(Pointer p) { super(p); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public OpInputList(long size) { super((Pointer)null); allocateArray(size); } private native void allocateArray(long size); @Override public OpInputList position(long position) { return (OpInputList)super.position(position); } public OpInputList() { super((Pointer)null); allocate(); } private native void allocate(); public OpInputList(OpKernelContext ctx, int start, int stop) { super((Pointer)null); allocate(ctx, start, stop); } private native void allocate(OpKernelContext ctx, int start, int stop); public native @ByRef @Name("operator =") OpInputList put(@Const @ByRef OpInputList other); public native @Const @ByRef @Name("operator []") Tensor get(int i); public native int size(); }
influx6/tlsfs
vendor/github.com/letsencrypt/boulder/sa/proto/sa.pb.go
<gh_stars>0 // Code generated by protoc-gen-go. // source: sa/proto/sa.proto // DO NOT EDIT! /* Package proto is a generated protocol buffer package. It is generated from these files: sa/proto/sa.proto It has these top-level messages: RegistrationID JSONWebKey AuthorizationID GetPendingAuthorizationRequest GetValidAuthorizationsRequest ValidAuthorizations CertificateStatus Serial Range Count CountCertificatesByNamesRequest CountByNames CountRegistrationsByIPRequest CountInvalidAuthorizationsRequest CountOrdersRequest GetSCTReceiptRequest CountFQDNSetsRequest FQDNSetExistsRequest PreviousCertificateExistsRequest Exists MarkCertificateRevokedRequest AddCertificateRequest AddCertificateResponse SignedCertificateTimestamp RevokeAuthorizationsByDomainRequest RevokeAuthorizationsByDomainResponse OrderRequest GetValidOrderAuthorizationsRequest GetOrderForNamesRequest GetAuthorizationsRequest Authorizations AddPendingAuthorizationsRequest AuthorizationIDs */ package proto import proto1 "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import core "github.com/letsencrypt/boulder/core/proto" import ( context "golang.org/x/net/context" grpc "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto1.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto1.ProtoPackageIsVersion2 // please upgrade the proto package type RegistrationID struct { Id *int64 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RegistrationID) Reset() { *m = RegistrationID{} } func (m *RegistrationID) String() string { return proto1.CompactTextString(m) } func (*RegistrationID) ProtoMessage() {} func (*RegistrationID) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *RegistrationID) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } type JSONWebKey struct { Jwk []byte `protobuf:"bytes,1,opt,name=jwk" json:"jwk,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *JSONWebKey) Reset() { *m = JSONWebKey{} } func (m *JSONWebKey) String() string { return proto1.CompactTextString(m) } func (*JSONWebKey) ProtoMessage() {} func (*JSONWebKey) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *JSONWebKey) GetJwk() []byte { if m != nil { return m.Jwk } return nil } type AuthorizationID struct { Id *string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *AuthorizationID) Reset() { *m = AuthorizationID{} } func (m *AuthorizationID) String() string { return proto1.CompactTextString(m) } func (*AuthorizationID) ProtoMessage() {} func (*AuthorizationID) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *AuthorizationID) GetId() string { if m != nil && m.Id != nil { return *m.Id } return "" } type GetPendingAuthorizationRequest struct { RegistrationID *int64 `protobuf:"varint,1,opt,name=registrationID" json:"registrationID,omitempty"` IdentifierType *string `protobuf:"bytes,2,opt,name=identifierType" json:"identifierType,omitempty"` IdentifierValue *string `protobuf:"bytes,3,opt,name=identifierValue" json:"identifierValue,omitempty"` // Result must be valid until at least this Unix timestamp (nanos) ValidUntil *int64 `protobuf:"varint,4,opt,name=validUntil" json:"validUntil,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetPendingAuthorizationRequest) Reset() { *m = GetPendingAuthorizationRequest{} } func (m *GetPendingAuthorizationRequest) String() string { return proto1.CompactTextString(m) } func (*GetPendingAuthorizationRequest) ProtoMessage() {} func (*GetPendingAuthorizationRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *GetPendingAuthorizationRequest) GetRegistrationID() int64 { if m != nil && m.RegistrationID != nil { return *m.RegistrationID } return 0 } func (m *GetPendingAuthorizationRequest) GetIdentifierType() string { if m != nil && m.IdentifierType != nil { return *m.IdentifierType } return "" } func (m *GetPendingAuthorizationRequest) GetIdentifierValue() string { if m != nil && m.IdentifierValue != nil { return *m.IdentifierValue } return "" } func (m *GetPendingAuthorizationRequest) GetValidUntil() int64 { if m != nil && m.ValidUntil != nil { return *m.ValidUntil } return 0 } type GetValidAuthorizationsRequest struct { RegistrationID *int64 `protobuf:"varint,1,opt,name=registrationID" json:"registrationID,omitempty"` Domains []string `protobuf:"bytes,2,rep,name=domains" json:"domains,omitempty"` Now *int64 `protobuf:"varint,3,opt,name=now" json:"now,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetValidAuthorizationsRequest) Reset() { *m = GetValidAuthorizationsRequest{} } func (m *GetValidAuthorizationsRequest) String() string { return proto1.CompactTextString(m) } func (*GetValidAuthorizationsRequest) ProtoMessage() {} func (*GetValidAuthorizationsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *GetValidAuthorizationsRequest) GetRegistrationID() int64 { if m != nil && m.RegistrationID != nil { return *m.RegistrationID } return 0 } func (m *GetValidAuthorizationsRequest) GetDomains() []string { if m != nil { return m.Domains } return nil } func (m *GetValidAuthorizationsRequest) GetNow() int64 { if m != nil && m.Now != nil { return *m.Now } return 0 } type ValidAuthorizations struct { Valid []*ValidAuthorizations_MapElement `protobuf:"bytes,1,rep,name=valid" json:"valid,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *ValidAuthorizations) Reset() { *m = ValidAuthorizations{} } func (m *ValidAuthorizations) String() string { return proto1.CompactTextString(m) } func (*ValidAuthorizations) ProtoMessage() {} func (*ValidAuthorizations) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *ValidAuthorizations) GetValid() []*ValidAuthorizations_MapElement { if m != nil { return m.Valid } return nil } type ValidAuthorizations_MapElement struct { Domain *string `protobuf:"bytes,1,opt,name=domain" json:"domain,omitempty"` Authz *core.Authorization `protobuf:"bytes,2,opt,name=authz" json:"authz,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *ValidAuthorizations_MapElement) Reset() { *m = ValidAuthorizations_MapElement{} } func (m *ValidAuthorizations_MapElement) String() string { return proto1.CompactTextString(m) } func (*ValidAuthorizations_MapElement) ProtoMessage() {} func (*ValidAuthorizations_MapElement) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5, 0} } func (m *ValidAuthorizations_MapElement) GetDomain() string { if m != nil && m.Domain != nil { return *m.Domain } return "" } func (m *ValidAuthorizations_MapElement) GetAuthz() *core.Authorization { if m != nil { return m.Authz } return nil } type CertificateStatus struct { Serial *string `protobuf:"bytes,1,opt,name=serial" json:"serial,omitempty"` SubscriberApproved *bool `protobuf:"varint,2,opt,name=subscriberApproved" json:"subscriberApproved,omitempty"` Status *string `protobuf:"bytes,3,opt,name=status" json:"status,omitempty"` OcspLastUpdated *int64 `protobuf:"varint,4,opt,name=ocspLastUpdated" json:"ocspLastUpdated,omitempty"` RevokedDate *int64 `protobuf:"varint,5,opt,name=revokedDate" json:"revokedDate,omitempty"` RevokedReason *int64 `protobuf:"varint,6,opt,name=revokedReason" json:"revokedReason,omitempty"` LastExpirationNagSent *int64 `protobuf:"varint,7,opt,name=lastExpirationNagSent" json:"lastExpirationNagSent,omitempty"` OcspResponse []byte `protobuf:"bytes,8,opt,name=ocspResponse" json:"ocspResponse,omitempty"` NotAfter *int64 `protobuf:"varint,9,opt,name=notAfter" json:"notAfter,omitempty"` IsExpired *bool `protobuf:"varint,10,opt,name=isExpired" json:"isExpired,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CertificateStatus) Reset() { *m = CertificateStatus{} } func (m *CertificateStatus) String() string { return proto1.CompactTextString(m) } func (*CertificateStatus) ProtoMessage() {} func (*CertificateStatus) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *CertificateStatus) GetSerial() string { if m != nil && m.Serial != nil { return *m.Serial } return "" } func (m *CertificateStatus) GetSubscriberApproved() bool { if m != nil && m.SubscriberApproved != nil { return *m.SubscriberApproved } return false } func (m *CertificateStatus) GetStatus() string { if m != nil && m.Status != nil { return *m.Status } return "" } func (m *CertificateStatus) GetOcspLastUpdated() int64 { if m != nil && m.OcspLastUpdated != nil { return *m.OcspLastUpdated } return 0 } func (m *CertificateStatus) GetRevokedDate() int64 { if m != nil && m.RevokedDate != nil { return *m.RevokedDate } return 0 } func (m *CertificateStatus) GetRevokedReason() int64 { if m != nil && m.RevokedReason != nil { return *m.RevokedReason } return 0 } func (m *CertificateStatus) GetLastExpirationNagSent() int64 { if m != nil && m.LastExpirationNagSent != nil { return *m.LastExpirationNagSent } return 0 } func (m *CertificateStatus) GetOcspResponse() []byte { if m != nil { return m.OcspResponse } return nil } func (m *CertificateStatus) GetNotAfter() int64 { if m != nil && m.NotAfter != nil { return *m.NotAfter } return 0 } func (m *CertificateStatus) GetIsExpired() bool { if m != nil && m.IsExpired != nil { return *m.IsExpired } return false } type Serial struct { Serial *string `protobuf:"bytes,1,opt,name=serial" json:"serial,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Serial) Reset() { *m = Serial{} } func (m *Serial) String() string { return proto1.CompactTextString(m) } func (*Serial) ProtoMessage() {} func (*Serial) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (m *Serial) GetSerial() string { if m != nil && m.Serial != nil { return *m.Serial } return "" } type Range struct { Earliest *int64 `protobuf:"varint,1,opt,name=earliest" json:"earliest,omitempty"` Latest *int64 `protobuf:"varint,2,opt,name=latest" json:"latest,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Range) Reset() { *m = Range{} } func (m *Range) String() string { return proto1.CompactTextString(m) } func (*Range) ProtoMessage() {} func (*Range) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (m *Range) GetEarliest() int64 { if m != nil && m.Earliest != nil { return *m.Earliest } return 0 } func (m *Range) GetLatest() int64 { if m != nil && m.Latest != nil { return *m.Latest } return 0 } type Count struct { Count *int64 `protobuf:"varint,1,opt,name=count" json:"count,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Count) Reset() { *m = Count{} } func (m *Count) String() string { return proto1.CompactTextString(m) } func (*Count) ProtoMessage() {} func (*Count) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } func (m *Count) GetCount() int64 { if m != nil && m.Count != nil { return *m.Count } return 0 } type CountCertificatesByNamesRequest struct { Range *Range `protobuf:"bytes,1,opt,name=range" json:"range,omitempty"` Names []string `protobuf:"bytes,2,rep,name=names" json:"names,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CountCertificatesByNamesRequest) Reset() { *m = CountCertificatesByNamesRequest{} } func (m *CountCertificatesByNamesRequest) String() string { return proto1.CompactTextString(m) } func (*CountCertificatesByNamesRequest) ProtoMessage() {} func (*CountCertificatesByNamesRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } func (m *CountCertificatesByNamesRequest) GetRange() *Range { if m != nil { return m.Range } return nil } func (m *CountCertificatesByNamesRequest) GetNames() []string { if m != nil { return m.Names } return nil } type CountByNames struct { CountByNames []*CountByNames_MapElement `protobuf:"bytes,1,rep,name=countByNames" json:"countByNames,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CountByNames) Reset() { *m = CountByNames{} } func (m *CountByNames) String() string { return proto1.CompactTextString(m) } func (*CountByNames) ProtoMessage() {} func (*CountByNames) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } func (m *CountByNames) GetCountByNames() []*CountByNames_MapElement { if m != nil { return m.CountByNames } return nil } type CountByNames_MapElement struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Count *int64 `protobuf:"varint,2,opt,name=count" json:"count,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CountByNames_MapElement) Reset() { *m = CountByNames_MapElement{} } func (m *CountByNames_MapElement) String() string { return proto1.CompactTextString(m) } func (*CountByNames_MapElement) ProtoMessage() {} func (*CountByNames_MapElement) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11, 0} } func (m *CountByNames_MapElement) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *CountByNames_MapElement) GetCount() int64 { if m != nil && m.Count != nil { return *m.Count } return 0 } type CountRegistrationsByIPRequest struct { Ip []byte `protobuf:"bytes,1,opt,name=ip" json:"ip,omitempty"` Range *Range `protobuf:"bytes,2,opt,name=range" json:"range,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CountRegistrationsByIPRequest) Reset() { *m = CountRegistrationsByIPRequest{} } func (m *CountRegistrationsByIPRequest) String() string { return proto1.CompactTextString(m) } func (*CountRegistrationsByIPRequest) ProtoMessage() {} func (*CountRegistrationsByIPRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } func (m *CountRegistrationsByIPRequest) GetIp() []byte { if m != nil { return m.Ip } return nil } func (m *CountRegistrationsByIPRequest) GetRange() *Range { if m != nil { return m.Range } return nil } type CountInvalidAuthorizationsRequest struct { RegistrationID *int64 `protobuf:"varint,1,opt,name=registrationID" json:"registrationID,omitempty"` Hostname *string `protobuf:"bytes,2,opt,name=hostname" json:"hostname,omitempty"` // Count authorizations that expire in this range. Range *Range `protobuf:"bytes,3,opt,name=range" json:"range,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CountInvalidAuthorizationsRequest) Reset() { *m = CountInvalidAuthorizationsRequest{} } func (m *CountInvalidAuthorizationsRequest) String() string { return proto1.CompactTextString(m) } func (*CountInvalidAuthorizationsRequest) ProtoMessage() {} func (*CountInvalidAuthorizationsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} } func (m *CountInvalidAuthorizationsRequest) GetRegistrationID() int64 { if m != nil && m.RegistrationID != nil { return *m.RegistrationID } return 0 } func (m *CountInvalidAuthorizationsRequest) GetHostname() string { if m != nil && m.Hostname != nil { return *m.Hostname } return "" } func (m *CountInvalidAuthorizationsRequest) GetRange() *Range { if m != nil { return m.Range } return nil } type CountOrdersRequest struct { AccountID *int64 `protobuf:"varint,1,opt,name=accountID" json:"accountID,omitempty"` Range *Range `protobuf:"bytes,2,opt,name=range" json:"range,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CountOrdersRequest) Reset() { *m = CountOrdersRequest{} } func (m *CountOrdersRequest) String() string { return proto1.CompactTextString(m) } func (*CountOrdersRequest) ProtoMessage() {} func (*CountOrdersRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} } func (m *CountOrdersRequest) GetAccountID() int64 { if m != nil && m.AccountID != nil { return *m.AccountID } return 0 } func (m *CountOrdersRequest) GetRange() *Range { if m != nil { return m.Range } return nil } type GetSCTReceiptRequest struct { Serial *string `protobuf:"bytes,1,opt,name=serial" json:"serial,omitempty"` LogID *string `protobuf:"bytes,2,opt,name=logID" json:"logID,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetSCTReceiptRequest) Reset() { *m = GetSCTReceiptRequest{} } func (m *GetSCTReceiptRequest) String() string { return proto1.CompactTextString(m) } func (*GetSCTReceiptRequest) ProtoMessage() {} func (*GetSCTReceiptRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } func (m *GetSCTReceiptRequest) GetSerial() string { if m != nil && m.Serial != nil { return *m.Serial } return "" } func (m *GetSCTReceiptRequest) GetLogID() string { if m != nil && m.LogID != nil { return *m.LogID } return "" } type CountFQDNSetsRequest struct { Window *int64 `protobuf:"varint,1,opt,name=window" json:"window,omitempty"` Domains []string `protobuf:"bytes,2,rep,name=domains" json:"domains,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CountFQDNSetsRequest) Reset() { *m = CountFQDNSetsRequest{} } func (m *CountFQDNSetsRequest) String() string { return proto1.CompactTextString(m) } func (*CountFQDNSetsRequest) ProtoMessage() {} func (*CountFQDNSetsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } func (m *CountFQDNSetsRequest) GetWindow() int64 { if m != nil && m.Window != nil { return *m.Window } return 0 } func (m *CountFQDNSetsRequest) GetDomains() []string { if m != nil { return m.Domains } return nil } type FQDNSetExistsRequest struct { Domains []string `protobuf:"bytes,1,rep,name=domains" json:"domains,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FQDNSetExistsRequest) Reset() { *m = FQDNSetExistsRequest{} } func (m *FQDNSetExistsRequest) String() string { return proto1.CompactTextString(m) } func (*FQDNSetExistsRequest) ProtoMessage() {} func (*FQDNSetExistsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } func (m *FQDNSetExistsRequest) GetDomains() []string { if m != nil { return m.Domains } return nil } type PreviousCertificateExistsRequest struct { Domain *string `protobuf:"bytes,1,opt,name=domain" json:"domain,omitempty"` RegID *int64 `protobuf:"varint,2,opt,name=regID" json:"regID,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *PreviousCertificateExistsRequest) Reset() { *m = PreviousCertificateExistsRequest{} } func (m *PreviousCertificateExistsRequest) String() string { return proto1.CompactTextString(m) } func (*PreviousCertificateExistsRequest) ProtoMessage() {} func (*PreviousCertificateExistsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} } func (m *PreviousCertificateExistsRequest) GetDomain() string { if m != nil && m.Domain != nil { return *m.Domain } return "" } func (m *PreviousCertificateExistsRequest) GetRegID() int64 { if m != nil && m.RegID != nil { return *m.RegID } return 0 } type Exists struct { Exists *bool `protobuf:"varint,1,opt,name=exists" json:"exists,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Exists) Reset() { *m = Exists{} } func (m *Exists) String() string { return proto1.CompactTextString(m) } func (*Exists) ProtoMessage() {} func (*Exists) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} } func (m *Exists) GetExists() bool { if m != nil && m.Exists != nil { return *m.Exists } return false } type MarkCertificateRevokedRequest struct { Serial *string `protobuf:"bytes,1,opt,name=serial" json:"serial,omitempty"` Code *int64 `protobuf:"varint,2,opt,name=code" json:"code,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MarkCertificateRevokedRequest) Reset() { *m = MarkCertificateRevokedRequest{} } func (m *MarkCertificateRevokedRequest) String() string { return proto1.CompactTextString(m) } func (*MarkCertificateRevokedRequest) ProtoMessage() {} func (*MarkCertificateRevokedRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} } func (m *MarkCertificateRevokedRequest) GetSerial() string { if m != nil && m.Serial != nil { return *m.Serial } return "" } func (m *MarkCertificateRevokedRequest) GetCode() int64 { if m != nil && m.Code != nil { return *m.Code } return 0 } type AddCertificateRequest struct { Der []byte `protobuf:"bytes,1,opt,name=der" json:"der,omitempty"` RegID *int64 `protobuf:"varint,2,opt,name=regID" json:"regID,omitempty"` // A signed OCSP response for the certificate contained in "der". // Note: The certificate status in the OCSP response is assumed to be 0 (good). Ocsp []byte `protobuf:"bytes,3,opt,name=ocsp" json:"ocsp,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *AddCertificateRequest) Reset() { *m = AddCertificateRequest{} } func (m *AddCertificateRequest) String() string { return proto1.CompactTextString(m) } func (*AddCertificateRequest) ProtoMessage() {} func (*AddCertificateRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} } func (m *AddCertificateRequest) GetDer() []byte { if m != nil { return m.Der } return nil } func (m *AddCertificateRequest) GetRegID() int64 { if m != nil && m.RegID != nil { return *m.RegID } return 0 } func (m *AddCertificateRequest) GetOcsp() []byte { if m != nil { return m.Ocsp } return nil } type AddCertificateResponse struct { Digest *string `protobuf:"bytes,1,opt,name=digest" json:"digest,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *AddCertificateResponse) Reset() { *m = AddCertificateResponse{} } func (m *AddCertificateResponse) String() string { return proto1.CompactTextString(m) } func (*AddCertificateResponse) ProtoMessage() {} func (*AddCertificateResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} } func (m *AddCertificateResponse) GetDigest() string { if m != nil && m.Digest != nil { return *m.Digest } return "" } type SignedCertificateTimestamp struct { Id *int64 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` SctVersion *int64 `protobuf:"varint,2,opt,name=sctVersion" json:"sctVersion,omitempty"` LogID *string `protobuf:"bytes,3,opt,name=logID" json:"logID,omitempty"` Timestamp *int64 `protobuf:"varint,4,opt,name=timestamp" json:"timestamp,omitempty"` Extensions []byte `protobuf:"bytes,5,opt,name=extensions" json:"extensions,omitempty"` Signature []byte `protobuf:"bytes,6,opt,name=signature" json:"signature,omitempty"` CertificateSerial *string `protobuf:"bytes,7,opt,name=certificateSerial" json:"certificateSerial,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SignedCertificateTimestamp) Reset() { *m = SignedCertificateTimestamp{} } func (m *SignedCertificateTimestamp) String() string { return proto1.CompactTextString(m) } func (*SignedCertificateTimestamp) ProtoMessage() {} func (*SignedCertificateTimestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} } func (m *SignedCertificateTimestamp) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } func (m *SignedCertificateTimestamp) GetSctVersion() int64 { if m != nil && m.SctVersion != nil { return *m.SctVersion } return 0 } func (m *SignedCertificateTimestamp) GetLogID() string { if m != nil && m.LogID != nil { return *m.LogID } return "" } func (m *SignedCertificateTimestamp) GetTimestamp() int64 { if m != nil && m.Timestamp != nil { return *m.Timestamp } return 0 } func (m *SignedCertificateTimestamp) GetExtensions() []byte { if m != nil { return m.Extensions } return nil } func (m *SignedCertificateTimestamp) GetSignature() []byte { if m != nil { return m.Signature } return nil } func (m *SignedCertificateTimestamp) GetCertificateSerial() string { if m != nil && m.CertificateSerial != nil { return *m.CertificateSerial } return "" } type RevokeAuthorizationsByDomainRequest struct { Domain *string `protobuf:"bytes,1,opt,name=domain" json:"domain,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RevokeAuthorizationsByDomainRequest) Reset() { *m = RevokeAuthorizationsByDomainRequest{} } func (m *RevokeAuthorizationsByDomainRequest) String() string { return proto1.CompactTextString(m) } func (*RevokeAuthorizationsByDomainRequest) ProtoMessage() {} func (*RevokeAuthorizationsByDomainRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} } func (m *RevokeAuthorizationsByDomainRequest) GetDomain() string { if m != nil && m.Domain != nil { return *m.Domain } return "" } type RevokeAuthorizationsByDomainResponse struct { Finalized *int64 `protobuf:"varint,1,opt,name=finalized" json:"finalized,omitempty"` Pending *int64 `protobuf:"varint,2,opt,name=pending" json:"pending,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RevokeAuthorizationsByDomainResponse) Reset() { *m = RevokeAuthorizationsByDomainResponse{} } func (m *RevokeAuthorizationsByDomainResponse) String() string { return proto1.CompactTextString(m) } func (*RevokeAuthorizationsByDomainResponse) ProtoMessage() {} func (*RevokeAuthorizationsByDomainResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} } func (m *RevokeAuthorizationsByDomainResponse) GetFinalized() int64 { if m != nil && m.Finalized != nil { return *m.Finalized } return 0 } func (m *RevokeAuthorizationsByDomainResponse) GetPending() int64 { if m != nil && m.Pending != nil { return *m.Pending } return 0 } type OrderRequest struct { Id *int64 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OrderRequest) Reset() { *m = OrderRequest{} } func (m *OrderRequest) String() string { return proto1.CompactTextString(m) } func (*OrderRequest) ProtoMessage() {} func (*OrderRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} } func (m *OrderRequest) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } type GetValidOrderAuthorizationsRequest struct { Id *int64 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` AcctID *int64 `protobuf:"varint,2,opt,name=acctID" json:"acctID,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetValidOrderAuthorizationsRequest) Reset() { *m = GetValidOrderAuthorizationsRequest{} } func (m *GetValidOrderAuthorizationsRequest) String() string { return proto1.CompactTextString(m) } func (*GetValidOrderAuthorizationsRequest) ProtoMessage() {} func (*GetValidOrderAuthorizationsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} } func (m *GetValidOrderAuthorizationsRequest) GetId() int64 { if m != nil && m.Id != nil { return *m.Id } return 0 } func (m *GetValidOrderAuthorizationsRequest) GetAcctID() int64 { if m != nil && m.AcctID != nil { return *m.AcctID } return 0 } type GetOrderForNamesRequest struct { AcctID *int64 `protobuf:"varint,1,opt,name=acctID" json:"acctID,omitempty"` Names []string `protobuf:"bytes,2,rep,name=names" json:"names,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetOrderForNamesRequest) Reset() { *m = GetOrderForNamesRequest{} } func (m *GetOrderForNamesRequest) String() string { return proto1.CompactTextString(m) } func (*GetOrderForNamesRequest) ProtoMessage() {} func (*GetOrderForNamesRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} } func (m *GetOrderForNamesRequest) GetAcctID() int64 { if m != nil && m.AcctID != nil { return *m.AcctID } return 0 } func (m *GetOrderForNamesRequest) GetNames() []string { if m != nil { return m.Names } return nil } type GetAuthorizationsRequest struct { RegistrationID *int64 `protobuf:"varint,1,opt,name=registrationID" json:"registrationID,omitempty"` Domains []string `protobuf:"bytes,2,rep,name=domains" json:"domains,omitempty"` Now *int64 `protobuf:"varint,3,opt,name=now" json:"now,omitempty"` RequireV2Authzs *bool `protobuf:"varint,4,opt,name=requireV2Authzs" json:"requireV2Authzs,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetAuthorizationsRequest) Reset() { *m = GetAuthorizationsRequest{} } func (m *GetAuthorizationsRequest) String() string { return proto1.CompactTextString(m) } func (*GetAuthorizationsRequest) ProtoMessage() {} func (*GetAuthorizationsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} } func (m *GetAuthorizationsRequest) GetRegistrationID() int64 { if m != nil && m.RegistrationID != nil { return *m.RegistrationID } return 0 } func (m *GetAuthorizationsRequest) GetDomains() []string { if m != nil { return m.Domains } return nil } func (m *GetAuthorizationsRequest) GetNow() int64 { if m != nil && m.Now != nil { return *m.Now } return 0 } func (m *GetAuthorizationsRequest) GetRequireV2Authzs() bool { if m != nil && m.RequireV2Authzs != nil { return *m.RequireV2Authzs } return false } type Authorizations struct { Authz []*Authorizations_MapElement `protobuf:"bytes,1,rep,name=authz" json:"authz,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Authorizations) Reset() { *m = Authorizations{} } func (m *Authorizations) String() string { return proto1.CompactTextString(m) } func (*Authorizations) ProtoMessage() {} func (*Authorizations) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30} } func (m *Authorizations) GetAuthz() []*Authorizations_MapElement { if m != nil { return m.Authz } return nil } type Authorizations_MapElement struct { Domain *string `protobuf:"bytes,1,opt,name=domain" json:"domain,omitempty"` Authz *core.Authorization `protobuf:"bytes,2,opt,name=authz" json:"authz,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Authorizations_MapElement) Reset() { *m = Authorizations_MapElement{} } func (m *Authorizations_MapElement) String() string { return proto1.CompactTextString(m) } func (*Authorizations_MapElement) ProtoMessage() {} func (*Authorizations_MapElement) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30, 0} } func (m *Authorizations_MapElement) GetDomain() string { if m != nil && m.Domain != nil { return *m.Domain } return "" } func (m *Authorizations_MapElement) GetAuthz() *core.Authorization { if m != nil { return m.Authz } return nil } type AddPendingAuthorizationsRequest struct { Authz []*core.Authorization `protobuf:"bytes,1,rep,name=authz" json:"authz,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *AddPendingAuthorizationsRequest) Reset() { *m = AddPendingAuthorizationsRequest{} } func (m *AddPendingAuthorizationsRequest) String() string { return proto1.CompactTextString(m) } func (*AddPendingAuthorizationsRequest) ProtoMessage() {} func (*AddPendingAuthorizationsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{31} } func (m *AddPendingAuthorizationsRequest) GetAuthz() []*core.Authorization { if m != nil { return m.Authz } return nil } type AuthorizationIDs struct { Ids []string `protobuf:"bytes,1,rep,name=ids" json:"ids,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *AuthorizationIDs) Reset() { *m = AuthorizationIDs{} } func (m *AuthorizationIDs) String() string { return proto1.CompactTextString(m) } func (*AuthorizationIDs) ProtoMessage() {} func (*AuthorizationIDs) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{32} } func (m *AuthorizationIDs) GetIds() []string { if m != nil { return m.Ids } return nil } func init() { proto1.RegisterType((*RegistrationID)(nil), "sa.RegistrationID") proto1.RegisterType((*JSONWebKey)(nil), "sa.JSONWebKey") proto1.RegisterType((*AuthorizationID)(nil), "sa.AuthorizationID") proto1.RegisterType((*GetPendingAuthorizationRequest)(nil), "sa.GetPendingAuthorizationRequest") proto1.RegisterType((*GetValidAuthorizationsRequest)(nil), "sa.GetValidAuthorizationsRequest") proto1.RegisterType((*ValidAuthorizations)(nil), "sa.ValidAuthorizations") proto1.RegisterType((*ValidAuthorizations_MapElement)(nil), "sa.ValidAuthorizations.MapElement") proto1.RegisterType((*CertificateStatus)(nil), "sa.CertificateStatus") proto1.RegisterType((*Serial)(nil), "sa.Serial") proto1.RegisterType((*Range)(nil), "sa.Range") proto1.RegisterType((*Count)(nil), "sa.Count") proto1.RegisterType((*CountCertificatesByNamesRequest)(nil), "sa.CountCertificatesByNamesRequest") proto1.RegisterType((*CountByNames)(nil), "sa.CountByNames") proto1.RegisterType((*CountByNames_MapElement)(nil), "sa.CountByNames.MapElement") proto1.RegisterType((*CountRegistrationsByIPRequest)(nil), "sa.CountRegistrationsByIPRequest") proto1.RegisterType((*CountInvalidAuthorizationsRequest)(nil), "sa.CountInvalidAuthorizationsRequest") proto1.RegisterType((*CountOrdersRequest)(nil), "sa.CountOrdersRequest") proto1.RegisterType((*GetSCTReceiptRequest)(nil), "sa.GetSCTReceiptRequest") proto1.RegisterType((*CountFQDNSetsRequest)(nil), "sa.CountFQDNSetsRequest") proto1.RegisterType((*FQDNSetExistsRequest)(nil), "sa.FQDNSetExistsRequest") proto1.RegisterType((*PreviousCertificateExistsRequest)(nil), "sa.PreviousCertificateExistsRequest") proto1.RegisterType((*Exists)(nil), "sa.Exists") proto1.RegisterType((*MarkCertificateRevokedRequest)(nil), "sa.MarkCertificateRevokedRequest") proto1.RegisterType((*AddCertificateRequest)(nil), "sa.AddCertificateRequest") proto1.RegisterType((*AddCertificateResponse)(nil), "sa.AddCertificateResponse") proto1.RegisterType((*SignedCertificateTimestamp)(nil), "sa.SignedCertificateTimestamp") proto1.RegisterType((*RevokeAuthorizationsByDomainRequest)(nil), "sa.RevokeAuthorizationsByDomainRequest") proto1.RegisterType((*RevokeAuthorizationsByDomainResponse)(nil), "sa.RevokeAuthorizationsByDomainResponse") proto1.RegisterType((*OrderRequest)(nil), "sa.OrderRequest") proto1.RegisterType((*GetValidOrderAuthorizationsRequest)(nil), "sa.GetValidOrderAuthorizationsRequest") proto1.RegisterType((*GetOrderForNamesRequest)(nil), "sa.GetOrderForNamesRequest") proto1.RegisterType((*GetAuthorizationsRequest)(nil), "sa.GetAuthorizationsRequest") proto1.RegisterType((*Authorizations)(nil), "sa.Authorizations") proto1.RegisterType((*Authorizations_MapElement)(nil), "sa.Authorizations.MapElement") proto1.RegisterType((*AddPendingAuthorizationsRequest)(nil), "sa.AddPendingAuthorizationsRequest") proto1.RegisterType((*AuthorizationIDs)(nil), "sa.AuthorizationIDs") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for StorageAuthority service type StorageAuthorityClient interface { // Getters GetRegistration(ctx context.Context, in *RegistrationID, opts ...grpc.CallOption) (*core.Registration, error) GetRegistrationByKey(ctx context.Context, in *JSONWebKey, opts ...grpc.CallOption) (*core.Registration, error) GetAuthorization(ctx context.Context, in *AuthorizationID, opts ...grpc.CallOption) (*core.Authorization, error) GetPendingAuthorization(ctx context.Context, in *GetPendingAuthorizationRequest, opts ...grpc.CallOption) (*core.Authorization, error) GetValidAuthorizations(ctx context.Context, in *GetValidAuthorizationsRequest, opts ...grpc.CallOption) (*ValidAuthorizations, error) GetCertificate(ctx context.Context, in *Serial, opts ...grpc.CallOption) (*core.Certificate, error) GetCertificateStatus(ctx context.Context, in *Serial, opts ...grpc.CallOption) (*CertificateStatus, error) CountCertificatesRange(ctx context.Context, in *Range, opts ...grpc.CallOption) (*Count, error) CountCertificatesByNames(ctx context.Context, in *CountCertificatesByNamesRequest, opts ...grpc.CallOption) (*CountByNames, error) CountCertificatesByExactNames(ctx context.Context, in *CountCertificatesByNamesRequest, opts ...grpc.CallOption) (*CountByNames, error) CountRegistrationsByIP(ctx context.Context, in *CountRegistrationsByIPRequest, opts ...grpc.CallOption) (*Count, error) CountRegistrationsByIPRange(ctx context.Context, in *CountRegistrationsByIPRequest, opts ...grpc.CallOption) (*Count, error) CountPendingAuthorizations(ctx context.Context, in *RegistrationID, opts ...grpc.CallOption) (*Count, error) CountOrders(ctx context.Context, in *CountOrdersRequest, opts ...grpc.CallOption) (*Count, error) // Return a count of authorizations with status "invalid" that belong to // a given registration ID and expire in the given time range. CountInvalidAuthorizations(ctx context.Context, in *CountInvalidAuthorizationsRequest, opts ...grpc.CallOption) (*Count, error) GetSCTReceipt(ctx context.Context, in *GetSCTReceiptRequest, opts ...grpc.CallOption) (*SignedCertificateTimestamp, error) CountFQDNSets(ctx context.Context, in *CountFQDNSetsRequest, opts ...grpc.CallOption) (*Count, error) FQDNSetExists(ctx context.Context, in *FQDNSetExistsRequest, opts ...grpc.CallOption) (*Exists, error) PreviousCertificateExists(ctx context.Context, in *PreviousCertificateExistsRequest, opts ...grpc.CallOption) (*Exists, error) // Adders NewRegistration(ctx context.Context, in *core.Registration, opts ...grpc.CallOption) (*core.Registration, error) UpdateRegistration(ctx context.Context, in *core.Registration, opts ...grpc.CallOption) (*core.Empty, error) NewPendingAuthorization(ctx context.Context, in *core.Authorization, opts ...grpc.CallOption) (*core.Authorization, error) UpdatePendingAuthorization(ctx context.Context, in *core.Authorization, opts ...grpc.CallOption) (*core.Empty, error) FinalizeAuthorization(ctx context.Context, in *core.Authorization, opts ...grpc.CallOption) (*core.Empty, error) MarkCertificateRevoked(ctx context.Context, in *MarkCertificateRevokedRequest, opts ...grpc.CallOption) (*core.Empty, error) AddCertificate(ctx context.Context, in *AddCertificateRequest, opts ...grpc.CallOption) (*AddCertificateResponse, error) AddSCTReceipt(ctx context.Context, in *SignedCertificateTimestamp, opts ...grpc.CallOption) (*core.Empty, error) RevokeAuthorizationsByDomain(ctx context.Context, in *RevokeAuthorizationsByDomainRequest, opts ...grpc.CallOption) (*RevokeAuthorizationsByDomainResponse, error) DeactivateRegistration(ctx context.Context, in *RegistrationID, opts ...grpc.CallOption) (*core.Empty, error) DeactivateAuthorization(ctx context.Context, in *AuthorizationID, opts ...grpc.CallOption) (*core.Empty, error) NewOrder(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Order, error) SetOrderProcessing(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Empty, error) SetOrderError(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Empty, error) FinalizeOrder(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Empty, error) GetOrder(ctx context.Context, in *OrderRequest, opts ...grpc.CallOption) (*core.Order, error) GetValidOrderAuthorizations(ctx context.Context, in *GetValidOrderAuthorizationsRequest, opts ...grpc.CallOption) (*Authorizations, error) GetOrderForNames(ctx context.Context, in *GetOrderForNamesRequest, opts ...grpc.CallOption) (*core.Order, error) GetAuthorizations(ctx context.Context, in *GetAuthorizationsRequest, opts ...grpc.CallOption) (*Authorizations, error) AddPendingAuthorizations(ctx context.Context, in *AddPendingAuthorizationsRequest, opts ...grpc.CallOption) (*AuthorizationIDs, error) } type storageAuthorityClient struct { cc *grpc.ClientConn } func NewStorageAuthorityClient(cc *grpc.ClientConn) StorageAuthorityClient { return &storageAuthorityClient{cc} } func (c *storageAuthorityClient) GetRegistration(ctx context.Context, in *RegistrationID, opts ...grpc.CallOption) (*core.Registration, error) { out := new(core.Registration) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetRegistration", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetRegistrationByKey(ctx context.Context, in *JSONWebKey, opts ...grpc.CallOption) (*core.Registration, error) { out := new(core.Registration) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetRegistrationByKey", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetAuthorization(ctx context.Context, in *AuthorizationID, opts ...grpc.CallOption) (*core.Authorization, error) { out := new(core.Authorization) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetAuthorization", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetPendingAuthorization(ctx context.Context, in *GetPendingAuthorizationRequest, opts ...grpc.CallOption) (*core.Authorization, error) { out := new(core.Authorization) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetPendingAuthorization", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetValidAuthorizations(ctx context.Context, in *GetValidAuthorizationsRequest, opts ...grpc.CallOption) (*ValidAuthorizations, error) { out := new(ValidAuthorizations) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetValidAuthorizations", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetCertificate(ctx context.Context, in *Serial, opts ...grpc.CallOption) (*core.Certificate, error) { out := new(core.Certificate) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetCertificate", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetCertificateStatus(ctx context.Context, in *Serial, opts ...grpc.CallOption) (*CertificateStatus, error) { out := new(CertificateStatus) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetCertificateStatus", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountCertificatesRange(ctx context.Context, in *Range, opts ...grpc.CallOption) (*Count, error) { out := new(Count) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountCertificatesRange", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountCertificatesByNames(ctx context.Context, in *CountCertificatesByNamesRequest, opts ...grpc.CallOption) (*CountByNames, error) { out := new(CountByNames) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountCertificatesByNames", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountCertificatesByExactNames(ctx context.Context, in *CountCertificatesByNamesRequest, opts ...grpc.CallOption) (*CountByNames, error) { out := new(CountByNames) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountCertificatesByExactNames", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountRegistrationsByIP(ctx context.Context, in *CountRegistrationsByIPRequest, opts ...grpc.CallOption) (*Count, error) { out := new(Count) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountRegistrationsByIP", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountRegistrationsByIPRange(ctx context.Context, in *CountRegistrationsByIPRequest, opts ...grpc.CallOption) (*Count, error) { out := new(Count) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountRegistrationsByIPRange", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountPendingAuthorizations(ctx context.Context, in *RegistrationID, opts ...grpc.CallOption) (*Count, error) { out := new(Count) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountPendingAuthorizations", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountOrders(ctx context.Context, in *CountOrdersRequest, opts ...grpc.CallOption) (*Count, error) { out := new(Count) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountOrders", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountInvalidAuthorizations(ctx context.Context, in *CountInvalidAuthorizationsRequest, opts ...grpc.CallOption) (*Count, error) { out := new(Count) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountInvalidAuthorizations", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetSCTReceipt(ctx context.Context, in *GetSCTReceiptRequest, opts ...grpc.CallOption) (*SignedCertificateTimestamp, error) { out := new(SignedCertificateTimestamp) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetSCTReceipt", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) CountFQDNSets(ctx context.Context, in *CountFQDNSetsRequest, opts ...grpc.CallOption) (*Count, error) { out := new(Count) err := grpc.Invoke(ctx, "/sa.StorageAuthority/CountFQDNSets", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) FQDNSetExists(ctx context.Context, in *FQDNSetExistsRequest, opts ...grpc.CallOption) (*Exists, error) { out := new(Exists) err := grpc.Invoke(ctx, "/sa.StorageAuthority/FQDNSetExists", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) PreviousCertificateExists(ctx context.Context, in *PreviousCertificateExistsRequest, opts ...grpc.CallOption) (*Exists, error) { out := new(Exists) err := grpc.Invoke(ctx, "/sa.StorageAuthority/PreviousCertificateExists", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) NewRegistration(ctx context.Context, in *core.Registration, opts ...grpc.CallOption) (*core.Registration, error) { out := new(core.Registration) err := grpc.Invoke(ctx, "/sa.StorageAuthority/NewRegistration", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) UpdateRegistration(ctx context.Context, in *core.Registration, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/UpdateRegistration", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) NewPendingAuthorization(ctx context.Context, in *core.Authorization, opts ...grpc.CallOption) (*core.Authorization, error) { out := new(core.Authorization) err := grpc.Invoke(ctx, "/sa.StorageAuthority/NewPendingAuthorization", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) UpdatePendingAuthorization(ctx context.Context, in *core.Authorization, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/UpdatePendingAuthorization", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) FinalizeAuthorization(ctx context.Context, in *core.Authorization, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/FinalizeAuthorization", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) MarkCertificateRevoked(ctx context.Context, in *MarkCertificateRevokedRequest, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/MarkCertificateRevoked", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) AddCertificate(ctx context.Context, in *AddCertificateRequest, opts ...grpc.CallOption) (*AddCertificateResponse, error) { out := new(AddCertificateResponse) err := grpc.Invoke(ctx, "/sa.StorageAuthority/AddCertificate", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) AddSCTReceipt(ctx context.Context, in *SignedCertificateTimestamp, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/AddSCTReceipt", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) RevokeAuthorizationsByDomain(ctx context.Context, in *RevokeAuthorizationsByDomainRequest, opts ...grpc.CallOption) (*RevokeAuthorizationsByDomainResponse, error) { out := new(RevokeAuthorizationsByDomainResponse) err := grpc.Invoke(ctx, "/sa.StorageAuthority/RevokeAuthorizationsByDomain", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) DeactivateRegistration(ctx context.Context, in *RegistrationID, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/DeactivateRegistration", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) DeactivateAuthorization(ctx context.Context, in *AuthorizationID, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/DeactivateAuthorization", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) NewOrder(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Order, error) { out := new(core.Order) err := grpc.Invoke(ctx, "/sa.StorageAuthority/NewOrder", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) SetOrderProcessing(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/SetOrderProcessing", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) SetOrderError(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/SetOrderError", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) FinalizeOrder(ctx context.Context, in *core.Order, opts ...grpc.CallOption) (*core.Empty, error) { out := new(core.Empty) err := grpc.Invoke(ctx, "/sa.StorageAuthority/FinalizeOrder", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetOrder(ctx context.Context, in *OrderRequest, opts ...grpc.CallOption) (*core.Order, error) { out := new(core.Order) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetOrder", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetValidOrderAuthorizations(ctx context.Context, in *GetValidOrderAuthorizationsRequest, opts ...grpc.CallOption) (*Authorizations, error) { out := new(Authorizations) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetValidOrderAuthorizations", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetOrderForNames(ctx context.Context, in *GetOrderForNamesRequest, opts ...grpc.CallOption) (*core.Order, error) { out := new(core.Order) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetOrderForNames", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) GetAuthorizations(ctx context.Context, in *GetAuthorizationsRequest, opts ...grpc.CallOption) (*Authorizations, error) { out := new(Authorizations) err := grpc.Invoke(ctx, "/sa.StorageAuthority/GetAuthorizations", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *storageAuthorityClient) AddPendingAuthorizations(ctx context.Context, in *AddPendingAuthorizationsRequest, opts ...grpc.CallOption) (*AuthorizationIDs, error) { out := new(AuthorizationIDs) err := grpc.Invoke(ctx, "/sa.StorageAuthority/AddPendingAuthorizations", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for StorageAuthority service type StorageAuthorityServer interface { // Getters GetRegistration(context.Context, *RegistrationID) (*core.Registration, error) GetRegistrationByKey(context.Context, *JSONWebKey) (*core.Registration, error) GetAuthorization(context.Context, *AuthorizationID) (*core.Authorization, error) GetPendingAuthorization(context.Context, *GetPendingAuthorizationRequest) (*core.Authorization, error) GetValidAuthorizations(context.Context, *GetValidAuthorizationsRequest) (*ValidAuthorizations, error) GetCertificate(context.Context, *Serial) (*core.Certificate, error) GetCertificateStatus(context.Context, *Serial) (*CertificateStatus, error) CountCertificatesRange(context.Context, *Range) (*Count, error) CountCertificatesByNames(context.Context, *CountCertificatesByNamesRequest) (*CountByNames, error) CountCertificatesByExactNames(context.Context, *CountCertificatesByNamesRequest) (*CountByNames, error) CountRegistrationsByIP(context.Context, *CountRegistrationsByIPRequest) (*Count, error) CountRegistrationsByIPRange(context.Context, *CountRegistrationsByIPRequest) (*Count, error) CountPendingAuthorizations(context.Context, *RegistrationID) (*Count, error) CountOrders(context.Context, *CountOrdersRequest) (*Count, error) // Return a count of authorizations with status "invalid" that belong to // a given registration ID and expire in the given time range. CountInvalidAuthorizations(context.Context, *CountInvalidAuthorizationsRequest) (*Count, error) GetSCTReceipt(context.Context, *GetSCTReceiptRequest) (*SignedCertificateTimestamp, error) CountFQDNSets(context.Context, *CountFQDNSetsRequest) (*Count, error) FQDNSetExists(context.Context, *FQDNSetExistsRequest) (*Exists, error) PreviousCertificateExists(context.Context, *PreviousCertificateExistsRequest) (*Exists, error) // Adders NewRegistration(context.Context, *core.Registration) (*core.Registration, error) UpdateRegistration(context.Context, *core.Registration) (*core.Empty, error) NewPendingAuthorization(context.Context, *core.Authorization) (*core.Authorization, error) UpdatePendingAuthorization(context.Context, *core.Authorization) (*core.Empty, error) FinalizeAuthorization(context.Context, *core.Authorization) (*core.Empty, error) MarkCertificateRevoked(context.Context, *MarkCertificateRevokedRequest) (*core.Empty, error) AddCertificate(context.Context, *AddCertificateRequest) (*AddCertificateResponse, error) AddSCTReceipt(context.Context, *SignedCertificateTimestamp) (*core.Empty, error) RevokeAuthorizationsByDomain(context.Context, *RevokeAuthorizationsByDomainRequest) (*RevokeAuthorizationsByDomainResponse, error) DeactivateRegistration(context.Context, *RegistrationID) (*core.Empty, error) DeactivateAuthorization(context.Context, *AuthorizationID) (*core.Empty, error) NewOrder(context.Context, *core.Order) (*core.Order, error) SetOrderProcessing(context.Context, *core.Order) (*core.Empty, error) SetOrderError(context.Context, *core.Order) (*core.Empty, error) FinalizeOrder(context.Context, *core.Order) (*core.Empty, error) GetOrder(context.Context, *OrderRequest) (*core.Order, error) GetValidOrderAuthorizations(context.Context, *GetValidOrderAuthorizationsRequest) (*Authorizations, error) GetOrderForNames(context.Context, *GetOrderForNamesRequest) (*core.Order, error) GetAuthorizations(context.Context, *GetAuthorizationsRequest) (*Authorizations, error) AddPendingAuthorizations(context.Context, *AddPendingAuthorizationsRequest) (*AuthorizationIDs, error) } func RegisterStorageAuthorityServer(s *grpc.Server, srv StorageAuthorityServer) { s.RegisterService(&_StorageAuthority_serviceDesc, srv) } func _StorageAuthority_GetRegistration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RegistrationID) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetRegistration(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetRegistration", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetRegistration(ctx, req.(*RegistrationID)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetRegistrationByKey_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(JSONWebKey) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetRegistrationByKey(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetRegistrationByKey", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetRegistrationByKey(ctx, req.(*JSONWebKey)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AuthorizationID) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetAuthorization(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetAuthorization", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetAuthorization(ctx, req.(*AuthorizationID)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetPendingAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetPendingAuthorizationRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetPendingAuthorization(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetPendingAuthorization", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetPendingAuthorization(ctx, req.(*GetPendingAuthorizationRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetValidAuthorizations_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetValidAuthorizationsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetValidAuthorizations(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetValidAuthorizations", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetValidAuthorizations(ctx, req.(*GetValidAuthorizationsRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Serial) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetCertificate(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetCertificate", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetCertificate(ctx, req.(*Serial)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetCertificateStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Serial) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetCertificateStatus(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetCertificateStatus", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetCertificateStatus(ctx, req.(*Serial)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountCertificatesRange_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(Range) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountCertificatesRange(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountCertificatesRange", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountCertificatesRange(ctx, req.(*Range)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountCertificatesByNames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CountCertificatesByNamesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountCertificatesByNames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountCertificatesByNames", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountCertificatesByNames(ctx, req.(*CountCertificatesByNamesRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountCertificatesByExactNames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CountCertificatesByNamesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountCertificatesByExactNames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountCertificatesByExactNames", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountCertificatesByExactNames(ctx, req.(*CountCertificatesByNamesRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountRegistrationsByIP_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CountRegistrationsByIPRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountRegistrationsByIP(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountRegistrationsByIP", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountRegistrationsByIP(ctx, req.(*CountRegistrationsByIPRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountRegistrationsByIPRange_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CountRegistrationsByIPRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountRegistrationsByIPRange(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountRegistrationsByIPRange", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountRegistrationsByIPRange(ctx, req.(*CountRegistrationsByIPRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountPendingAuthorizations_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RegistrationID) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountPendingAuthorizations(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountPendingAuthorizations", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountPendingAuthorizations(ctx, req.(*RegistrationID)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountOrders_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CountOrdersRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountOrders(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountOrders", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountOrders(ctx, req.(*CountOrdersRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountInvalidAuthorizations_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CountInvalidAuthorizationsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountInvalidAuthorizations(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountInvalidAuthorizations", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountInvalidAuthorizations(ctx, req.(*CountInvalidAuthorizationsRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetSCTReceipt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetSCTReceiptRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetSCTReceipt(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetSCTReceipt", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetSCTReceipt(ctx, req.(*GetSCTReceiptRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_CountFQDNSets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CountFQDNSetsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).CountFQDNSets(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/CountFQDNSets", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).CountFQDNSets(ctx, req.(*CountFQDNSetsRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_FQDNSetExists_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(FQDNSetExistsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).FQDNSetExists(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/FQDNSetExists", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).FQDNSetExists(ctx, req.(*FQDNSetExistsRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_PreviousCertificateExists_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PreviousCertificateExistsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).PreviousCertificateExists(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/PreviousCertificateExists", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).PreviousCertificateExists(ctx, req.(*PreviousCertificateExistsRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_NewRegistration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Registration) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).NewRegistration(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/NewRegistration", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).NewRegistration(ctx, req.(*core.Registration)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_UpdateRegistration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Registration) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).UpdateRegistration(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/UpdateRegistration", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).UpdateRegistration(ctx, req.(*core.Registration)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_NewPendingAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Authorization) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).NewPendingAuthorization(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/NewPendingAuthorization", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).NewPendingAuthorization(ctx, req.(*core.Authorization)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_UpdatePendingAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Authorization) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).UpdatePendingAuthorization(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/UpdatePendingAuthorization", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).UpdatePendingAuthorization(ctx, req.(*core.Authorization)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_FinalizeAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Authorization) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).FinalizeAuthorization(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/FinalizeAuthorization", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).FinalizeAuthorization(ctx, req.(*core.Authorization)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_MarkCertificateRevoked_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MarkCertificateRevokedRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).MarkCertificateRevoked(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/MarkCertificateRevoked", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).MarkCertificateRevoked(ctx, req.(*MarkCertificateRevokedRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_AddCertificate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddCertificateRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).AddCertificate(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/AddCertificate", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).AddCertificate(ctx, req.(*AddCertificateRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_AddSCTReceipt_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(SignedCertificateTimestamp) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).AddSCTReceipt(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/AddSCTReceipt", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).AddSCTReceipt(ctx, req.(*SignedCertificateTimestamp)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_RevokeAuthorizationsByDomain_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RevokeAuthorizationsByDomainRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).RevokeAuthorizationsByDomain(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/RevokeAuthorizationsByDomain", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).RevokeAuthorizationsByDomain(ctx, req.(*RevokeAuthorizationsByDomainRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_DeactivateRegistration_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RegistrationID) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).DeactivateRegistration(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/DeactivateRegistration", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).DeactivateRegistration(ctx, req.(*RegistrationID)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_DeactivateAuthorization_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AuthorizationID) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).DeactivateAuthorization(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/DeactivateAuthorization", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).DeactivateAuthorization(ctx, req.(*AuthorizationID)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_NewOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Order) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).NewOrder(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/NewOrder", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).NewOrder(ctx, req.(*core.Order)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_SetOrderProcessing_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Order) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).SetOrderProcessing(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/SetOrderProcessing", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).SetOrderProcessing(ctx, req.(*core.Order)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_SetOrderError_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Order) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).SetOrderError(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/SetOrderError", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).SetOrderError(ctx, req.(*core.Order)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_FinalizeOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(core.Order) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).FinalizeOrder(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/FinalizeOrder", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).FinalizeOrder(ctx, req.(*core.Order)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetOrder_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(OrderRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetOrder(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetOrder", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetOrder(ctx, req.(*OrderRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetValidOrderAuthorizations_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetValidOrderAuthorizationsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetValidOrderAuthorizations(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetValidOrderAuthorizations", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetValidOrderAuthorizations(ctx, req.(*GetValidOrderAuthorizationsRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetOrderForNames_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetOrderForNamesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetOrderForNames(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetOrderForNames", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetOrderForNames(ctx, req.(*GetOrderForNamesRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_GetAuthorizations_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetAuthorizationsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).GetAuthorizations(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/GetAuthorizations", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).GetAuthorizations(ctx, req.(*GetAuthorizationsRequest)) } return interceptor(ctx, in, info, handler) } func _StorageAuthority_AddPendingAuthorizations_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AddPendingAuthorizationsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(StorageAuthorityServer).AddPendingAuthorizations(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/sa.StorageAuthority/AddPendingAuthorizations", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(StorageAuthorityServer).AddPendingAuthorizations(ctx, req.(*AddPendingAuthorizationsRequest)) } return interceptor(ctx, in, info, handler) } var _StorageAuthority_serviceDesc = grpc.ServiceDesc{ ServiceName: "sa.StorageAuthority", HandlerType: (*StorageAuthorityServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "GetRegistration", Handler: _StorageAuthority_GetRegistration_Handler, }, { MethodName: "GetRegistrationByKey", Handler: _StorageAuthority_GetRegistrationByKey_Handler, }, { MethodName: "GetAuthorization", Handler: _StorageAuthority_GetAuthorization_Handler, }, { MethodName: "GetPendingAuthorization", Handler: _StorageAuthority_GetPendingAuthorization_Handler, }, { MethodName: "GetValidAuthorizations", Handler: _StorageAuthority_GetValidAuthorizations_Handler, }, { MethodName: "GetCertificate", Handler: _StorageAuthority_GetCertificate_Handler, }, { MethodName: "GetCertificateStatus", Handler: _StorageAuthority_GetCertificateStatus_Handler, }, { MethodName: "CountCertificatesRange", Handler: _StorageAuthority_CountCertificatesRange_Handler, }, { MethodName: "CountCertificatesByNames", Handler: _StorageAuthority_CountCertificatesByNames_Handler, }, { MethodName: "CountCertificatesByExactNames", Handler: _StorageAuthority_CountCertificatesByExactNames_Handler, }, { MethodName: "CountRegistrationsByIP", Handler: _StorageAuthority_CountRegistrationsByIP_Handler, }, { MethodName: "CountRegistrationsByIPRange", Handler: _StorageAuthority_CountRegistrationsByIPRange_Handler, }, { MethodName: "CountPendingAuthorizations", Handler: _StorageAuthority_CountPendingAuthorizations_Handler, }, { MethodName: "CountOrders", Handler: _StorageAuthority_CountOrders_Handler, }, { MethodName: "CountInvalidAuthorizations", Handler: _StorageAuthority_CountInvalidAuthorizations_Handler, }, { MethodName: "GetSCTReceipt", Handler: _StorageAuthority_GetSCTReceipt_Handler, }, { MethodName: "CountFQDNSets", Handler: _StorageAuthority_CountFQDNSets_Handler, }, { MethodName: "FQDNSetExists", Handler: _StorageAuthority_FQDNSetExists_Handler, }, { MethodName: "PreviousCertificateExists", Handler: _StorageAuthority_PreviousCertificateExists_Handler, }, { MethodName: "NewRegistration", Handler: _StorageAuthority_NewRegistration_Handler, }, { MethodName: "UpdateRegistration", Handler: _StorageAuthority_UpdateRegistration_Handler, }, { MethodName: "NewPendingAuthorization", Handler: _StorageAuthority_NewPendingAuthorization_Handler, }, { MethodName: "UpdatePendingAuthorization", Handler: _StorageAuthority_UpdatePendingAuthorization_Handler, }, { MethodName: "FinalizeAuthorization", Handler: _StorageAuthority_FinalizeAuthorization_Handler, }, { MethodName: "MarkCertificateRevoked", Handler: _StorageAuthority_MarkCertificateRevoked_Handler, }, { MethodName: "AddCertificate", Handler: _StorageAuthority_AddCertificate_Handler, }, { MethodName: "AddSCTReceipt", Handler: _StorageAuthority_AddSCTReceipt_Handler, }, { MethodName: "RevokeAuthorizationsByDomain", Handler: _StorageAuthority_RevokeAuthorizationsByDomain_Handler, }, { MethodName: "DeactivateRegistration", Handler: _StorageAuthority_DeactivateRegistration_Handler, }, { MethodName: "DeactivateAuthorization", Handler: _StorageAuthority_DeactivateAuthorization_Handler, }, { MethodName: "NewOrder", Handler: _StorageAuthority_NewOrder_Handler, }, { MethodName: "SetOrderProcessing", Handler: _StorageAuthority_SetOrderProcessing_Handler, }, { MethodName: "SetOrderError", Handler: _StorageAuthority_SetOrderError_Handler, }, { MethodName: "FinalizeOrder", Handler: _StorageAuthority_FinalizeOrder_Handler, }, { MethodName: "GetOrder", Handler: _StorageAuthority_GetOrder_Handler, }, { MethodName: "GetValidOrderAuthorizations", Handler: _StorageAuthority_GetValidOrderAuthorizations_Handler, }, { MethodName: "GetOrderForNames", Handler: _StorageAuthority_GetOrderForNames_Handler, }, { MethodName: "GetAuthorizations", Handler: _StorageAuthority_GetAuthorizations_Handler, }, { MethodName: "AddPendingAuthorizations", Handler: _StorageAuthority_AddPendingAuthorizations_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "sa/proto/sa.proto", } func init() { proto1.RegisterFile("sa/proto/sa.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 1760 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x58, 0xef, 0x72, 0x1b, 0xb7, 0x11, 0xe7, 0x1f, 0xd3, 0x96, 0x56, 0x7f, 0x2c, 0xc1, 0x92, 0x7c, 0x39, 0x4b, 0xb2, 0x8c, 0xb8, 0xae, 0x32, 0xed, 0x28, 0xae, 0xda, 0x49, 0x3a, 0xa3, 0xba, 0xad, 0x64, 0xc9, 0x8c, 0x62, 0x5b, 0x56, 0x8f, 0x8e, 0x92, 0x69, 0x67, 0x3a, 0x03, 0xf3, 0x60, 0x1a, 0x35, 0x75, 0xc7, 0x00, 0xa0, 0x64, 0xf9, 0x05, 0xda, 0x27, 0xe8, 0xf4, 0x63, 0x9f, 0xa3, 0xef, 0xd2, 0x37, 0xe8, 0x0b, 0xf4, 0x5b, 0x07, 0x0b, 0x1c, 0xef, 0x0f, 0xef, 0xc8, 0x78, 0xdc, 0xc9, 0xb7, 0xdb, 0xc5, 0xee, 0x6f, 0x17, 0x8b, 0xc5, 0xe2, 0x47, 0xc2, 0xb2, 0x62, 0x9f, 0x0f, 0x64, 0xac, 0xe3, 0xcf, 0x15, 0xdb, 0xc1, 0x0f, 0xd2, 0x50, 0xcc, 0x5f, 0xed, 0xc6, 0x92, 0xbb, 0x05, 0xf3, 0x69, 0x97, 0xe8, 0x16, 0x2c, 0x06, 0xbc, 0x27, 0x94, 0x96, 0x4c, 0x8b, 0x38, 0x3a, 0x3e, 0x24, 0x8b, 0xd0, 0x10, 0xa1, 0x57, 0xdf, 0xaa, 0x6f, 0x37, 0x83, 0x86, 0x08, 0xe9, 0x26, 0xc0, 0xd7, 0x9d, 0x17, 0x27, 0xdf, 0xf2, 0x57, 0x4f, 0xf9, 0x15, 0x59, 0x82, 0xe6, 0x5f, 0x2e, 0xdf, 0xe2, 0xf2, 0x7c, 0x60, 0x3e, 0xe9, 0x3d, 0xb8, 0xb9, 0x3f, 0xd4, 0x6f, 0x62, 0x29, 0xde, 0x8f, 0x43, 0xcc, 0x22, 0xc4, 0xbf, 0xea, 0xb0, 0xd9, 0xe6, 0xfa, 0x94, 0x47, 0xa1, 0x88, 0x7a, 0x39, 0xeb, 0x80, 0x7f, 0x3f, 0xe4, 0x4a, 0x93, 0x07, 0xb0, 0x28, 0x73, 0x79, 0xb8, 0x0c, 0x0a, 0x5a, 0x63, 0x27, 0x42, 0x1e, 0x69, 0xf1, 0x5a, 0x70, 0xf9, 0xf2, 0x6a, 0xc0, 0xbd, 0x06, 0x86, 0x29, 0x68, 0xc9, 0x36, 0xdc, 0x4c, 0x35, 0x67, 0xac, 0x3f, 0xe4, 0x5e, 0x13, 0x0d, 0x8b, 0x6a, 0xb2, 0x09, 0x70, 0xc1, 0xfa, 0x22, 0xfc, 0x26, 0xd2, 0xa2, 0xef, 0x5d, 0xc3, 0xa8, 0x19, 0x0d, 0x55, 0xb0, 0xd1, 0xe6, 0xfa, 0xcc, 0x28, 0x72, 0x99, 0xab, 0x0f, 0x4d, 0xdd, 0x83, 0x1b, 0x61, 0x7c, 0xce, 0x44, 0xa4, 0xbc, 0xc6, 0x56, 0x73, 0x7b, 0x36, 0x48, 0x44, 0x53, 0xd4, 0x28, 0xbe, 0xc4, 0x04, 0x9b, 0x81, 0xf9, 0xa4, 0xff, 0xac, 0xc3, 0xad, 0x92, 0x90, 0xe4, 0xd7, 0xd0, 0xc2, 0xd4, 0xbc, 0xfa, 0x56, 0x73, 0x7b, 0x6e, 0x97, 0xee, 0x28, 0xb6, 0x53, 0x62, 0xb7, 0xf3, 0x9c, 0x0d, 0x8e, 0xfa, 0xfc, 0x9c, 0x47, 0x3a, 0xb0, 0x0e, 0xfe, 0x0b, 0x80, 0x54, 0x49, 0xd6, 0xe0, 0xba, 0x0d, 0xee, 0x4e, 0xc9, 0x49, 0xe4, 0x33, 0x68, 0xb1, 0xa1, 0x7e, 0xf3, 0x1e, 0xab, 0x3a, 0xb7, 0x7b, 0x6b, 0x07, 0x5b, 0x25, 0x7f, 0x62, 0xd6, 0x82, 0xfe, 0xb7, 0x01, 0xcb, 0x8f, 0xb9, 0x34, 0xa5, 0xec, 0x32, 0xcd, 0x3b, 0x9a, 0xe9, 0xa1, 0x32, 0xc0, 0x8a, 0x4b, 0xc1, 0xfa, 0x09, 0xb0, 0x95, 0xc8, 0x0e, 0x10, 0x35, 0x7c, 0xa5, 0xba, 0x52, 0xbc, 0xe2, 0x72, 0x7f, 0x30, 0x90, 0xf1, 0x05, 0x0f, 0x31, 0xca, 0x4c, 0x50, 0xb2, 0x82, 0x38, 0x88, 0xe8, 0x8e, 0xcd, 0x49, 0xe6, 0x5c, 0xe3, 0xae, 0x1a, 0x3c, 0x63, 0x4a, 0x7f, 0x33, 0x08, 0x99, 0xe6, 0xa1, 0x3b, 0xb2, 0xa2, 0x9a, 0x6c, 0xc1, 0x9c, 0xe4, 0x17, 0xf1, 0x5b, 0x1e, 0x1e, 0x32, 0xcd, 0xbd, 0x16, 0x5a, 0x65, 0x55, 0xe4, 0x3e, 0x2c, 0x38, 0x31, 0xe0, 0x4c, 0xc5, 0x91, 0x77, 0x1d, 0x6d, 0xf2, 0x4a, 0xf2, 0x2b, 0x58, 0xed, 0x33, 0xa5, 0x8f, 0xde, 0x0d, 0x84, 0x3d, 0xca, 0x13, 0xd6, 0xeb, 0xf0, 0x48, 0x7b, 0x37, 0xd0, 0xba, 0x7c, 0x91, 0x50, 0x98, 0x37, 0x09, 0x05, 0x5c, 0x0d, 0xe2, 0x48, 0x71, 0x6f, 0x06, 0x2f, 0x4c, 0x4e, 0x47, 0x7c, 0x98, 0x89, 0x62, 0xbd, 0xff, 0x5a, 0x73, 0xe9, 0xcd, 0x22, 0xd8, 0x48, 0x26, 0xeb, 0x30, 0x2b, 0x14, 0xc2, 0xf2, 0xd0, 0x03, 0x2c, 0x53, 0xaa, 0xa0, 0x5b, 0x70, 0xbd, 0x63, 0xeb, 0x5a, 0x51, 0x6f, 0xba, 0x07, 0xad, 0x80, 0x45, 0x3d, 0x0c, 0xc2, 0x99, 0xec, 0x0b, 0xae, 0xb4, 0xeb, 0xcb, 0x91, 0x6c, 0x9c, 0xfb, 0x4c, 0x9b, 0x95, 0x06, 0xae, 0x38, 0x89, 0x6e, 0x40, 0xeb, 0x71, 0x3c, 0x8c, 0x34, 0x59, 0x81, 0x56, 0xd7, 0x7c, 0x38, 0x4f, 0x2b, 0xd0, 0xef, 0xe0, 0x2e, 0x2e, 0x67, 0x4e, 0x5f, 0x1d, 0x5c, 0x9d, 0xb0, 0x73, 0x3e, 0xba, 0x13, 0x77, 0xa1, 0x25, 0x4d, 0x78, 0x74, 0x9c, 0xdb, 0x9d, 0x35, 0x7d, 0x8a, 0xf9, 0x04, 0x56, 0x6f, 0x90, 0x23, 0xe3, 0xe0, 0xae, 0x82, 0x15, 0xe8, 0x5f, 0xeb, 0x30, 0x8f, 0xd0, 0x0e, 0x8e, 0xfc, 0x0e, 0xe6, 0xbb, 0x19, 0xd9, 0xb5, 0xfd, 0x1d, 0x03, 0x97, 0xb5, 0xcb, 0xf6, 0x7b, 0xce, 0xc1, 0xff, 0x22, 0xd7, 0xf6, 0x04, 0xae, 0x99, 0x40, 0xae, 0x56, 0xf8, 0x9d, 0xee, 0xb1, 0x91, 0xdd, 0xe3, 0x29, 0x6c, 0x60, 0x80, 0xec, 0x70, 0x54, 0x07, 0x57, 0xc7, 0xa7, 0xc9, 0x0e, 0xcd, 0x8c, 0x1b, 0xb8, 0x39, 0xd8, 0x10, 0x83, 0x74, 0xc7, 0x8d, 0xf2, 0x1d, 0xd3, 0xbf, 0xd5, 0xe1, 0x1e, 0x42, 0x1e, 0x47, 0x17, 0x1f, 0x3f, 0x4c, 0x7c, 0x98, 0x79, 0x13, 0x2b, 0x8d, 0xbb, 0xb1, 0x13, 0x70, 0x24, 0xa7, 0xa9, 0x34, 0x2b, 0x52, 0xe9, 0x00, 0xc1, 0x4c, 0x5e, 0xc8, 0x90, 0xcb, 0x51, 0xe8, 0x75, 0x98, 0x65, 0x5d, 0xdc, 0xfd, 0x28, 0x6a, 0xaa, 0x98, 0xbe, 0xbf, 0x43, 0x58, 0x69, 0x73, 0xdd, 0x79, 0xfc, 0x32, 0xe0, 0x5d, 0x2e, 0x06, 0x3a, 0x81, 0xad, 0x9a, 0x08, 0x2b, 0xd0, 0xea, 0xc7, 0xbd, 0xe3, 0x43, 0x97, 0xbe, 0x15, 0xe8, 0x57, 0xb0, 0x82, 0xa9, 0x3d, 0xf9, 0xc3, 0xe1, 0x49, 0x87, 0x6b, 0x95, 0x41, 0xb9, 0x14, 0x51, 0x18, 0x5f, 0xba, 0xcc, 0x9c, 0x54, 0x3d, 0x54, 0xe9, 0x43, 0x58, 0x71, 0x20, 0x47, 0xef, 0x84, 0x4a, 0x91, 0x32, 0x1e, 0xf5, 0xbc, 0xc7, 0x29, 0x6c, 0x9d, 0x4a, 0x7e, 0x21, 0xe2, 0xa1, 0xca, 0xb4, 0x76, 0xde, 0xbb, 0x6a, 0x70, 0xae, 0x40, 0x4b, 0xf2, 0x64, 0x37, 0xcd, 0xc0, 0x0a, 0xe6, 0x9e, 0x5a, 0x77, 0xe3, 0xc7, 0xf1, 0x0b, 0xfd, 0x66, 0x02, 0x27, 0xd1, 0xa7, 0xb0, 0xf1, 0x9c, 0xc9, 0xb7, 0x99, 0x78, 0x41, 0x32, 0x7d, 0x26, 0x97, 0x8f, 0xc0, 0xb5, 0x6e, 0x1c, 0x72, 0x17, 0x0f, 0xbf, 0x69, 0x07, 0x56, 0xf7, 0xc3, 0x30, 0x87, 0x65, 0x41, 0x96, 0xa0, 0x19, 0x72, 0x99, 0xbc, 0xda, 0x21, 0x97, 0xe5, 0xf9, 0x1a, 0x50, 0x33, 0xa1, 0xb0, 0x71, 0xe6, 0x03, 0xfc, 0xa6, 0x0f, 0x61, 0xad, 0x08, 0xea, 0xe6, 0x97, 0xa9, 0x85, 0xe8, 0x25, 0x83, 0xc5, 0xd4, 0x02, 0x25, 0xfa, 0x9f, 0x3a, 0xf8, 0x1d, 0xd1, 0x8b, 0x78, 0xd6, 0xeb, 0xa5, 0x38, 0xe7, 0x4a, 0xb3, 0xf3, 0x41, 0x91, 0x60, 0x98, 0x07, 0x58, 0x75, 0xf5, 0x19, 0x97, 0x4a, 0xc4, 0x91, 0xcb, 0x27, 0xa3, 0x49, 0x1b, 0xa5, 0x99, 0x69, 0x14, 0xd3, 0xad, 0x3a, 0x81, 0x74, 0x4f, 0x40, 0xaa, 0x30, 0x98, 0xfc, 0x9d, 0xe6, 0x91, 0x01, 0x50, 0x38, 0xfb, 0xe7, 0x83, 0x8c, 0xc6, 0x78, 0x2b, 0xd1, 0x8b, 0x98, 0x1e, 0x4a, 0x8e, 0x63, 0x7f, 0x3e, 0x48, 0x15, 0xe4, 0xe7, 0xb0, 0xdc, 0xcd, 0xbc, 0x6c, 0xb6, 0xfc, 0x37, 0x30, 0xfa, 0xf8, 0x02, 0x7d, 0x04, 0x9f, 0xda, 0x33, 0xcb, 0xdf, 0xe8, 0x83, 0xab, 0x43, 0x6c, 0x8d, 0x29, 0x9d, 0x43, 0xff, 0x0c, 0xf7, 0x27, 0xbb, 0xbb, 0x6a, 0xaf, 0xc3, 0xec, 0x6b, 0x11, 0xb1, 0xbe, 0x78, 0xcf, 0x93, 0xea, 0xa5, 0x0a, 0xd3, 0xd5, 0x03, 0x4b, 0xaf, 0x5c, 0x05, 0x13, 0x91, 0x6e, 0xc2, 0x3c, 0xde, 0xf3, 0xec, 0xe0, 0xca, 0xf2, 0xbb, 0x67, 0x40, 0x13, 0x7e, 0x83, 0x76, 0xe5, 0x73, 0xa9, 0x78, 0x68, 0x6b, 0x70, 0x9d, 0x75, 0xbb, 0x7a, 0xd4, 0x40, 0x4e, 0xa2, 0x6d, 0xb8, 0xdd, 0xe6, 0x76, 0xb0, 0x3c, 0x89, 0x65, 0xee, 0x4d, 0x48, 0x5d, 0xea, 0x59, 0x97, 0x8a, 0xa7, 0xe0, 0x1f, 0x75, 0xf0, 0xda, 0x5c, 0xff, 0x68, 0x94, 0xcb, 0x30, 0x0b, 0xc9, 0xbf, 0x1f, 0x0a, 0xc9, 0xcf, 0x76, 0x4d, 0xd4, 0xf7, 0x0a, 0xdb, 0x6a, 0x26, 0x28, 0xaa, 0xe9, 0xdf, 0xeb, 0xb0, 0x58, 0xe0, 0x65, 0xbf, 0x4c, 0x78, 0x93, 0x7d, 0xa0, 0x36, 0xcc, 0x74, 0x9c, 0x40, 0xc9, 0xd0, 0xf6, 0xff, 0x4f, 0xc9, 0x9e, 0xc1, 0xdd, 0xfd, 0x30, 0x2c, 0xa3, 0xd9, 0xa3, 0xca, 0x7d, 0x96, 0x4f, 0x74, 0x12, 0xda, 0x7d, 0x58, 0x2a, 0x10, 0x7b, 0x2c, 0x9b, 0x08, 0x93, 0xc1, 0x69, 0x3e, 0x77, 0xff, 0xbd, 0x02, 0x4b, 0x1d, 0x1d, 0x4b, 0xd6, 0x4b, 0x1a, 0x58, 0x5f, 0x91, 0x3d, 0xb8, 0xd9, 0xe6, 0xb9, 0xb7, 0x93, 0x10, 0x7c, 0x30, 0x72, 0xc7, 0xe3, 0x13, 0x1b, 0x3d, 0xab, 0xa5, 0x35, 0xf2, 0x1b, 0x7c, 0x48, 0xb2, 0xca, 0x83, 0x2b, 0xf3, 0xd3, 0x63, 0xd1, 0x20, 0xa4, 0x3f, 0x45, 0x2a, 0xbc, 0x7f, 0x0b, 0x4b, 0xc5, 0xb6, 0x21, 0xb7, 0xc6, 0x8e, 0xe3, 0xf8, 0xd0, 0x2f, 0xdb, 0x3a, 0xad, 0x91, 0x97, 0xd8, 0xc0, 0x65, 0x35, 0x24, 0xc8, 0xb6, 0x27, 0xff, 0x8e, 0xa9, 0x42, 0x3d, 0x83, 0xb5, 0xf2, 0x1f, 0x11, 0xe4, 0x9e, 0x03, 0xad, 0xfe, 0x81, 0xe1, 0xdf, 0xae, 0x60, 0xf9, 0xb4, 0x46, 0x7e, 0x01, 0x8b, 0x6d, 0x9e, 0x25, 0x62, 0x04, 0x8c, 0xb1, 0x9d, 0x4c, 0xfe, 0xb2, 0x4d, 0x26, 0xb3, 0x4c, 0x6b, 0x64, 0x0f, 0xcb, 0x3b, 0xce, 0xdc, 0xb3, 0x8e, 0xab, 0x48, 0xb0, 0x8a, 0x26, 0xb4, 0x46, 0x1e, 0xc2, 0xda, 0x18, 0xf5, 0xb3, 0x3c, 0x33, 0x25, 0x04, 0xfe, 0xec, 0x88, 0x9e, 0xd1, 0x1a, 0xe9, 0x80, 0x57, 0x45, 0x16, 0xc9, 0xa7, 0x23, 0xc3, 0x6a, 0x2a, 0xe9, 0x2f, 0x15, 0xc9, 0x1e, 0xad, 0x91, 0xef, 0x1c, 0x3b, 0xcb, 0xbb, 0x1d, 0xbd, 0x63, 0x5d, 0xfd, 0x91, 0xc8, 0x5f, 0xb9, 0x0d, 0x8e, 0xf1, 0x3e, 0x7b, 0x50, 0x13, 0x39, 0x61, 0x7e, 0xe3, 0xcf, 0xe1, 0x4e, 0x85, 0x35, 0xd6, 0xeb, 0x43, 0xe1, 0x1e, 0x81, 0x8f, 0x9f, 0xa5, 0xb7, 0xbb, 0xf4, 0x76, 0xe5, 0xdc, 0x77, 0x61, 0x2e, 0x43, 0xf9, 0xc8, 0xda, 0x68, 0x2d, 0xc7, 0x01, 0xf3, 0x3e, 0xa7, 0x2e, 0x64, 0x29, 0x61, 0x25, 0x3f, 0x19, 0x99, 0x4e, 0x22, 0xb4, 0x79, 0xc4, 0xa7, 0xb0, 0x90, 0xe3, 0x88, 0xc4, 0x73, 0xdd, 0x3f, 0x46, 0x1b, 0xfd, 0x4d, 0x6c, 0xc7, 0x4a, 0x16, 0x41, 0x6b, 0xe4, 0x0b, 0x58, 0xc8, 0x51, 0x45, 0x0b, 0x56, 0xc6, 0x1e, 0xf3, 0x49, 0x7c, 0x09, 0x0b, 0x39, 0x62, 0x68, 0xfd, 0xca, 0xb8, 0xa2, 0x8f, 0x77, 0xc2, 0xaa, 0x68, 0x8d, 0xbc, 0x80, 0x4f, 0x2a, 0xf9, 0x21, 0xb9, 0x6f, 0x4c, 0xa7, 0xd1, 0xc7, 0x02, 0xe0, 0x1e, 0xdc, 0x3c, 0xe1, 0x97, 0x85, 0x31, 0x39, 0x36, 0xd4, 0x2a, 0x06, 0xdd, 0x97, 0x40, 0xec, 0x4f, 0xdd, 0xa9, 0xfe, 0x73, 0x56, 0x77, 0x74, 0x3e, 0xd0, 0x57, 0xb4, 0x46, 0x8e, 0xe0, 0xf6, 0x09, 0xbf, 0x2c, 0x9d, 0x70, 0x65, 0xd3, 0xab, 0x6a, 0xa4, 0xfd, 0x1e, 0x7c, 0x1b, 0xff, 0x87, 0x23, 0x15, 0x12, 0xd9, 0x83, 0xd5, 0x27, 0x8e, 0xc0, 0x7c, 0xb8, 0xf3, 0xd7, 0xb0, 0x56, 0x4e, 0x9c, 0xed, 0xcd, 0x9a, 0x48, 0xaa, 0x8b, 0x58, 0xc7, 0xb0, 0x98, 0xa7, 0xb8, 0xe4, 0x13, 0x7c, 0x31, 0xca, 0xb8, 0xb4, 0xef, 0x97, 0x2d, 0x59, 0x8e, 0x86, 0xcf, 0xcf, 0xc2, 0x7e, 0x18, 0x66, 0x3a, 0x7c, 0x4a, 0x1f, 0x17, 0x53, 0x51, 0xb0, 0x3e, 0x89, 0x0d, 0x92, 0x9f, 0xda, 0x8b, 0x3e, 0x95, 0x6e, 0xfa, 0xdb, 0xd3, 0x0d, 0x47, 0x49, 0xef, 0xc1, 0xda, 0x21, 0x67, 0x5d, 0x2d, 0x2e, 0xc6, 0xdb, 0x69, 0x7c, 0xae, 0x14, 0x32, 0x7e, 0x04, 0xb7, 0x53, 0xe7, 0x1f, 0xf0, 0xee, 0x16, 0xdc, 0x1f, 0xc0, 0xcc, 0x09, 0xbf, 0xc4, 0x29, 0x44, 0xdc, 0x12, 0x0a, 0x7e, 0x56, 0xc0, 0x97, 0x87, 0x74, 0x1c, 0xb1, 0x3c, 0x95, 0x71, 0x97, 0x2b, 0x25, 0xa2, 0x5e, 0xa9, 0x47, 0x82, 0xfc, 0x33, 0x58, 0x48, 0x3c, 0x8e, 0xa4, 0x8c, 0xe5, 0x34, 0xe3, 0xa4, 0x17, 0xab, 0x73, 0x49, 0x8d, 0x67, 0x12, 0x92, 0x4b, 0xf0, 0x11, 0xc9, 0x12, 0xec, 0x62, 0xe2, 0x7f, 0x82, 0x3b, 0x13, 0xf8, 0x35, 0x79, 0x90, 0x7d, 0xff, 0xab, 0x09, 0xb8, 0x4f, 0xc6, 0x29, 0xe5, 0x88, 0xed, 0xe4, 0xe8, 0x36, 0xb9, 0xe3, 0x10, 0xcb, 0x48, 0x78, 0x31, 0xb9, 0x36, 0x2c, 0x8f, 0x91, 0x6c, 0xb2, 0xee, 0x00, 0x3e, 0x24, 0x91, 0x6f, 0xc1, 0xab, 0xa2, 0x9e, 0xf6, 0x31, 0x9e, 0x42, 0x4c, 0xfd, 0x95, 0x92, 0x5e, 0x51, 0xb4, 0x76, 0x70, 0xe3, 0x8f, 0x2d, 0xfc, 0xa7, 0xfa, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x5e, 0x68, 0x89, 0xbd, 0xd8, 0x16, 0x00, 0x00, }
dave2wave/whimsy
www/board/agenda/config.ru
require 'whimsy/asf/rack' require File.expand_path('../main.rb', __FILE__) # https://svn.apache.org/repos/infra/infrastructure/trunk/projects/whimsy/asf/rack.rb use ASF::Auth::MembersAndOfficers do |env| # allow access to bootstrap related content if env['PATH_INFO'] =~ %r{^/(app|sw)\.js(\.map)?$} or env['PATH_INFO'] =~ %r{\.js\.rb?$} or env['PATH_INFO'] =~ %r{^/stylesheets/.*\.css\$} or env['PATH_INFO'] =~ %r{^/[-\d]+/bootstrap.html$} or env['PATH_INFO'] == '/manifest.json' then next true end # allow access to historical-comments and post for reporter tool. # notes: # - historical-comments and latest is filtered by routes.rb to only include # the list of PMCs that the user is a member of for non-ASF-members and # non-officers. # - post is limited to ASF members, officers, and members of the PMC whose # report is being posted. # - reporter can be used with both HTTP GET and POST. GET is filtered # like historical-commits, and POST is limited like post. # - calendar is available to all committers next true if env['PATH_INFO'] == '/json/historical-comments' next true if env['PATH_INFO'] == '/json/post' next true if env['PATH_INFO'] == '/json/reporter' next true if env['PATH_INFO'] == '/latest.json' next true if env['PATH_INFO'] == '/calendar.json' # additionally authorize all invited guests agenda = dir('board_agenda_*.txt').sort.last if agenda Agenda.parse(agenda, :full) roll = Agenda[agenda][:parsed].find {|item| item['title'] == 'Roll Call'} roll['people'].keys.include? env['REMOTE_USER'] end end use ASF::HTTPS_workarounds use ASF::ETAG_Deflator_workaround use ASF::DocumentRoot run Sinatra::Application
unidal/phoenix
phoenix-load-balancer/src/main/java/com/dianping/phoenix/lb/constant/MessageID.java
/** * Project: phoenix-load-balancer * * File Created at Oct 28, 2013 * */ package com.dianping.phoenix.lb.constant; /** * @author <NAME> * */ public enum MessageID { STRATEGY_SAVE_FAIL("strategy_save_fail"), // STRATEGY_NAME_EMPTY("strategy_name_empty"), // STRATEGY_TYPE_EMPTY("strategy_type_empty"), // // VIRTUALSERVER_ALREADY_EXISTS("vs_already_exists"), // VIRTUALSERVER_SAVE_FAIL("vs_save_fail"), // VIRTUALSERVER_CONCURRENT_MOD("vs_concurrent_mod"), // VIRTUALSERVER_NOT_EXISTS("vs_not_exists"), // VIRTUALSERVER_DEL_FAIL("vs_del_fail"), // VIRTUALSERVER_NAME_EMPTY("vs_name_empty"), // VIRTUALSERVER_TAGID_EMPTY("vs_pushid_empty"), // VIRTUALSERVER_DEFAULTPOOL_NOT_EXISTS("vs_defaultpool_not_exists"), // VIRTUALSERVER_DIRECTIVE_TYPE_NOT_SUPPORT("vs_directive_type_not_support"), // VIRTUALSERVER_LOCATION_NO_DOMAIN("vs_location_no_domain"), // VIRTUALSERVER_STRATEGY_NOT_SUPPORT("vs_strategy_not_support"), // VIRTUALSERVER_TAG_FAIL("vs_tag_fail"), // VIRTUALSERVER_TAG_LOAD_FAIL("vs_tag_load_fail"), // VIRTUALSERVER_TAG_NOT_FOUND("vs_tag_not_found"), // VIRTUALSERVER_TAG_LIST_FAIL("vs_tag_list_fail"), // POOL_LOWER_THAN_MINAVAIL_PCT("pool_lower_than_minavail_pct"), // POOL_NO_MEMBER("pool_no_member"), // ; private String messageId; private MessageID(String messageId) { this.messageId = messageId; } public String messageId() { return this.messageId; } }
ngswbryan/main
src/test/java/seedu/address/logic/commands/FindNotesCommandTest.java
package seedu.address.logic.commands; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.commons.core.Messages.MESSAGE_NOTES_LISTED_OVERVIEW; import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess; import static seedu.address.testutil.TypicalNotes.getTypicalTutorAid; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.note.FindNotesCommand; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.note.NotesContainsKeywordsPredicate; public class FindNotesCommandTest { private Model model = new ModelManager(getTypicalTutorAid(), new UserPrefs()); private Model expectedModel = new ModelManager(getTypicalTutorAid(), new UserPrefs()); @Test public void equals() { NotesContainsKeywordsPredicate firstPredicate = new NotesContainsKeywordsPredicate(Collections.singletonList("CS2100")); NotesContainsKeywordsPredicate secondPredicate = new NotesContainsKeywordsPredicate(Collections.singletonList("CS2103T")); FindNotesCommand firstNotesCommand = new FindNotesCommand(firstPredicate); FindNotesCommand secondNotesCommand = new FindNotesCommand(secondPredicate); // same object -> returns true assertTrue(firstNotesCommand.equals(firstNotesCommand)); // same values -> returns true FindNotesCommand findFirstNotesCommandCopy = new FindNotesCommand(firstPredicate); assertTrue(firstNotesCommand.equals(firstNotesCommand)); // different types -> returns false assertFalse(firstNotesCommand.equals(1)); // null -> returns false assertFalse(firstNotesCommand.equals(null)); // different person -> returns false assertFalse(firstNotesCommand.equals(secondNotesCommand)); } @Test public void execute_zeroKeywords_noNotesFound() { String expectedMessage = String.format(MESSAGE_NOTES_LISTED_OVERVIEW, 0); NotesContainsKeywordsPredicate predicate = getPredicate(" "); FindNotesCommand command = new FindNotesCommand(predicate); expectedModel.updateFilteredNotesList(predicate); assertCommandSuccess(command, model, expectedMessage, expectedModel); assertEquals(Collections.emptyList(), model.getFilteredNotesList()); } /** * Parses {@code userInput} into a {@code NameContainsKeywordsPredicate}. */ private NotesContainsKeywordsPredicate getPredicate(String userInput) { return new NotesContainsKeywordsPredicate(Arrays.asList(userInput.split("\\s+"))); } }
xiongwq16/exact-algorithm
src/fctp/subproblem/FctpSubProblemDual.java
package fctp.subproblem; import fctp.AbstractFctpSubProblem; import fctp.Fctp; import fctp.Parameters; import ilog.concert.IloException; import ilog.concert.IloLinearNumExpr; import ilog.concert.IloLinearNumExprIterator; import ilog.concert.IloNumExpr; import ilog.concert.IloNumVar; import ilog.concert.IloRange; import ilog.cplex.IloCplex; import ilog.cplex.IloCplex.UnknownObjectException; import java.util.HashMap; /** * FCTP 子问题(对偶形式). * * @author <NAME> * @version V1.0 * @since JDK1.8 */ public class FctpSubProblemDual extends AbstractFctpSubProblem { /** 需求量约束的对偶变量,对应需求量约束. */ private IloNumVar[] demandDualVars; /** 容量约束的对偶变量,对应容量约束:for j in warehouses. */ private IloNumVar[] capacityDualVars; /** 记录目标函数系数,便于生成割平面(重要). */ private HashMap<IloNumVar, IloLinearNumExpr> objCoeff; /** 对偶问题约束,constraints[j][k] 对应的对偶变量即为原问题中的 仓库 j 供应给客户 k 的货量. */ private IloRange[][] constraints; /** * Create a Instance FctpSubProblemDual. * * @param fctpIns FCTP 实例 * @param openVar 主问题中的 open 变量 * @throws IloException */ public FctpSubProblemDual(Fctp fctpIns, IloNumVar[] openVar) throws IloException { super(fctpIns); // 创建决策变量,并保存对应的目标函数系数 demandDualVars = new IloNumVar[customerNum]; capacityDualVars = new IloNumVar[warehouseNum]; objCoeff = new HashMap<>((int)((customerNum + warehouseNum) / Parameters.LOADER_FACTOR) + 1); double[] demand = fctpIns.getDemand(); for (int k = 0; k < customerNum; k++) { demandDualVars[k] = subSolver.numVar(0.0, Double.MAX_VALUE, "u_" + k); // 保存需求量约束对应的对偶变量在子问题目标函数中的系数 objCoeff.put(demandDualVars[k], subSolver.linearNumExpr(demand[k])); } double[] capacity = fctpIns.getCapacity(); for (int j = 0; j < warehouseNum; j++) { capacityDualVars[j] = subSolver.numVar(0.0, Double.MAX_VALUE, "v_" + j); /* * 保存容量约束对应的对偶变量在子问题目标函数中的系数 * 注意这里的右侧项存放的变量 -capacity[j] * open[j] */ IloLinearNumExpr expr = subSolver.linearNumExpr(); expr.addTerm(-capacity[j], openVar[j]); objCoeff.put(capacityDualVars[j], expr); } // 对偶约束,u[k] - v[j] >= flowCost[j][k] double[][] flowCost = fctpIns.getFlowCost(); constraints = new IloRange[warehouseNum][customerNum]; for (int j = 0; j < warehouseNum; j++) { for (int k = 0; k < customerNum; k++) { constraints[j][k] = subSolver.addLe( subSolver.diff(demandDualVars[k], capacityDualVars[j]), flowCost[j][k]); } } // 最大化目标 subSolver.addMaximize(); /* * Turn off the "presolve" reductions * if the presolver recognizes that the subproblem is infeasible, we do not get a dual ray */ subSolver.setParam(IloCplex.Param.Preprocessing.Reduce, 0); // Solve the subProblem(Dual Type) with dual simplex method subSolver.setParam(IloCplex.Param.RootAlgorithm, IloCplex.Algorithm.Dual); subSolver.setOut(null); } @Override protected double getFlowBetween(int warehouseIndex, int customerIndex) throws UnknownObjectException, IloException { return subSolver.getDual(constraints[warehouseIndex][customerIndex]); } @Override protected IloCplex.Status solve(double[] openValues, double[] capacity) throws IloException { IloNumExpr objExpr = subSolver.numExpr(); // 根据仓库开设情况更新的容量 double[] openCapacity = new double[warehouseNum]; for (int j = 0; j < warehouseNum; j++) { openCapacity[j] = 0; if (openValues[j] > Parameters.ROUNDUP) { openCapacity[j] = -capacity[j]; } objExpr = subSolver.sum(objExpr, subSolver.prod(openCapacity[j], capacityDualVars[j])); } for (int k = 0; k < customerNum; k++) { objExpr = subSolver.sum(objExpr, subSolver.prod(objCoeff.get(demandDualVars[k]), demandDualVars[k])); } subSolver.getObjective().setExpr(objExpr); subSolver.solve(); return subSolver.getStatus(); } @Override protected IloRange createFeasibilityCut() throws IloException { IloLinearNumExpr ray = subSolver.getRay(); IloLinearNumExprIterator it = ray.linearIterator(); // 约束的右侧项 * 对应的极射线的值 IloNumExpr expr = subSolver.numExpr(); while (it.hasNext()) { IloNumVar var = it.nextNumVar(); double value = it.getValue(); expr = subSolver.sum(expr, subSolver.prod(value, objCoeff.get(var))); } // 返回对偶问题的极射线对应的“可行割”:u^r(d - Gx) <= 0 return subSolver.le(expr, 0); } @Override protected IloRange createOptimalityCut(IloNumVar estFlowCost) throws IloException { IloNumExpr expr = subSolver.numExpr(); // 需求量约束的右侧项 * 对偶变量值 double dualVal; for (int k = 0; k < customerNum; k++) { dualVal = subSolver.getValue(demandDualVars[k]); expr = subSolver.sum(expr, subSolver.prod(objCoeff.get(demandDualVars[k]), dualVal)); } // 容量约束的右侧项 * 对偶变量值 for (int j = 0; j < warehouseNum; j++) { dualVal = subSolver.getValue(capacityDualVars[j]); expr = subSolver.sum(expr, subSolver.prod(objCoeff.get(capacityDualVars[j]), dualVal)); } // 返回对偶问题的极点对应的“最优割”:u^t(d - Gx) <= sigma return subSolver.le(subSolver.diff(expr, estFlowCost), 0); } }
rudty/nodekell
test/take.spec.js
"use strict"; const F = require("../index"); const assert = require("assert"); describe('test take', () => { it('<', async () => { const a = [1,2,3,4,5]; const r = F.take(1, a); const result = [] for await (const e of r) { result.push(e); } assert.deepStrictEqual(result, [1]); }); it('==', async () => { const a = [1,2,3,4,5]; const r = F.take(5, a); const result = [] for await (const e of r) { result.push(e); } assert.deepStrictEqual(result, [1,2,3,4,5]); }); it('>', async () => { const a = [1,2,3,4,5]; const r = F.take(Infinity, a); const result = [] for await (const e of r) { result.push(e); } assert.deepStrictEqual(result, [1,2,3,4,5]); }); it('0', async () => { const a = [1,2,3,4,5]; const r = F.take(0, a); const result = [] for await (const e of r) { result.push(e); } assert.deepStrictEqual(result, []); }); });
mail-ru-im/im-desktop
gui/main_window/history_control/feeds/FeedPage.h
#pragma once #include "../PageBase.h" namespace Ui { enum class FeedType { Threads, }; class FeedDataLoader : public QObject { public: FeedDataLoader(QObject* _parent) : QObject(_parent) {} virtual void loadNext() = 0; virtual bool isLoading() const { return false; } virtual bool isExhausted() const { return true; } virtual void reset() {} }; class MessagesFeedLoader : public FeedDataLoader { Q_OBJECT Q_SIGNALS: void pageLoaded(const Data::MessageBuddies& _messages); public: MessagesFeedLoader(QObject* _parent) : FeedDataLoader(_parent) {} }; class FeedDataContainer: public QWidget { Q_OBJECT public: FeedDataContainer(QWidget* _parent) : QWidget(_parent) {} virtual void setLoader(FeedDataLoader* _loader) {} virtual void setPlaceholder(QWidget* _placeholder) {} virtual void onPageOpened() {} virtual void onPageLeft() {} }; class FeedPage_p; class FeedPage : public PageBase { Q_OBJECT public: FeedPage(const QString& _id, QWidget* _parent); ~FeedPage(); const QString& aimId() const override; QWidget* getTopWidget() const override; void setUnreadBadgeText(const QString& _text) override; void setPrevChatButtonVisible(bool _visible) override; void setOverlayTopWidgetVisible(bool _visible) override; void pageOpen() override; void pageLeave() override; protected: void resizeEvent(QResizeEvent* _event) override; void paintEvent(QPaintEvent* _event) override; private: FeedDataLoader* createDataLoader(); FeedDataContainer* createContainer(); std::unique_ptr<FeedPage_p> d; }; }
leafina/pxview
src/screens/MyPage/MyPage.js
<filename>src/screens/MyPage/MyPage.js import React, { Component, useRef } from 'react'; import { StyleSheet, View, ScrollView, Alert } from 'react-native'; import { connect } from 'react-redux'; import { useScrollToTop } from '@react-navigation/native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { Icon } from 'react-native-elements'; import { withTheme } from 'react-native-paper'; // import CookieManager from 'react-native-cookies'; import { connectLocalization } from '../../components/Localization'; import UserCover from '../../components/UserCover'; import PXListItem from '../../components/PXListItem'; import * as authActionCreators from '../../common/actions/auth'; import * as browsingHistoryIllustsActionCreators from '../../common/actions/browsingHistoryIllusts'; import * as browsingHistoryNovelsActionCreators from '../../common/actions/browsingHistoryNovels'; import * as searchHistoryActionCreators from '../../common/actions/searchHistory'; import * as themeActionCreators from '../../common/actions/theme'; import { SCREENS, THEME_TYPES } from '../../common/constants'; const styles = StyleSheet.create({ container: { flex: 1, }, listContainer: { marginHorizontal: 10, }, }); const menuList = [ { id: 'works', title: 'myWorks', icon: 'picture-o', type: 'font-awesome', }, { id: 'connection', title: 'connection', icon: 'users', type: 'font-awesome', }, { id: 'collection', title: 'collection', icon: 'heart', type: 'font-awesome', }, { id: 'browsingHistory', title: 'browsingHistory', icon: 'clock-o', type: 'font-awesome', }, ]; const menuList2 = [ { id: 'settings', title: 'settings', icon: 'cog', type: 'font-awesome', }, { id: 'feedback', title: 'feedback', icon: 'comment-o', type: 'font-awesome', }, { id: 'logout', title: 'logout', icon: 'sign-out', type: 'font-awesome', }, ]; class MyPage extends Component { handleOnPressListItem = (item) => { const { user, navigation: { navigate }, } = this.props; switch (item.id) { case 'works': navigate(SCREENS.MyWorks, { userId: user.id }); break; case 'collection': navigate(SCREENS.MyCollection, { userId: user.id }); break; case 'connection': navigate(SCREENS.MyConnection, { userId: user.id }); break; case 'browsingHistory': navigate(SCREENS.BrowsingHistory); break; case 'settings': { navigate(SCREENS.Settings); break; } case 'feedback': { navigate(SCREENS.Feedback); break; } case 'logout': { this.handleOnPressLogout(); break; } default: break; } }; handleOnPressLogout = () => { const { user, i18n } = this.props; if (user.isProvisionalAccount) { Alert.alert( i18n.logoutConfirmNoRegisterTitle, i18n.logoutConfirmNoRegisterDescription, [ { text: i18n.cancel, style: 'cancel' }, { text: i18n.commentRequireAccountRegistrationAction, onPress: this.handleOnPressRegisterAccount, }, { text: i18n.logout, style: 'destructive', onPress: this.handleOnPressConfirmLogout, }, ], { cancelable: false }, ); } else { Alert.alert( i18n.logoutConfirm, null, [ { text: i18n.cancel, style: 'cancel' }, { text: i18n.logout, style: 'destructive', onPress: this.handleOnPressConfirmLogout, }, ], { cancelable: false }, ); } }; handleOnPressConfirmLogout = () => { const { clearBrowsingHistoryIllusts, clearBrowsingHistoryNovels, clearSearchHistory, logout, } = this.props; logout(); clearBrowsingHistoryIllusts(); clearBrowsingHistoryNovels(); clearSearchHistory(); // clear cookies set from webview for advance account settings // CookieManager.clearAll(); }; handleOnPressRegisterAccount = () => { const { navigation: { navigate }, } = this.props; navigate(SCREENS.AccountSettingsModal, { hideAdvanceSettings: true, }); }; handleOnPressAvatar = () => { const { user, navigation: { navigate }, } = this.props; if (user) { navigate(SCREENS.UserDetail, { userId: user.id, }); } }; handleOnPressChangeTheme = () => { const { themeName, setTheme } = this.props; if (themeName === THEME_TYPES.DARK) { setTheme(THEME_TYPES.LIGHT); } else { setTheme(THEME_TYPES.DARK); } }; renderCover = () => { const { user, i18n, themeName } = this.props; return ( <UserCover user={user} i18n={i18n} themeName={themeName} onPressAvatar={this.handleOnPressAvatar} onPressChangeTheme={this.handleOnPressChangeTheme} /> ); }; renderList = (list) => { const { user, i18n } = this.props; if (!user && list.some((l) => l.id === 'logout')) { list = list.filter((l) => l.id !== 'logout'); } return ( <View style={styles.listContainer}> {list.map((item) => ( <PXListItem key={item.id} title={i18n[item.title]} left={({ color }) => ( <Icon name={item.icon} type={item.type} color={color} size={item.size} /> )} onPress={() => this.handleOnPressListItem(item)} /> ))} </View> ); }; render() { const { theme, scrollRef } = this.props; return ( <SafeAreaView style={[ styles.container, { backgroundColor: theme.colors.background, }, ]} > <ScrollView ref={scrollRef} style={styles.container}> {this.renderCover()} {this.renderList(menuList)} {this.renderList(menuList2)} </ScrollView> </SafeAreaView> ); } } const MyPageWithHOC = withTheme( connectLocalization( connect( (state) => ({ user: state.auth.user, themeName: state.theme.name, }), { ...authActionCreators, ...browsingHistoryIllustsActionCreators, ...browsingHistoryNovelsActionCreators, ...searchHistoryActionCreators, ...themeActionCreators, }, )(MyPage), ), ); export default function (props) { const ref = useRef(null); useScrollToTop(ref); // eslint-disable-next-line react/jsx-props-no-spreading return <MyPageWithHOC {...props} scrollRef={ref} />; }
Amoryan/fresco
imagepipeline/src/test/java/com/facebook/imagepipeline/memory/SharedByteArrayTest.java
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.memory; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import com.facebook.common.memory.MemoryTrimType; import com.facebook.common.memory.MemoryTrimmableRegistry; import com.facebook.common.references.CloseableReference; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; /** * Tests for {@link SharedByteArray} */ @RunWith(RobolectricTestRunner.class) public class SharedByteArrayTest { private SharedByteArray mArray; @Before public void setup() { mArray = new SharedByteArray( mock(MemoryTrimmableRegistry.class), new PoolParams( Integer.MAX_VALUE, Integer.MAX_VALUE, null, 4, 16, 1)); } @Test public void testBasic() throws Exception { assertEquals(4, mArray.mMinByteArraySize); assertEquals(16, mArray.mMaxByteArraySize); assertNull(mArray.mByteArraySoftRef.get()); assertEquals(1, mArray.mSemaphore.availablePermits()); } @Test public void testGet() throws Exception { CloseableReference<byte[]> arrayRef = mArray.get(1); assertSame(mArray.mByteArraySoftRef.get(), arrayRef.get()); assertEquals(4, arrayRef.get().length); assertEquals(0, mArray.mSemaphore.availablePermits()); } @Test(expected = IllegalArgumentException.class) public void testGetTooBigArray() { mArray.get(32); } @Test public void testRelease() throws Exception { mArray.get(4).close(); assertEquals(1, mArray.mSemaphore.availablePermits()); } @Test public void testGet_Realloc() { CloseableReference<byte[]> arrayRef = mArray.get(1); final byte[] smallArray = arrayRef.get(); arrayRef.close(); arrayRef = mArray.get(7); assertEquals(8, arrayRef.get().length); assertSame(mArray.mByteArraySoftRef.get(), arrayRef.get()); assertNotSame(smallArray, arrayRef.get()); } @Test public void testTrim() { mArray.get(7).close(); assertEquals(8, mArray.mByteArraySoftRef.get().length); // now trim, and verify again mArray.trim(MemoryTrimType.OnCloseToDalvikHeapLimit); assertNull(mArray.mByteArraySoftRef.get()); assertEquals(1, mArray.mSemaphore.availablePermits()); } @Test public void testTrimUnsuccessful() { CloseableReference<byte[]> arrayRef = mArray.get(7); mArray.trim(MemoryTrimType.OnCloseToDalvikHeapLimit); assertSame(arrayRef.get(), mArray.mByteArraySoftRef.get()); assertEquals(0, mArray.mSemaphore.availablePermits()); } @Test public void testGetBucketedSize() throws Exception { assertEquals(4, mArray.getBucketedSize(1)); assertEquals(4, mArray.getBucketedSize(2)); assertEquals(4, mArray.getBucketedSize(3)); assertEquals(4, mArray.getBucketedSize(4)); assertEquals(8, mArray.getBucketedSize(5)); assertEquals(8, mArray.getBucketedSize(6)); assertEquals(8, mArray.getBucketedSize(7)); assertEquals(8, mArray.getBucketedSize(8)); assertEquals(16, mArray.getBucketedSize(9)); } }