code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# Digitaria adscendens var. rhachiseta VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Digitaria/Digitaria nuda/ Syn. Digitaria adscendens rhachiseta/README.md
Markdown
apache-2.0
193
# Lepanthopsis michelii Dod SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Lepanthopsis/Lepanthopsis michelii/README.md
Markdown
apache-2.0
175
# Pinus strobiformis var. carvajalii Silba VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Pinophyta/Pinopsida/Pinales/Pinaceae/Pinus/Pinus strobiformis/ Syn. Pinus strobiformis carvajalii/README.md
Markdown
apache-2.0
197
# Alseodaphne suboppositifolia Kosterm. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Laurales/Lauraceae/Alseodaphne/Alseodaphne suboppositifolia/README.md
Markdown
apache-2.0
187
package com.bootcamp.topic0.builder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConexionBD { private String host; private String user; private String pass; private String dbname; private String dbmotor; private Connection con; public Connection getConexion(){ try { con = DriverManager.getConnection("jdbc:"+ dbmotor+"://" + host + "/" + dbname, user, pass); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } public void releaseConexion(){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getDbname() { return dbname; } public void setDbname(String dbname) { this.dbname = dbname; } public String getDbmotor() { return dbmotor; } public void setDbmotor(String dbmotor) { this.dbmotor = dbmotor; } }
rami51/java-bootcamp-2016
Topics/Topic_0/src/com/bootcamp/topic0/builder/ConexionBD.java
Java
apache-2.0
1,265
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::OR { #[doc = r" Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct RMPR { bits: u8, } impl RMPR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Proxy"] pub struct _RMPW<'a> { w: &'a mut W, } impl<'a> _RMPW<'a> { #[doc = r" Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:1 - Timer input 1 remap"] #[inline(always)] pub fn rmp(&self) -> RMPR { let bits = { const MASK: u8 = 3; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; RMPR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline(always)] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:1 - Timer input 1 remap"] #[inline(always)] pub fn rmp(&mut self) -> _RMPW { _RMPW { w: self } } }
pollen/stm32f0
stm32f0x2/src/tim14/or/mod.rs
Rust
apache-2.0
2,554
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { public GameObject Player; public GameObject TheCamera; void Start () { Player = Resources.Load <GameObject>("Prefabs/PlayerPrefabs/Serenity"); GameObject PlayerClone = (GameObject) Instantiate (Player); TheCamera = (GameObject)Instantiate(Resources.Load<GameObject>("Prefabs/MainCamera")); TheCamera.GetComponent<MainCamera>().target = PlayerClone.transform; } void Update () { } }
MAVG-Programmers/Navis-Public
Assets/Scripts/GameController.cs
C#
apache-2.0
529
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_20) on Wed Feb 16 05:11:23 PST 2011 --> <TITLE> org.apache.pig.tools.pigstats (Pig 0.8.0-CDH3B4-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2011-02-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.pig.tools.pigstats (Pig 0.8.0-CDH3B4-SNAPSHOT API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/pig/tools/parameters/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/pig/tools/streams/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/pig/tools/pigstats/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package org.apache.pig.tools.pigstats </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/PigProgressNotificationListener.html" title="interface in org.apache.pig.tools.pigstats">PigProgressNotificationListener</A></B></TD> <TD>Should be implemented by an object that wants to receive notifications from <A HREF="../../../../../org/apache/pig/PigRunner.html" title="class in org.apache.pig"><CODE>PigRunner</CODE></A>.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/InputStats.html" title="class in org.apache.pig.tools.pigstats">InputStats</A></B></TD> <TD>This class encapsulates the runtime statistics of a user specified input.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/JobStats.html" title="class in org.apache.pig.tools.pigstats">JobStats</A></B></TD> <TD>This class encapsulates the runtime statistics of a MapReduce job.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/OutputStats.html" title="class in org.apache.pig.tools.pigstats">OutputStats</A></B></TD> <TD>This class encapsulates the runtime statistics of an user specified output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/PigStats.html" title="class in org.apache.pig.tools.pigstats">PigStats</A></B></TD> <TD>PigStats encapsulates the statistics collected from a running script.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/PigStats.JobGraph.html" title="class in org.apache.pig.tools.pigstats">PigStats.JobGraph</A></B></TD> <TD>JobGraph is an <A HREF="../../../../../org/apache/pig/newplan/OperatorPlan.html" title="interface in org.apache.pig.newplan"><CODE>OperatorPlan</CODE></A> whose members are <A HREF="../../../../../org/apache/pig/tools/pigstats/JobStats.html" title="class in org.apache.pig.tools.pigstats"><CODE>JobStats</CODE></A></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/PigStatsUtil.html" title="class in org.apache.pig.tools.pigstats">PigStatsUtil</A></B></TD> <TD>A utility class for Pig Statistics</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/PigStatusReporter.html" title="class in org.apache.pig.tools.pigstats">PigStatusReporter</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/ScriptState.html" title="class in org.apache.pig.tools.pigstats">ScriptState</A></B></TD> <TD>ScriptStates encapsulates settings for a Pig script that runs on a hadoop cluster.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/ScriptState.LogicalPlanFeatureVisitor.html" title="class in org.apache.pig.tools.pigstats">ScriptState.LogicalPlanFeatureVisitor</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Enum Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/InputStats.INPUT_TYPE.html" title="enum in org.apache.pig.tools.pigstats">InputStats.INPUT_TYPE</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/pig/tools/pigstats/JobStats.JobState.html" title="enum in org.apache.pig.tools.pigstats">JobStats.JobState</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/pig/tools/parameters/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/pig/tools/streams/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/pig/tools/pigstats/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; ${year} The Apache Software Foundation </BODY> </HTML>
simplegeo/hadoop-pig
docs/api/org/apache/pig/tools/pigstats/package-summary.html
HTML
apache-2.0
10,434
# Copyright 2014 Rackspace # # 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. from gbpservice.nfp.configurator.drivers.loadbalancer.v2.haproxy.octavia_lib.\ common import data_models class Interface(data_models.BaseDataModel): def __init__(self, id=None, compute_id=None, network_id=None, fixed_ips=None, port_id=None): self.id = id self.compute_id = compute_id self.network_id = network_id self.port_id = port_id self.fixed_ips = fixed_ips class Delta(data_models.BaseDataModel): def __init__(self, amphora_id=None, compute_id=None, add_nics=None, delete_nics=None): self.compute_id = compute_id self.amphora_id = amphora_id self.add_nics = add_nics self.delete_nics = delete_nics class Network(data_models.BaseDataModel): def __init__(self, id=None, name=None, subnets=None, project_id=None, admin_state_up=None, mtu=None, provider_network_type=None, provider_physical_network=None, provider_segmentation_id=None, router_external=None): self.id = id self.name = name self.subnets = subnets self.project_id = project_id self.admin_state_up = admin_state_up self.provider_network_type = provider_network_type self.provider_physical_network = provider_physical_network self.provider_segmentation_id = provider_segmentation_id self.router_external = router_external self.mtu = mtu class Subnet(data_models.BaseDataModel): def __init__(self, id=None, name=None, network_id=None, project_id=None, gateway_ip=None, cidr=None, ip_version=None): self.id = id self.name = name self.network_id = network_id self.project_id = project_id self.gateway_ip = gateway_ip self.cidr = cidr self.ip_version = ip_version class Port(data_models.BaseDataModel): def __init__(self, id=None, name=None, device_id=None, device_owner=None, mac_address=None, network_id=None, status=None, project_id=None, admin_state_up=None, fixed_ips=None, network=None): self.id = id self.name = name self.device_id = device_id self.device_owner = device_owner self.mac_address = mac_address self.network_id = network_id self.status = status self.project_id = project_id self.admin_state_up = admin_state_up self.fixed_ips = fixed_ips or [] self.network = network def get_subnet_id(self, fixed_ip_address): for fixed_ip in self.fixed_ips: if fixed_ip.ip_address == fixed_ip_address: return fixed_ip.subnet_id class FixedIP(data_models.BaseDataModel): def __init__(self, subnet_id=None, ip_address=None, subnet=None): self.subnet_id = subnet_id self.ip_address = ip_address self.subnet = subnet class AmphoraNetworkConfig(data_models.BaseDataModel): def __init__(self, amphora=None, vip_subnet=None, vip_port=None, vrrp_subnet=None, vrrp_port=None, ha_subnet=None, ha_port=None): self.amphora = amphora self.vip_subnet = vip_subnet self.vip_port = vip_port self.vrrp_subnet = vrrp_subnet self.vrrp_port = vrrp_port self.ha_subnet = ha_subnet self.ha_port = ha_port
jiahaoliang/group-based-policy
gbpservice/nfp/configurator/drivers/loadbalancer/v2/haproxy/octavia_lib/network/data_models.py
Python
apache-2.0
4,043
import angular from 'angular'; import gameboardComponent from './gameboard.component'; import Game from '../../common/game/game'; let gameboardModule = angular.module('gameboard', [ Game ]) .component('gameboard', gameboardComponent) .name; export default gameboardModule;
zbicin/word-game
client/app/components/gameboard/gameboard.js
JavaScript
apache-2.0
283
# Command to invoke > docker-compose run dockermon or create an alias like > alias mon="docker-compose -f /home/gianluca/Apps/docker-composer/docker-mon/docker-compose.yml run dockermon"
gi4nks/docker-composer
docker-mon/README.md
Markdown
apache-2.0
192
package collector import ( "fullerite/metric" "testing" l "github.com/Sirupsen/logrus" "github.com/stretchr/testify/assert" ) func TestNewProcNetUDPStats(t *testing.T) { c := make(chan metric.Metric) i := 10 l := defaultLog.WithFields(l.Fields{"collector": "Mesos"}) actual := newProcNetUDPStats(c, i, l).(*procNetUDPStats) assert.Equal(t, "ProcNetUDPStats", actual.Name()) assert.Equal(t, c, actual.Channel()) assert.Equal(t, i, actual.Interval()) assert.Equal(t, l, actual.log) } func TestProcNetUDPStatsConfigureMissingRemote(t *testing.T) { l := defaultLog.WithFields(l.Fields{"collector": "ProcNetUDPStats"}) fakeCollector := newProcNetUDPStats(nil, 0, l).(*procNetUDPStats) fakeCollector.Configure(map[string]interface{}{ "localAddressWhitelist": "7F000001:613", }) assert.NotNil(t, fakeCollector.localAddressWhitelist) assert.Nil(t, fakeCollector.remoteAddressWhitelist) } func TestProcNetUDPStatsConfigureMissingLocal(t *testing.T) { l := defaultLog.WithFields(l.Fields{"collector": "ProcNetUDPStats"}) fakeCollector := newProcNetUDPStats(nil, 0, l).(*procNetUDPStats) fakeCollector.Configure(map[string]interface{}{ "remoteAddressWhitelist": "7F000001:613", }) assert.Nil(t, fakeCollector.localAddressWhitelist) assert.NotNil(t, fakeCollector.remoteAddressWhitelist) } func TestProcNetUDPStatsConfigure(t *testing.T) { l := defaultLog.WithFields(l.Fields{"collector": "ProcNetUDPStats"}) fakeCollector := newProcNetUDPStats(nil, 0, l).(*procNetUDPStats) fakeCollector.Configure(map[string]interface{}{ "localAddressWhitelist": "7F000001:613", "remoteAddressWhitelist": "7F000001:613", }) assert.NotNil(t, fakeCollector.localAddressWhitelist) assert.NotNil(t, fakeCollector.remoteAddressWhitelist) } func TestParse(t *testing.T) { out := `sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode ref pointer drops 3152: FEFFFEA9:4ED6 00000000:0000 07 00000000:00000000 00:00000000 00000000 65534 0 3841266873 2 ffff88021734b480 0 15747: FEFFFEA9:8009 FEFFFEA9:1FBD 01 00000000:00000000 00:00000000 00000000 4404 0 1989081677 2 ffff8806859712c0 100` fakeCollector := &procNetUDPStats{} lines := fakeCollector.parseProcNetUDPLines(out) assert.Equal(t, 2, len(lines)) assert.Equal(t, "FEFFFEA9:4ED6", lines[0].localAddress) assert.Equal(t, "00000000:0000", lines[0].remoteAddress) assert.Equal(t, "0", lines[0].drops) assert.Equal(t, "FEFFFEA9:8009", lines[1].localAddress) assert.Equal(t, "FEFFFEA9:1FBD", lines[1].remoteAddress) assert.Equal(t, "100", lines[1].drops) }
baris/fullerite
src/fullerite/collector/net_udp_test.go
GO
apache-2.0
2,597
/* * @license * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Constants are installed on both the prototype and class. <pre> Ex. constants: { KEY: 'some value' } this.cls_.KEY === this.KEY === 'some value' </pre> */ foam.CLASS({ package: 'foam.core', name: 'Constant', // documentation: 'Constant Axiom', properties: [ 'name', 'value' ], methods: [ function installInClass(cls) { Object.defineProperty( cls, foam.String.constantize(this.name), { value: this.value, configurable: false }); }, function installInProto(proto) { this.installInClass(proto); } ] }); foam.CLASS({ refines: 'foam.core.Model', properties: [ { class: 'AxiomArray', of: 'Constant', name: 'constants', adapt: function(_, a, prop) { if ( ! a ) return []; if ( ! Array.isArray(a) ) { var cs = []; for ( var key in a ) { cs.push(foam.core.Constant.create({name: key, value: a[key]})); } return cs; } var b = new Array(a.length); for ( var i = 0 ; i < a.length ; i++ ) { b[i] = prop.adaptArrayElement.call(this, a[i], prop); } return b; } } ] });
jacksonic/foamTableTop
bower_components/foam2-experimental/src/core/Constant.js
JavaScript
apache-2.0
1,859
#include "generator/translator.hpp" #include "generator/collector_interface.hpp" #include "generator/emitter_interface.hpp" #include "generator/intermediate_data.hpp" #include "generator/osm_element.hpp" #include "base/assert.hpp" using namespace feature; namespace generator { Translator::Translator(std::shared_ptr<EmitterInterface> emitter, cache::IntermediateDataReader & cache, std::shared_ptr<FeatureMakerBase> maker, FilterCollection const & filters, CollectorCollection const & collectors) : m_filters(filters) , m_collectors(collectors) , m_tagsEnricher(cache) , m_featureMaker(maker) , m_emitter(emitter) , m_cache(cache) { CHECK(m_emitter, ()); } Translator::Translator(std::shared_ptr<EmitterInterface> emitter, cache::IntermediateDataReader & cache, std::shared_ptr<FeatureMakerBase> maker) : Translator(emitter, cache, maker, {} /* filters */, {} /* collectors */) {} void Translator::Emit(OsmElement & element) { if (!m_filters.IsAccepted(element)) return; Preprocess(element); m_tagsEnricher(element); m_collectors.Collect(element); m_featureMaker->Add(element); FeatureBuilder feature; while (m_featureMaker->GetNextFeature(feature)) { if (!m_filters.IsAccepted(feature)) continue; m_collectors.CollectFeature(feature, element); m_emitter->Process(feature); } } bool Translator::Finish() { m_collectors.Save(); return m_emitter->Finish(); } void Translator::GetNames(std::vector<std::string> & names) const { m_emitter->GetNames(names); } void Translator::AddCollector(std::shared_ptr<CollectorInterface> collector) { m_collectors.Append(collector); } void Translator::AddFilter(std::shared_ptr<FilterInterface> filter) { m_filters.Append(filter); } } // namespace generator
VladiMihaylenko/omim
generator/translator.cpp
C++
apache-2.0
1,840
package it.unibz.inf.ontop.iq.node; /** * Union of CommutativeJoinNode and FilterNode */ public interface CommutativeJoinOrFilterNode extends JoinOrFilterNode { }
ontop/ontop
core/model/src/main/java/it/unibz/inf/ontop/iq/node/CommutativeJoinOrFilterNode.java
Java
apache-2.0
167
#!/bin/bash # # honggfuzz libunwind build help script # ----------------------------------------- # # 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. set -xeu abort() { cd - &>/dev/null exit "$1" } trap "abort 1" SIGINT SIGTERM if [ $# -ne 2 ]; then echo "[-] Invalid arguments" echo "[!] $0 <LIBUNWIND_DIR> <ARCH>" echo " ARCH: arm arm64 x86 x86_64" exit 1 fi readonly LIBUNWIND_DIR="$1" if [ ! -d "$LIBUNWIND_DIR/.git" ]; then git submodule update --init third_party/android/libunwind fi # Change workspace cd "$LIBUNWIND_DIR" &>/dev/null if [[ $(which ndk-build) != "" ]]; then NDK=$(dirname $(which ndk-build)) else echo "[-] Could not detect Android NDK dir" abort 1 fi if ! echo "$ANDROID_API" | grep -qoE 'android-[0-9]{1,2}'; then echo "[-] Invalid ANDROID_API '$ANDROID_API'" abort 1 fi ANDROID_API_V=$(echo "$ANDROID_API" | grep -oE '[0-9]{1,2}$') LC_LDFLAGS="-static" ARCH="$2" # Prepare toolchain case "$ARCH" in arm) TOOLCHAIN=arm-linux-androideabi ;; arm64) TOOLCHAIN=aarch64-linux-android ;; x86) TOOLCHAIN=i686-linux-android ;; x86_64) TOOLCHAIN=x86_64-linux-android ;; esac # Support both Linux & Darwin HOST_OS=$(uname -s | tr '[:upper:]' '[:lower:]') HOST_ARCH=$(uname -m) export CC="$NDK"/toolchains/llvm/prebuilt/"$HOST_OS"-x86_64/bin/"$ANDROID_NDK_COMPILER_PREFIX""$ANDROID_API_V"-clang export CXX="$NDK"/toolchains/llvm/prebuilt/"$HOST_OS"-x86_64/bin/"$ANDROID_NDK_COMPILER_PREFIX""$ANDROID_API_V"-clang++ if [ ! -x "$CC" ]; then echo "[-] clang doesn't exist: $CC" abort 1 elif [ ! -x "$CXX" ]; then echo "[-] clang++ doesn't exist: $CXX" abort 1 fi if [ ! -f configure ]; then autoreconf -i else make clean fi ./configure "--host=$TOOLCHAIN" --disable-coredump --enable-static --disable-shared --disable-tests --enable-ptrace make -j LDFLAGS="$LC_LDFLAGS" # Naming conventions for arm64 if [[ "$ARCH" == "arm64" ]]; then find . -type f -name "*aarch64*.a" | while read -r libFile do dir=$(dirname "$libFile") pushd $dir fName=$(basename "$libFile") newFName=$(echo "$fName" | sed "s#aarch64#arm64#") ln -sf "$fName" "$newFName" popd done fi abort 0
google/honggfuzz
third_party/android/scripts/compile-libunwind.sh
Shell
apache-2.0
2,716
from django.shortcuts import render from django.http import HttpResponse from django.utils import simplejson as json import ner def index(request): params = {'current': 'home'} return render(request, 'index.html', params) def name_entity_recognition(request): if request.method == 'GET': #Get the array that contains the list of texts to recognize input_text_array = request.GET.getlist('text[]') data = {} i=0 for text in input_text_array: #Recognize all strings / texts contained in the array data[i] = ner.recognize(text.strip()) i+=1 return HttpResponse(json.dumps(data), content_type = "application/json")
smouzakitis/molly
molly/views.py
Python
apache-2.0
711
import { isInteger } from "../utils/native"; const ASCENDING = (a, b) => a - b; const DESCENDING = (a, b) => b - a; const isInRange = (value, start, end) => value >= start && value <= end; const isValidIndex = function (keys, start, end) { return function (key) { return !(key in keys) && isInteger(key) && isInRange(key, start, end); }; }; export default function SparseIterator (obj, start, end, desc) { this.object = obj; this.start = start; this.end = end; this.asc = !desc; this.version = 0; } SparseIterator.prototype = { constructor: SparseIterator, [Symbol.iterator] () { return this; }, reset () { this.version = 0; this.prototypes = []; this.props = Object.create(null); this.keys = []; let current = this.object; while (current) { this.prototypes.push(current); this.version += current.version; current.getOwnPropertyKeys("String") .filter(isValidIndex(this.props, this.start, this.end)) .forEach(key => { // wrap in function - avoid calling until iteration this.props[key] = current.getValue.bind(current, key); this.keys.push(Number(key)); }); current = current.getPrototype(); } this.keys.sort(this.asc ? ASCENDING : DESCENDING); }, next () { if (!this.version || this.shouldReset()) { this.reset(); } if (this.keys.length > 0) { let key = this.currentIndex = this.keys.shift(); let value = this.props[key](); return { value: { key, value }, done: false }; } return { done: true }; }, shouldReset () { let currentVersion = this.prototypes.reduce((v, o) => o.version + v, 0); if (currentVersion !== this.version) { if (this.asc) { this.start = this.currentIndex + 1; } else { this.end = this.currentIndex - 1; } return true; } return false; }, }; SparseIterator.create = function (arr, start, end, desc) { return new SparseIterator(arr, start, end, desc); };
jrsearles/SandBoxr
src/iterators/sparse-iterator.js
JavaScript
apache-2.0
2,091
# Copyright 2017 Google 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. import os import shutil import tempfile import pytest import redact GCLOUD_PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT") RESOURCE_DIRECTORY = os.path.join(os.path.dirname(__file__), "resources") @pytest.fixture(scope="module") def tempdir(): tempdir = tempfile.mkdtemp() yield tempdir shutil.rmtree(tempdir) def test_redact_image_file(tempdir, capsys): test_filepath = os.path.join(RESOURCE_DIRECTORY, "test.png") output_filepath = os.path.join(tempdir, "redacted.png") redact.redact_image( GCLOUD_PROJECT, test_filepath, output_filepath, ["FIRST_NAME", "EMAIL_ADDRESS"], ) out, _ = capsys.readouterr() assert output_filepath in out def test_redact_image_all_text(tempdir, capsys): test_filepath = os.path.join(RESOURCE_DIRECTORY, "test.png") output_filepath = os.path.join(tempdir, "redacted.png") redact.redact_image_all_text( GCLOUD_PROJECT, test_filepath, output_filepath, ) out, _ = capsys.readouterr() assert output_filepath in out
googleapis/python-dlp
samples/snippets/redact_test.py
Python
apache-2.0
1,601
<?php error_reporting(-1); require './luhn-creator.php'; define('PAYSTACK_SECRET_KEY', 'sk_test_xxx'); function getIp() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } function getUnusedCode() { // to generate our random string code $newcode = createLuhnCheckedRandomString(10); // while the new string exists, get a new code while (file_exists('results/' . $newcode . '-response.json')) { $newcode = createLuhnCheckedRandomString(10); } return $newcode; } class VirtualDirectory { var $protocol; var $site; var $thisfile; var $real_directories; var $num_of_real_directories; var $virtual_directories = array(); var $num_of_virtual_directories = array(); var $baseURL; var $thisURL; function __construct() { $this->protocol = (array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http'; $this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST']; $this->thisfile = basename($_SERVER['SCRIPT_FILENAME']); $this->real_directories = $this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['PHP_SELF']))); $this->num_of_real_directories = count($this->real_directories); $this->virtual_directories = array_diff($this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['REQUEST_URI']))),$this->real_directories); $this->num_of_virtual_directories = count($this->virtual_directories); $this->baseURL = $this->site . "/" . implode("/", $this->real_directories) . "/"; $this->thisURL = $this->baseURL . implode("/", $this->virtual_directories) . "/"; } function cleanUp($array) { $cleaned_array = array(); foreach($array as $key => $value) { $qpos = strpos($value, "?"); if($qpos !== false) { break; } if($key != "" && $value != "") { $cleaned_array[] = $value; } } return $cleaned_array; } }
ibrahimlawal/paystack-php-sample
donate/functions.php
PHP
apache-2.0
2,286
/* * Copyright 2017 Martin Kouba * * 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 com.githhub.mkouba.cdibee; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.enterprise.util.AnnotationLiteral; import javax.inject.Qualifier; /** * Qualifier used to distinguish hello message events. * * @author Martin Kouba * @see EventHelloService */ @Qualifier @Target({ TYPE, METHOD, PARAMETER, FIELD }) @Retention(RUNTIME) public @interface HelloMessage { @SuppressWarnings("all") public static class Literal extends AnnotationLiteral<HelloMessage> implements HelloMessage { public static final Literal INSTANCE = new Literal(); } }
mkouba/cdi-beyond-ee
src/main/java/com/githhub/mkouba/cdibee/HelloMessage.java
Java
apache-2.0
1,489
<th:block xmlns:th="http://www.thymeleaf.org"> <!--/*@thymesVar id="results" type="org.strangeforest.tcb.stats.model.TournamentEventResults"*/--> <div th:unless="${results.isEmpty()}" th:include="fragments/eventResults :: eventResults('', -1, true, false)"></div> <th:block th:if="${results.isEmpty()}"> <br/> <div class="alert alert-warning">No results found</div> </th:block> </th:block>
mcekovic/tennis-crystal-ball
tennis-stats/src/main/resources/templates/inProgressEventResults.html
HTML
apache-2.0
397
/*! * Bootstrap-Showcase v1.0 * * Copyright 2013-2014 www.abuabdul.com */ body { background: #eeeeee; /* background: #efefff; */ padding-top: 4px; padding-bottom: 4px; } /* Custom container */ .container-narrow { background: #ffffff; margin: 0 auto; max-width: 1000px; padding: 10px; -webkit-border-radius: 7px; -moz-border-radius: 7px; border-radius: 7px; } .container-narrow>hr { margin: 30px 25; } .jumbotron { margin: 10px 0; text-align: left; padding: 15px; margin-bottom: 15px; font-size: 18px; font-weight: 100; line-height: 20px; background-color: #eeeeee; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } .jumbotron h1 { font-size: 18px; line-height: 1; color: #d14; /* color: #b94a48; */ /* color: #3a87ad; */ /* color: #2d6987; */ } .jumbotron p { font-size: 15px; font-weight: 100; line-height: 1.35; } .jumbotron .btn { font-size: 18px; padding: 14px 24px; } .showcase { margin: 20px 0; } .showcase p+h4 { margin-top: 28px; } .tab-content p{ padding: 2px; font-size: 16px; } div .popover-content { color: #d14; } input[type="radio"], input[type="checkbox"]{ margin: 5px; } .carousel-indicators li { background-color: #000; background-color: rgba(0, 0, 0, 0.25); } .carousel-indicators .active { background-color: #005580; } .redHead{ color: #d14; } .text-justify{ text-align: justify; } .sleek-style{ font-style:italic; } .blackBG{ background-color: #000; }
abuabdul/bootstrap-showcase
src/main/webapp/css/bootstrap-showcase.css
CSS
apache-2.0
1,475
/** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {SCHEDULER_PRIORITIES} from './scheduler-priorities.js'; /** * This class manages scheduling and running callbacks using postMessage. * @private */ class PostMessageCallbackMananger { /** * Construct a PostMessageCallbackMananger, which handles scheduling * and running callbacks via a MessageChannel. */ constructor() { /** * @private * @const {!MessageChannel} */ this.channel_ = new MessageChannel(); /** * @private * @const {MessagePort} */ this.sendPort_ = this.channel_.port2; /** * @private * @const {!Object<number, function(): undefined>} */ this.messages_ = {}; /** * @private * @type {number} */ this.nextMessageHandle_ = 1; this.channel_.port1.onmessage = (e) => this.onMessageReceived_(e); } /** * @param {function(): undefined} callback * @return {number} A handle that can used for cancellation. */ queueCallback(callback) { // We support multiple pending postMessage callbacks by associating a handle // with each message, which is used to look up the callback when the message // is received. const handle = this.nextMessageHandle_++; this.messages_[handle] = callback; this.sendPort_.postMessage(handle); return handle; } /** * @param {number} handle The handle returned when the callback was queued. */ cancelCallback(handle) { delete this.messages_[handle]; } /** * The onmessage handler, invoked when the postMessage runs. * @private * @param {!Event} e */ onMessageReceived_(e) { const handle = e.data; // The handle will have been removed if the callback was canceled. if (!(handle in this.messages_)) return; const callback = this.messages_[handle]; delete this.messages_[handle]; callback(); } } /** * Get the lazily initialized instance of PostMessageCallbackMananger, which * is initialized that way to avoid errors if MessageChannel is not available. * * @return {!PostMessageCallbackMananger} */ function getPostMessageCallbackManager() { if (!getPostMessageCallbackManager.instance_) { getPostMessageCallbackManager.instance_ = new PostMessageCallbackMananger(); } return getPostMessageCallbackManager.instance_; } /** @enum {number} */ const CallbackType = { REQUEST_IDLE_CALLBACK: 0, SET_TIMEOUT: 1, POST_MESSAGE: 2, }; /** * HostCallback is used for tracking host callbacks, both for the schedueler * entrypoint --- which can be a postMessage, setTimeout, or * requestIdleCallback --- and for delayed tasks. */ class HostCallback { /** * @param {function(): undefined} callback * @param {?string} priority The scheduler priority of the associated host * callback. This is used to determine which type of underlying API to * use. This can be null if delay is set. * @param {number} delay An optional delay. Tasks with a delay will * ignore the `priority` parameter and use setTimeout. */ constructor(callback, priority, delay = 0) { /** @const {function(): undefined} */ this.callback_ = callback; /** * @private * @type {CallbackType} */ this.callbackType_ = null; /** * Handle for cancellation, which is set when the callback is scheduled. * @private * @type {?number} */ this.handle_ = null; /** * @private * @type {boolean} */ this.canceled_ = false; this.schedule_(priority, delay); } /** * Returns true iff this task was scheduled with requestIdleCallback. * @return {boolean} */ isIdleCallback() { return this.callbackType_ === CallbackType.REQUEST_IDLE_CALLBACK; } /** * Cancel the host callback, and if possible, cancel the underlying API call. */ cancel() { if (this.canceled_) return; this.canceled_ = true; switch (this.callbackType_) { case CallbackType.REQUEST_IDLE_CALLBACK: cancelIdleCallback(this.handle_); break; case CallbackType.SET_TIMEOUT: clearTimeout(this.handle_); break; case CallbackType.POST_MESSAGE: getPostMessageCallbackManager().cancelCallback(this.handle_); break; default: throw new TypeError('Unknown CallbackType'); } } /** * @private * @param {?string} priority The scheduler priority of the associated host * callback. This is used to determine which type of underlying API to * use. This can be null if delay is set. * @param {number} delay An optional delay. Tasks with a delay will * ignore the `priority` parameter and use setTimeout. */ schedule_(priority, delay) { // For the delay case, our only option is setTimeout. This gets queued at // the appropriate priority when the callback runs. If the delay <= 0 and // MessageChannel is available, we use postMessage below. if ((delay && delay > 0) || typeof MessageChannel !== 'function') { if (!delay) delay = 0; this.callbackType_ = CallbackType.SET_TIMEOUT; this.handle_ = setTimeout(() => { this.runCallback_(); }, delay); return; } // This shouldn't happen since Scheduler checks the priority before creating // a HostCallback, but fail loudly in case it does. if (!SCHEDULER_PRIORITIES.includes(priority)) { throw new TypeError(`Invalid task priority : ${priority}`); } if (priority === 'background' && typeof requestIdleCallback === 'function') { this.handle_ = requestIdleCallback(() => { this.runCallback_(); }); this.callbackType_ = CallbackType.REQUEST_IDLE_CALLBACK; } else { // TODO: Consider using setTimeout in the background so tasks are // throttled. One caveat here is that requestIdleCallback may not be // throttled. this.handle_ = getPostMessageCallbackManager().queueCallback(() => { this.runCallback_(); }); this.callbackType_ = CallbackType.POST_MESSAGE; } } /** Run the associated callback. */ runCallback_() { if (this.canceled_) return; this.callback_(); } } export {HostCallback};
GoogleChromeLabs/scheduler-polyfill
src/host-callback.js
JavaScript
apache-2.0
6,775
package com.dyz.myBatis.services; import org.apache.ibatis.session.SqlSessionFactory; import com.dyz.myBatis.dao.GameRecordMapper; import com.dyz.myBatis.daoImp.GameRecordDaoImp; public class GameRecordService { private GameRecordMapper gameRecordMap; private static GameRecordService gameService = new GameRecordService(); public static GameRecordService getInstance(){ return gameService; } public void initSetSession(SqlSessionFactory sqlSessionFactory){ gameRecordMap = new GameRecordDaoImp(sqlSessionFactory); } }
XihuLai/GS
src/com/dyz/myBatis/services/GameRecordService.java
Java
apache-2.0
582
# Ugly Number II ## Problem: <div class="question-content"> <p> </p> <p> Write a program to find the <code> n </code> -th ugly number. </p> <p> Ugly numbers are positive numbers whose prime factors only include <code> 2, 3, 5 </code> . For example, <code> 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 </code> is the sequence of the first <code> 10 </code> ugly numbers. </p> <p> Note that <code> 1 </code> is typically treated as an ugly number. </p> <ol id="hints"> <li class="hint"> The naive approach is to call <code> isUgly </code> for every number until you reach the n <sup> th </sup> one. Most numbers are <i> not </i> ugly. Try to focus your effort on generating only the ugly ones. </li> <li class="hint"> An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. </li> <li class="hint"> The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L <sub> 1 </sub> , L <sub> 2 </sub> , and L <sub> 3 </sub> . </li> <li class="hint"> Assume you have U <sub> k </sub> , the k <sup> th </sup> ugly number. Then U <sub> k+1 </sub> must be Min(L <sub> 1 </sub> * 2, L <sub> 2 </sub> * 3, L <sub> 3 </sub> * 5). </li> </ol> <p> <b> Credits: </b> <br/> Special thanks to <a href="https://leetcode.com/discuss/user/jianchao.li.fighter"> @jianchao.li.fighter </a> for adding this problem and creating all test cases. </p> </div> ## Source: [Leetcode](https://leetcode.com/problems/ugly-number-ii/)
Dragon-lake/leetcode
Java/264_Ugly_Number_II/README.md
Markdown
apache-2.0
1,740
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/bigtable/admin/v2/bigtable_table_admin.proto #include "google/cloud/bigtable/admin/internal/bigtable_table_admin_auth_decorator.h" #include <google/bigtable/admin/v2/bigtable_table_admin.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace bigtable_admin_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN BigtableTableAdminAuth::BigtableTableAdminAuth( std::shared_ptr<google::cloud::internal::GrpcAuthenticationStrategy> auth, std::shared_ptr<BigtableTableAdminStub> child) : auth_(std::move(auth)), child_(std::move(child)) {} StatusOr<google::bigtable::admin::v2::Table> BigtableTableAdminAuth::CreateTable( grpc::ClientContext& context, google::bigtable::admin::v2::CreateTableRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->CreateTable(context, request); } StatusOr<google::bigtable::admin::v2::ListTablesResponse> BigtableTableAdminAuth::ListTables( grpc::ClientContext& context, google::bigtable::admin::v2::ListTablesRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ListTables(context, request); } StatusOr<google::bigtable::admin::v2::Table> BigtableTableAdminAuth::GetTable( grpc::ClientContext& context, google::bigtable::admin::v2::GetTableRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetTable(context, request); } Status BigtableTableAdminAuth::DeleteTable( grpc::ClientContext& context, google::bigtable::admin::v2::DeleteTableRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->DeleteTable(context, request); } StatusOr<google::bigtable::admin::v2::Table> BigtableTableAdminAuth::ModifyColumnFamilies( grpc::ClientContext& context, google::bigtable::admin::v2::ModifyColumnFamiliesRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ModifyColumnFamilies(context, request); } Status BigtableTableAdminAuth::DropRowRange( grpc::ClientContext& context, google::bigtable::admin::v2::DropRowRangeRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->DropRowRange(context, request); } StatusOr<google::bigtable::admin::v2::GenerateConsistencyTokenResponse> BigtableTableAdminAuth::GenerateConsistencyToken( grpc::ClientContext& context, google::bigtable::admin::v2::GenerateConsistencyTokenRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GenerateConsistencyToken(context, request); } StatusOr<google::bigtable::admin::v2::CheckConsistencyResponse> BigtableTableAdminAuth::CheckConsistency( grpc::ClientContext& context, google::bigtable::admin::v2::CheckConsistencyRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->CheckConsistency(context, request); } future<StatusOr<google::longrunning::Operation>> BigtableTableAdminAuth::AsyncCreateBackup( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::bigtable::admin::v2::CreateBackupRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::unique_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncCreateBackup(cq, *std::move(context), request); }); } StatusOr<google::bigtable::admin::v2::Backup> BigtableTableAdminAuth::GetBackup( grpc::ClientContext& context, google::bigtable::admin::v2::GetBackupRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetBackup(context, request); } StatusOr<google::bigtable::admin::v2::Backup> BigtableTableAdminAuth::UpdateBackup( grpc::ClientContext& context, google::bigtable::admin::v2::UpdateBackupRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->UpdateBackup(context, request); } Status BigtableTableAdminAuth::DeleteBackup( grpc::ClientContext& context, google::bigtable::admin::v2::DeleteBackupRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->DeleteBackup(context, request); } StatusOr<google::bigtable::admin::v2::ListBackupsResponse> BigtableTableAdminAuth::ListBackups( grpc::ClientContext& context, google::bigtable::admin::v2::ListBackupsRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->ListBackups(context, request); } future<StatusOr<google::longrunning::Operation>> BigtableTableAdminAuth::AsyncRestoreTable( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::bigtable::admin::v2::RestoreTableRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::unique_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncRestoreTable(cq, *std::move(context), request); }); } StatusOr<google::iam::v1::Policy> BigtableTableAdminAuth::GetIamPolicy( grpc::ClientContext& context, google::iam::v1::GetIamPolicyRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->GetIamPolicy(context, request); } StatusOr<google::iam::v1::Policy> BigtableTableAdminAuth::SetIamPolicy( grpc::ClientContext& context, google::iam::v1::SetIamPolicyRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->SetIamPolicy(context, request); } StatusOr<google::iam::v1::TestIamPermissionsResponse> BigtableTableAdminAuth::TestIamPermissions( grpc::ClientContext& context, google::iam::v1::TestIamPermissionsRequest const& request) { auto status = auth_->ConfigureContext(context); if (!status.ok()) return status; return child_->TestIamPermissions(context, request); } future<StatusOr<google::bigtable::admin::v2::CheckConsistencyResponse>> BigtableTableAdminAuth::AsyncCheckConsistency( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::bigtable::admin::v2::CheckConsistencyRequest const& request) { using ReturnType = StatusOr<google::bigtable::admin::v2::CheckConsistencyResponse>; auto child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::unique_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncCheckConsistency(cq, *std::move(context), request); }); } future<StatusOr<google::longrunning::Operation>> BigtableTableAdminAuth::AsyncGetOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { using ReturnType = StatusOr<google::longrunning::Operation>; auto child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::unique_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) { return make_ready_future(ReturnType(std::move(context).status())); } return child->AsyncGetOperation(cq, *std::move(context), request); }); } future<Status> BigtableTableAdminAuth::AsyncCancelOperation( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { auto child = child_; return auth_->AsyncConfigureContext(std::move(context)) .then([cq, child, request](future<StatusOr<std::unique_ptr<grpc::ClientContext>>> f) mutable { auto context = f.get(); if (!context) return make_ready_future(std::move(context).status()); return child->AsyncCancelOperation(cq, *std::move(context), request); }); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace bigtable_admin_internal } // namespace cloud } // namespace google
googleapis/google-cloud-cpp
google/cloud/bigtable/admin/internal/bigtable_table_admin_auth_decorator.cc
C++
apache-2.0
10,008
/* * 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.ignite.internal.portable; import org.apache.ignite.binary.BinaryObjectException; import org.apache.ignite.binary.BinaryRawReader; import org.jetbrains.annotations.Nullable; /** * Extended reader interface. */ public interface BinaryRawReaderEx extends BinaryRawReader { /** * @return Object. * @throws org.apache.ignite.binary.BinaryObjectException In case of error. */ @Nullable public Object readObjectDetached() throws BinaryObjectException; }
apacheignite/ignite
modules/core/src/main/java/org/apache/ignite/internal/portable/BinaryRawReaderEx.java
Java
apache-2.0
1,296
/* * Copyright 2017-present Facebook, 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 com.facebook.buck.js; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.FlavorDomain; import com.facebook.buck.model.Flavored; import com.facebook.buck.model.UnflavoredBuildTarget; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleCreationContext; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.CommonDescriptionArg; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.Description; import com.facebook.buck.rules.HasDepsQuery; import com.facebook.buck.rules.HasTests; import com.facebook.buck.rules.Hint; import com.facebook.buck.rules.ImplicitDepsInferringDescription; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.query.QueryUtils; import com.facebook.buck.shell.WorkerTool; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.facebook.buck.util.types.Either; import com.facebook.buck.util.types.Pair; import com.google.common.base.Preconditions; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.Weigher; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.function.Function; import java.util.stream.Stream; import javax.annotation.Nullable; import org.immutables.value.Value; public class JsLibraryDescription implements Description<JsLibraryDescriptionArg>, Flavored, ImplicitDepsInferringDescription<JsLibraryDescription.AbstractJsLibraryDescriptionArg> { static final ImmutableSet<FlavorDomain<?>> FLAVOR_DOMAINS = ImmutableSet.of(JsFlavors.PLATFORM_DOMAIN, JsFlavors.OPTIMIZATION_DOMAIN); private final Cache< ImmutableSet<Either<SourcePath, Pair<SourcePath, String>>>, ImmutableBiMap<Either<SourcePath, Pair<SourcePath, String>>, Flavor>> sourcesToFlavorsCache = CacheBuilder.newBuilder() .weakKeys() .maximumWeight(1 << 16) .weigher( (Weigher<ImmutableSet<?>, ImmutableBiMap<?, ?>>) (sources, flavors) -> sources.size()) .build(); @Override public Class<JsLibraryDescriptionArg> getConstructorArgType() { return JsLibraryDescriptionArg.class; } @Override public BuildRule createBuildRule( BuildRuleCreationContext context, BuildTarget buildTarget, BuildRuleParams params, JsLibraryDescriptionArg args) { BuildRuleResolver resolver = context.getBuildRuleResolver(); // this params object is used as base for the JsLibrary build rule, but also for all dynamically // created JsFile rules. // For the JsLibrary case, we want to propagate flavors to library dependencies // For the JsFile case, we only want to depend on the worker, not on any libraries params = JsUtil.withWorkerDependencyOnly(params, resolver, args.getWorker()); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver); SourcePathResolver sourcePathResolver = DefaultSourcePathResolver.from(ruleFinder); ImmutableBiMap<Either<SourcePath, Pair<SourcePath, String>>, Flavor> sourcesToFlavors; try { sourcesToFlavors = sourcesToFlavorsCache.get( args.getSrcs(), () -> mapSourcesToFlavors(sourcePathResolver, args.getSrcs())); } catch (ExecutionException e) { throw new RuntimeException(e); } Optional<Either<SourcePath, Pair<SourcePath, String>>> file = JsFlavors.extractSourcePath(sourcesToFlavors.inverse(), buildTarget.getFlavors().stream()); ProjectFilesystem projectFilesystem = context.getProjectFilesystem(); CellPathResolver cellRoots = context.getCellPathResolver(); WorkerTool worker = resolver.getRuleWithType(args.getWorker(), WorkerTool.class); if (file.isPresent()) { return buildTarget.getFlavors().contains(JsFlavors.RELEASE) ? createReleaseFileRule( buildTarget, projectFilesystem, params, resolver, cellRoots, args, worker) : createDevFileRule( buildTarget, projectFilesystem, params, ruleFinder, sourcePathResolver, resolver, cellRoots, args, file.get(), worker); } else if (buildTarget.getFlavors().contains(JsFlavors.LIBRARY_FILES)) { return new LibraryFilesBuilder(resolver, buildTarget, params, sourcesToFlavors) .setSources(args.getSrcs()) .build(projectFilesystem, worker); } else { Stream<BuildTarget> deps = args.getDeps().stream(); if (args.getDepsQuery().isPresent()) { // We allow the `deps_query` to contain different kinds of build targets, but filter out // all targets that don't refer to a JsLibrary rule. // That prevents users from having to wrap every query into "kind(js_library, ...)". Stream<BuildTarget> jsLibraryTargetsInQuery = args.getDepsQuery() .get() .getResolvedQuery() .stream() .filter(target -> JsUtil.isJsLibraryTarget(target, context.getTargetGraph())); deps = Stream.concat(deps, jsLibraryTargetsInQuery); } return new LibraryBuilder(context.getTargetGraph(), resolver, buildTarget, params) .setLibraryDependencies(deps) .build(projectFilesystem, worker); } } @Override public boolean hasFlavors(ImmutableSet<Flavor> flavors) { return JsFlavors.validateFlavors(flavors, FLAVOR_DOMAINS); } @Override public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains() { return Optional.of(FLAVOR_DOMAINS); } @Override public void findDepsForTargetFromConstructorArgs( BuildTarget buildTarget, CellPathResolver cellRoots, AbstractJsLibraryDescriptionArg arg, ImmutableCollection.Builder<BuildTarget> extraDepsBuilder, ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) { if (arg.getDepsQuery().isPresent()) { extraDepsBuilder.addAll( QueryUtils.extractParseTimeTargets(buildTarget, cellRoots, arg.getDepsQuery().get()) .iterator()); } } @BuckStyleImmutable @Value.Immutable(copy = true) interface AbstractJsLibraryDescriptionArg extends CommonDescriptionArg, HasDepsQuery, HasExtraJson, HasTests { Optional<String> getExtraArgs(); ImmutableSet<Either<SourcePath, Pair<SourcePath, String>>> getSrcs(); BuildTarget getWorker(); @Hint(isDep = false, isInput = false) Optional<String> getBasePath(); } private static class LibraryFilesBuilder { private final BuildRuleResolver resolver; private final BuildTarget baseTarget; private final ImmutableBiMap<Either<SourcePath, Pair<SourcePath, String>>, Flavor> sourcesToFlavors; private final BuildTarget fileBaseTarget; private final BuildRuleParams baseParams; @Nullable private ImmutableList<JsFile> sourceFiles; public LibraryFilesBuilder( BuildRuleResolver resolver, BuildTarget baseTarget, BuildRuleParams baseParams, ImmutableBiMap<Either<SourcePath, Pair<SourcePath, String>>, Flavor> sourcesToFlavors) { this.resolver = resolver; this.baseTarget = baseTarget; this.sourcesToFlavors = sourcesToFlavors; // Platform information is only relevant when building release-optimized files. // Stripping platform targets from individual files allows us to use the base version of // every file in the build for all supported platforms, leading to improved cache reuse. this.fileBaseTarget = !baseTarget.getFlavors().contains(JsFlavors.RELEASE) ? baseTarget.withFlavors() : baseTarget; this.baseParams = baseParams; } private LibraryFilesBuilder setSources( ImmutableSet<Either<SourcePath, Pair<SourcePath, String>>> sources) { this.sourceFiles = ImmutableList.copyOf(sources.stream().map(this::requireJsFile).iterator()); return this; } private JsFile requireJsFile(Either<SourcePath, Pair<SourcePath, String>> file) { Flavor fileFlavor = sourcesToFlavors.get(file); BuildTarget target = fileBaseTarget.withAppendedFlavors(fileFlavor); resolver.requireRule(target); return resolver.getRuleWithType(target, JsFile.class); } private JsLibrary.Files build(ProjectFilesystem projectFileSystem, WorkerTool worker) { Preconditions.checkNotNull(sourceFiles, "No source files set"); return new JsLibrary.Files( baseTarget.withAppendedFlavors(JsFlavors.LIBRARY_FILES), projectFileSystem, baseParams.copyAppendingExtraDeps(sourceFiles), sourceFiles .stream() .map(BuildRule::getSourcePathToOutput) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())), worker); } } private static class LibraryBuilder { private final TargetGraph targetGraph; private final BuildRuleResolver resolver; private final BuildTarget baseTarget; private final BuildRuleParams baseParams; @Nullable private ImmutableList<JsLibrary> libraryDependencies; private LibraryBuilder( TargetGraph targetGraph, BuildRuleResolver resolver, BuildTarget baseTarget, BuildRuleParams baseParams) { this.targetGraph = targetGraph; this.baseTarget = baseTarget; this.baseParams = baseParams; this.resolver = resolver; } private LibraryBuilder setLibraryDependencies(Stream<BuildTarget> deps) { this.libraryDependencies = deps.map(hasFlavors() ? this::addFlavorsToLibraryTarget : Function.identity()) // `requireRule()` needed for dependencies to flavored versions .map(resolver::requireRule) .map(this::verifyIsJsLibraryRule) .collect(ImmutableList.toImmutableList()); return this; } private JsLibrary build(ProjectFilesystem projectFilesystem, WorkerTool worker) { Preconditions.checkNotNull(libraryDependencies, "No library dependencies set"); BuildTarget filesTarget = baseTarget.withAppendedFlavors(JsFlavors.LIBRARY_FILES); BuildRule filesRule = resolver.requireRule(filesTarget); return new JsLibrary( baseTarget, projectFilesystem, baseParams.copyAppendingExtraDeps( Iterables.concat(ImmutableList.of(filesRule), libraryDependencies)), resolver.getRuleWithType(filesTarget, JsLibrary.Files.class).getSourcePathToOutput(), libraryDependencies .stream() .map(BuildRule::getSourcePathToOutput) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())), worker); } private boolean hasFlavors() { return !baseTarget.getFlavors().isEmpty(); } private BuildTarget addFlavorsToLibraryTarget(BuildTarget unflavored) { return unflavored.withAppendedFlavors(baseTarget.getFlavors()); } JsLibrary verifyIsJsLibraryRule(BuildRule rule) { if (!(rule instanceof JsLibrary)) { BuildTarget target = rule.getBuildTarget(); throw new HumanReadableException( "js_library target '%s' can only depend on other js_library targets, but one of its " + "dependencies, '%s', is of type %s.", baseTarget, target, Description.getBuildRuleType(targetGraph.get(target).getDescription()).getName()); } return (JsLibrary) rule; } } private static BuildRule createReleaseFileRule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, BuildRuleResolver resolver, CellPathResolver cellRoots, JsLibraryDescriptionArg args, WorkerTool worker) { BuildTarget devTarget = withFileFlavorOnly(buildTarget); BuildRule devFile = resolver.requireRule(devTarget); return new JsFile.JsFileRelease( buildTarget, projectFilesystem, params.copyAppendingExtraDeps(devFile), resolver.getRuleWithType(devTarget, JsFile.class).getSourcePathToOutput(), JsUtil.getExtraJson(args, buildTarget, resolver, cellRoots), args.getExtraArgs(), worker); } private static <A extends AbstractJsLibraryDescriptionArg> BuildRule createDevFileRule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams params, SourcePathRuleFinder ruleFinder, SourcePathResolver sourcePathResolver, BuildRuleResolver resolver, CellPathResolver cellRoots, A args, Either<SourcePath, Pair<SourcePath, String>> source, WorkerTool worker) { SourcePath sourcePath = source.transform(x -> x, Pair::getFirst); Optional<String> subPath = Optional.ofNullable(source.transform(x -> null, Pair::getSecond)); Optional<Path> virtualPath = args.getBasePath() .map( basePath -> changePathPrefix( sourcePath, basePath, projectFilesystem, sourcePathResolver, buildTarget.getUnflavoredBuildTarget()) .resolve(subPath.orElse(""))); return new JsFile.JsFileDev( buildTarget, projectFilesystem, ruleFinder.getRule(sourcePath).map(params::copyAppendingExtraDeps).orElse(params), sourcePath, subPath, virtualPath, JsUtil.getExtraJson(args, buildTarget, resolver, cellRoots), args.getExtraArgs(), worker); } private static BuildTarget withFileFlavorOnly(BuildTarget target) { return target.withFlavors( target.getFlavors().stream().filter(JsFlavors::isFileFlavor).toArray(Flavor[]::new)); } private static ImmutableBiMap<Either<SourcePath, Pair<SourcePath, String>>, Flavor> mapSourcesToFlavors( SourcePathResolver sourcePathResolver, ImmutableSet<Either<SourcePath, Pair<SourcePath, String>>> sources) { ImmutableBiMap.Builder<Either<SourcePath, Pair<SourcePath, String>>, Flavor> builder = ImmutableBiMap.builder(); for (Either<SourcePath, Pair<SourcePath, String>> source : sources) { Path relativePath = source.transform( sourcePathResolver::getRelativePath, pair -> Paths.get(pair.getSecond())); builder.put(source, JsFlavors.fileFlavorForSourcePath(relativePath)); } return builder.build(); } private static Path changePathPrefix( SourcePath sourcePath, String basePath, ProjectFilesystem projectFilesystem, SourcePathResolver sourcePathResolver, UnflavoredBuildTarget target) { Path directoryOfBuildFile = target.getCellPath().resolve(target.getBasePath()); Path transplantTo = MorePaths.normalize(directoryOfBuildFile.resolve(basePath)); Path absolutePath = sourcePathResolver .getPathSourcePath(sourcePath) .map( pathSourcePath -> // for sub paths, replace the leading directory with the base path transplantTo.resolve( MorePaths.relativize( directoryOfBuildFile, sourcePathResolver.getAbsolutePath(sourcePath)))) .orElse(transplantTo); // build target output paths are replaced completely return projectFilesystem .getPathRelativeToProjectRoot(absolutePath) .orElseThrow( () -> new HumanReadableException( "%s: Using '%s' as base path for '%s' would move the file " + "out of the project root.", target, basePath, sourcePathResolver.getRelativePath(sourcePath))); } }
clonetwin26/buck
src/com/facebook/buck/js/JsLibraryDescription.java
Java
apache-2.0
17,462
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.data.join; import io.crate.data.BatchIterator; import java.util.function.Predicate; /** * <pre> * for (leftRow in left) { * for (rightRow in right) { * match? * onRow * } * if (noRightRowMatched) { * onRow // with right side null * } * } * </pre> */ public class LeftJoinNLBatchIterator<L, R, C> extends JoinBatchIterator<L, R, C> { private final Predicate<C> joinCondition; private boolean hadMatch = false; public LeftJoinNLBatchIterator(BatchIterator<L> left, BatchIterator<R> right, ElementCombiner<L, R, C> combiner, Predicate<C> joinCondition) { super(left, right, combiner); this.joinCondition = joinCondition; } @Override public boolean moveNext() { while (true) { if (activeIt == left) { return moveLeftSide(); } Boolean x = tryAdvanceRight(); if (x != null) { return x; } activeIt = left; } } private boolean moveLeftSide() { activeIt = right; while (tryMoveLeft()) { Boolean x = tryAdvanceRight(); if (x != null) { return x; } } activeIt = left; return false; } /** * try to move the right side * * @return true -> moved and matched * false -> need to load more data * null -> reached it's end and moved back to start -> left side needs to continue */ private Boolean tryAdvanceRight() { while (tryMoveRight()) { if (joinCondition.test(combiner.currentElement())) { hadMatch = true; return true; } } if (right.allLoaded() == false) { return false; } right.moveToStart(); if (hadMatch == false) { activeIt = left; combiner.nullRight(); return true; } hadMatch = false; return null; } }
crate/crate
libs/dex/src/main/java/io/crate/data/join/LeftJoinNLBatchIterator.java
Java
apache-2.0
3,218
package com.wincom.mstar.domain; import java.util.ArrayList; import java.util.List; public class CNumExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public CNumExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated do_not_delete_during_merge Thu Mar 02 11:23:21 CST 2017 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table nfjd502.dbo.CNum * * @mbggenerated Thu Mar 02 11:23:21 CST 2017 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
xtwxy/cassandra-tests
mstar-server-dao/src/main/java/com/wincom/mstar/domain/CNumExample.java
Java
apache-2.0
10,330
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.unsafe.impl.batchimport.input; /** * A {@link Listener} which is designed to receive one or more items, to then finally be closed * when all items have been received. */ public interface Receiver<T,EXCEPTION extends Exception> extends AutoCloseable { void receive( T item ) throws EXCEPTION; @Override void close() throws EXCEPTION; }
HuangLS/neo4j
community/kernel/src/main/java/org/neo4j/unsafe/impl/batchimport/input/Receiver.java
Java
apache-2.0
1,166
class RegisterPair: def __init__(self, name, register_high, register_low): self.name = name self.register_high = register_high self.register_low = register_low
AlexLitvino/i8080_simulator
microprocessor/register_pair.py
Python
apache-2.0
189
# Neotrisauropus deambulator SPECIES #### Status ACCEPTED #### According to Paleobiology Database #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/incertae sedis/Neotrisauropus/Neotrisauropus deambulator/README.md
Markdown
apache-2.0
166
/* * Copyright 2008, Unitils.org * * 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.unitils.util; import junit.framework.TestCase; import org.unitils.core.UnitilsException; /** * Test for {@link ReflectionUtils} that use enumeration values. * * @author Tim Ducheyne * @author Filip Neven */ public class ReflectionUtilsEnumTest extends TestCase { /** * Test for get enum value. */ public void testGetEnumValue() { TestEnum result = ReflectionUtils.getEnumValue(TestEnum.class, "VALUE1"); assertSame(TestEnum.VALUE1, result); } /** * Test for get enum value with different case. */ public void testGetEnumValue_differentCase() { TestEnum result = ReflectionUtils.getEnumValue(TestEnum.class, "Value1"); assertSame(TestEnum.VALUE1, result); } /** * Test for get enum value, but an unknown value name. * Should fail with a runtime exception. */ public void testGetEnumValue_unexisting() { try { ReflectionUtils.getEnumValue(TestEnum.class, "xxxxxxxxx"); fail("Expected UnitilsException"); } catch (UnitilsException e) { //expected } } /** * Test enumeration with a default value. */ private enum TestEnum { DEFAULT, VALUE1, VALUE2 } }
arteam/unitils
unitils-test/src/test/java/org/unitils/util/ReflectionUtilsEnumTest.java
Java
apache-2.0
1,947
package org.sociesc.system.university.bo; import org.sociesc.system.university.Course; import org.sociesc.system.university.dao.CourseDAO; import org.sociesc.util.bo.BaseBO; public class CourseBO extends BaseBO<CourseDAO, Course> { public CourseBO(){ super(CourseDAO.class); } public void insert(Course course) throws Exception{ if(course.getNome().trim().isEmpty()){ throw new Exception("Nome está vazio."); } if(course.getSigla().trim().isEmpty()){ throw new Exception("Sigla está vazio."); } this.getDao().insert(course); } }
diegoarcega/JAVAWEB-VRaptorFramework
src/org/sociesc/system/university/bo/CourseBO.java
Java
apache-2.0
573
package gr.iti.mklab.framework.retrievers.impl; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.DateTime; import com.google.api.services.plus.Plus; import com.google.api.services.plus.Plus.People; import com.google.api.services.plus.Plus.People.Get; import com.google.api.services.plus.Plus.People.Search; import com.google.api.services.plus.PlusRequestInitializer; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import com.google.api.services.plus.model.PeopleFeed; import com.google.api.services.plus.model.Person; import gr.iti.mklab.framework.Credentials; import gr.iti.mklab.framework.abstractions.socialmedia.items.GooglePlusItem; import gr.iti.mklab.framework.abstractions.socialmedia.users.GooglePlusStreamUser; import gr.iti.mklab.framework.common.domain.Item; import gr.iti.mklab.framework.common.domain.MediaItem; import gr.iti.mklab.framework.common.domain.StreamUser; import gr.iti.mklab.framework.common.domain.feeds.AccountFeed; import gr.iti.mklab.framework.common.domain.feeds.GroupFeed; import gr.iti.mklab.framework.common.domain.feeds.KeywordsFeed; import gr.iti.mklab.framework.common.domain.feeds.LocationFeed; import gr.iti.mklab.framework.retrievers.Response; import gr.iti.mklab.framework.retrievers.Retriever; /** * Class responsible for retrieving Google+ content based on keywords or google+ users * The retrieval process takes place through Google API * * @author manosetro - manosetro@iti.gr */ public class GooglePlusRetriever extends Retriever { private Logger logger = LogManager.getLogger(GooglePlusRetriever.class); private static final HttpTransport transport = new NetHttpTransport(); private static final JsonFactory jsonFactory = new JacksonFactory(); private Plus googlePlusService; private String GooglePlusKey; public GooglePlusRetriever(Credentials credentials) { super(credentials); GooglePlusKey = credentials.getKey(); GoogleCredential credential = new GoogleCredential(); googlePlusService = new Plus.Builder(transport, jsonFactory, credential) .setApplicationName("SocialSensor") .setHttpRequestInitializer(credential) .setPlusRequestInitializer(new PlusRequestInitializer(GooglePlusKey)).build(); } @Override public Response retrieveAccountFeed(AccountFeed feed, Integer maxRequests) { List<Item> items = new ArrayList<Item>(); Date sinceDate = new Date(feed.getSinceDate()); String label = feed.getLabel(); int numberOfRequests = 0; String userID = feed.getId(); String uName = feed.getUsername(); if(uName == null && userID == null) { logger.info("#GooglePlus : No account feed"); Response response = getResponse(items, numberOfRequests); return response; } //Retrieve userID from Google+ StreamUser streamUser = null; try { if(userID == null) { // userid is not available. search with username Search searchPeople = googlePlusService.people().search(uName); searchPeople.setMaxResults(50L); PeopleFeed peopleFeed = searchPeople.execute(); numberOfRequests++; List<Person> personsFound = peopleFeed.getItems(); for(Person person : personsFound) { if(person.getUrl().equals("https://plus.google.com/+" + uName) || person.getDisplayName().equals(uName)) { userID = person.getId(); streamUser = getStreamUser(userID); break; } } } else { numberOfRequests++; streamUser = getStreamUser(userID); uName = streamUser.getUsername(); } } catch (Exception e) { logger.error(e); Response response = getResponse(items, numberOfRequests); return response; } if(streamUser == null) { logger.error("User not found. Feed: (" + feed.getId() + ""); Response response = getResponse(items, numberOfRequests); return response; } //Retrieve activity with userID logger.info("Get public feed of user " + userID); boolean isFinished = false, sinceDateReached = false; while(true) { try { Plus.Activities.List userActivities = googlePlusService.activities().list(userID, "public"); userActivities.setMaxResults(100L); ActivityFeed activityFeed = userActivities.execute(); numberOfRequests ++; List<Activity> activities = activityFeed.getItems(); if(activities == null) { isFinished = true; break; } for (Activity activity : activities) { if(activity == null || activity.getId() == null) { isFinished = true; break; } DateTime publicationTime = activity.getPublished(); Date publicationDate = new Date(publicationTime.getValue()); if(publicationDate.before(sinceDate)) { sinceDateReached = true; break; } String verb = activity.getVerb(); String objectType = activity.getObject().getObjectType(); if(!verb.equals("post") && !verb.equals("share") && !objectType.equals("note") && !objectType.equals("activity")) { // unknown type of activity continue; } Item googlePlusItem = new GooglePlusItem(activity, streamUser); if(label != null) { googlePlusItem.addLabel(label); } if(streamUser != null) { googlePlusItem.setStreamUser(streamUser); } items.add(googlePlusItem); } if(sinceDateReached) { logger.info("Stop retriever. Since date " + sinceDate + " reached for " + userID + " (" + uName + ")."); break; } if(numberOfRequests > maxRequests) { logger.info("Stop retriever. Number of requests (" + numberOfRequests + ") has reached for " + userID + " (" + uName + ")."); break; } if(activityFeed.getNextPageToken() == null) { logger.info("Stop retriever. There is no more pages to fetch for " + userID + " (" + uName + ")."); break; } if(isFinished) { logger.info("Stop retriever. Activity is null for " + userID + " (" + uName + ")."); break; } userActivities.setPageToken(activityFeed.getNextPageToken()); } catch (IOException e) { logger.error("#GooglePlus Exception for feed (" + feed.getId() + ")", e); Response response = getResponse(items, numberOfRequests); return response; } } Response response = getResponse(items, numberOfRequests); return response; } @Override public Response retrieveKeywordsFeed(KeywordsFeed feed, Integer maxRequests) { List<Item> items = new ArrayList<Item>(); int numberOfRequests = 0; Date sinceDate = new Date(feed.getSinceDate()); String label = feed.getLabel(); List<String> keywords = feed.getKeywords(); if(keywords == null || keywords.isEmpty()) { logger.info("#GooglePlus : No keywords feed"); Response response = getResponse(items, numberOfRequests); return response; } List<String> queryParts = new ArrayList<String>(); for(String keyword : keywords) { String [] parts = keyword.trim().split("\\s+"); String part = "(" + StringUtils.join(parts, " AND ") + ")"; queryParts.add(part); } String tagsQuery = StringUtils.join(queryParts, " OR "); if(tagsQuery.equals("")) { Response response = getResponse(items, numberOfRequests); return response; } logger.info("Text Query: (" + tagsQuery + ")" + (label==null ? "" : ("with label=" + label))); boolean isFinished = false, sinceDateReached = false; String nextPageToken = null; while(true) { try { Plus.Activities.Search searchActivities = googlePlusService.activities().search(tagsQuery); searchActivities.setMaxResults(20L); searchActivities.setOrderBy("recent"); if(nextPageToken != null) { searchActivities.setPageToken(nextPageToken); } ActivityFeed activityFeed = searchActivities.execute(); numberOfRequests++; List<Activity> activities = activityFeed.getItems(); for (Activity activity : activities) { DateTime publicationTime = activity.getPublished(); Date publicationDate = new Date(publicationTime.getValue()); if(publicationDate.before(sinceDate)) { sinceDateReached = true; break; } String verb = activity.getVerb(); String objectType = activity.getObject().getObjectType(); if(!verb.equals("post") && !verb.equals("share") && !objectType.equals("note") && !objectType.equals("activity")) { // unknown type of activity continue; } Item googlePlusItem = new GooglePlusItem(activity); if(label != null) { googlePlusItem.addLabel(label); } items.add(googlePlusItem); } nextPageToken = activityFeed.getNextPageToken(); if(sinceDateReached) { logger.info("Stop retriever. Since date " + sinceDate + " reached for (" + tagsQuery + ")."); break; } if(numberOfRequests > maxRequests) { logger.info("Stop retriever. Number of requests (" + numberOfRequests + ") has reached for (" + tagsQuery + ")."); break; } if(activityFeed.getNextPageToken() == null) { logger.info("Stop retriever. There is no more pages to fetch for (" + tagsQuery + ")."); break; } if(isFinished) { logger.info("Stop retriever. Activity is null for (" + tagsQuery + ")."); break; } } catch (IOException e) { logger.error(e); } } Response response = getResponse(items, numberOfRequests); return response; } @Override public Response retrieveLocationFeed(LocationFeed feed, Integer maxRequests) { return new Response(); } @Override public Response retrieveGroupFeed(GroupFeed feed, Integer maxRequests) { return new Response(); } @Override public MediaItem getMediaItem(String id) { return null; } @Override public Item getItem(String id) { try { Plus.Activities.Get get = googlePlusService.activities().get(id); Activity activity = get.execute(); if(activity != null) { String verb = activity.getVerb(); String objectType = activity.getObject().getObjectType(); if(!verb.equals("post") && !verb.equals("share") && !objectType.equals("note") && !objectType.equals("activity")) { return null; } Item item = new GooglePlusItem(activity); return item; } } catch (IOException e) { e.printStackTrace(); } return null; } @Override public StreamUser getStreamUser(String uid) { People people = googlePlusService.people(); try { Get getRequest = people.get(uid); Person person = getRequest.execute(); StreamUser streamUser = new GooglePlusStreamUser(person); return streamUser; } catch (IOException e) { logger.error("Exception for user " + uid, e); } return null; } public static void main(String...args) { String uid = "103783079217258362060"; Date since = new Date(System.currentTimeMillis()-365*24*3600000l); AccountFeed aFeed = new AccountFeed(uid, null, since.getTime(), "GooglePlus"); KeywordsFeed kFeed = new KeywordsFeed("id", "#debt", since.getTime(), "GooglePlus"); Credentials credentials = new Credentials(); credentials.setKey("xxxxxxxxxxxxxxxxxxxxxxxxxxx"); GooglePlusRetriever retriever = new GooglePlusRetriever(credentials); Response response = retriever.retrieveAccountFeed(aFeed, 1); System.out.println(response.getNumberOfItems() + " items found for " + aFeed.getId()); Response response2 = retriever.retrieveKeywordsFeed(kFeed, 1); for(Item item : response2.getItems()) { System.out.println(StringUtils.join(item.getTags())); } } @Override public List<Item> getItemComments(Item item, long since) { // TODO Auto-generated method stub return null; } }
MKLab-ITI/mklab-socialmedia-abstractions
src/main/java/gr/iti/mklab/framework/retrievers/impl/GooglePlusRetriever.java
Java
apache-2.0
12,192
const path = require('path') const config = require('config') const git = require('git-rev-sync') const CDN = config.get('cdn') const appVersion = git.short() const CDN_URI = appVersion const CDN_URL = CDN ? `${CDN}/${CDN_URI}` : '' const PUBLIC_PATH = CDN ? `${CDN}/${CDN_URI}/assets/` : '/assets/' const ROOT_PATH = path.join(__dirname, '../') // 项目根目录 const ASSETS_PATH = path.join(ROOT_PATH, './public') const MODULES_PATH = path.join(ROOT_PATH, './node_modules') // node包目录 const BUILD_PATH = path.resolve(ASSETS_PATH, './assets') // 最后输出放置公共资源的目录 const DLL_PATH = path.resolve(ASSETS_PATH, './dll') const SOURCE_PATH = path.join(ROOT_PATH, './frontend') const ENTRY_PATH = path.join(SOURCE_PATH, './entries') // webpack入口文件 module.exports = { ROOT_PATH, BUILD_PATH, DLL_PATH, MODULES_PATH, CDN_URI, CDN_URL, PUBLIC_PATH, ENTRY_PATH, SOURCE_PATH, ASSETS_PATH }
ecmadao/hacknical
config/path.js
JavaScript
apache-2.0
942
Sidekiq.configure_server do |config| config.redis = { url: "redis://localhost:6379/" } end Sidekiq.configure_client do |config| config.redis = { url: "redis://localhost:6379/" } end
smartbox-io/cell
config/initializers/sidekiq.rb
Ruby
apache-2.0
187
package org.esmerilprogramming.overtown.annotation.session; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = { ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface OnSessionCreate { }
EsmerilProgramming/overtown
src/main/java/org/esmerilprogramming/overtown/annotation/session/OnSessionCreate.java
Java
apache-2.0
338
package org.rabix.engine.rest.backend.stub.impl; import org.apache.commons.configuration.Configuration; import org.rabix.engine.rest.backend.stub.BackendStub; import org.rabix.engine.rest.service.JobService; import org.rabix.transport.backend.impl.BackendRabbitMQ; import org.rabix.transport.backend.impl.BackendRabbitMQ.BackendConfiguration; import org.rabix.transport.backend.impl.BackendRabbitMQ.EngineConfiguration; import org.rabix.transport.mechanism.TransportPluginException; import org.rabix.transport.mechanism.impl.rabbitmq.TransportPluginRabbitMQ; import org.rabix.transport.mechanism.impl.rabbitmq.TransportQueueRabbitMQ; public class BackendStubRabbitMQ extends BackendStub<TransportQueueRabbitMQ, BackendRabbitMQ, TransportPluginRabbitMQ> { public BackendStubRabbitMQ(JobService jobService, BackendRabbitMQ backend, Configuration configuration) throws TransportPluginException { this.jobService = jobService; this.backend = backend; this.transportPlugin = new TransportPluginRabbitMQ(configuration); BackendConfiguration backendConfiguration = backend.getBackendConfiguration(); this.sendToBackendQueue = new TransportQueueRabbitMQ(backendConfiguration.getExchange(), backendConfiguration.getExchangeType(), backendConfiguration.getReceiveRoutingKey()); this.sendToBackendControlQueue = new TransportQueueRabbitMQ(backendConfiguration.getExchange(), backendConfiguration.getExchangeType(), backendConfiguration.getReceiveControlRoutingKey()); EngineConfiguration engineConfiguration = backend.getEngineConfiguration(); this.receiveFromBackendQueue = new TransportQueueRabbitMQ(engineConfiguration.getExchange(), engineConfiguration.getExchangeType(), engineConfiguration.getReceiveRoutingKey()); this.receiveFromBackendHeartbeatQueue = new TransportQueueRabbitMQ(engineConfiguration.getExchange(), engineConfiguration.getExchangeType(), engineConfiguration.getHeartbeatRoutingKey()); initialize(); } /** * Try to initialize both exchanges (engine, backend) */ private void initialize() { try { transportPlugin.initializeExchange(backend.getBackendConfiguration().getExchange(), backend.getBackendConfiguration().getExchangeType()); transportPlugin.initializeExchange(backend.getEngineConfiguration().getExchange(), backend.getEngineConfiguration().getExchangeType()); } catch (TransportPluginException e) { // do nothing } } @Override public void stop() { try { transportPlugin.deleteExchange(backend.getBackendConfiguration().getExchange()); } catch (TransportPluginException e) { // do nothing } } }
markosbg/debug
rabix-engine-rest/src/main/java/org/rabix/engine/rest/backend/stub/impl/BackendStubRabbitMQ.java
Java
apache-2.0
2,646
import { connect } from 'react-redux'; import ErrorMessageList from '../../components/error_messages/list'; import { fetchErrorMessagesIfNeeded, searchErrorMessages, loadNext } from '../../actions/error_messages' export default connect( (state,ownProps) => { let errorMessages; let match = ownProps.match if (match && match.params && match.params.id) { errorMessages = state.errorMessages[match.params.id] } return {errorMessages} }, (dispatch,ownProps) => { let resourceId; let match = ownProps.match if (match && match.params && match.params.id) { resourceId = match.params.id } return { loadErrorMessagesOnce: () => dispatch(fetchErrorMessagesIfNeeded(resourceId)), loadNext: () => dispatch(loadNext(resourceId)), searchErrorMessages: (term) => dispatch(searchErrorMessages(resourceId,term)) } } )(ErrorMessageList);
sapcc/elektra
plugins/shared_filesystem_storage/app/javascript/app/containers/error_messages/list.js
JavaScript
apache-2.0
916
package com.neustar.ultraservice.schema.v01; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for PasswordVerificationQuestionList complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="PasswordVerificationQuestionList"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="PasswordVerificationQuestion" type="{http://schema.ultraservice.neustar.com/v01/}PasswordVerificationQuestion" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "PasswordVerificationQuestionList", propOrder = { "passwordVerificationQuestion" }) public class PasswordVerificationQuestionList { @XmlElement(name = "PasswordVerificationQuestion", required = true) protected List<PasswordVerificationQuestion> passwordVerificationQuestion; /** * Gets the value of the passwordVerificationQuestion property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the passwordVerificationQuestion property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPasswordVerificationQuestion().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PasswordVerificationQuestion } * * */ public List<PasswordVerificationQuestion> getPasswordVerificationQuestion() { if (passwordVerificationQuestion == null) { passwordVerificationQuestion = new ArrayList<PasswordVerificationQuestion>(); } return this.passwordVerificationQuestion; } }
ultradns/ultra-java-api
src/main/java/com/neustar/ultraservice/schema/v01/PasswordVerificationQuestionList.java
Java
apache-2.0
2,280
package com.yourname.flixelgame.examples.timer; import org.flixel.FlxG; import org.flixel.FlxState; import org.flixel.FlxText; import org.flixel.FlxTimer; import org.flixel.event.IFlxTimer; /** * A short demo how to use the methods for the plugins. * In this demo the TimerManager is used. * * @author Ka Wing Chin */ public class PlayState extends FlxState { private FlxTimer _timer; private FlxText _text; private boolean _complete; @Override public void create() { FlxG.setBgColor(0xFF000000); // The timer class. _timer = new FlxTimer(); _timer.start(3, 1, stop); // Removes an instance of a plugin from the global plugin array. //FlxG.removePlugin(FlxTimer.getManager()); // Removes an instance of a plugin from the global plugin array. //FlxG.removePluginType(TimerManager.class); // Removes an instance of a plugin from the global plugin array. //FlxG.getPlugin(TimerManager.class); _text = new FlxText(10, 10, 200, "Time: "); add(_text); } @Override public void update() { if(!_complete) _text.setText("Time: " + _timer.getTimeLeft()); super.update(); } IFlxTimer stop = new IFlxTimer() { @Override public void callback(FlxTimer flxTimer) { _text.setText("Time: complete"); _complete = true; } }; }
jjhaggar/libGDX-flixel-test-autogenerated
flixelgame/src/com/yourname/flixelgame/examples/timer/PlayState.java
Java
apache-2.0
1,304
/** * FreeRDP: A Remote Desktop Protocol Implementation * * Copyright 2013-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <freerdp/log.h> #include <winpr/tchar.h> #include <winpr/print.h> #include "wf_rail.h" #define TAG CLIENT_TAG("windows") #define GET_X_LPARAM(lParam) ((UINT16) (lParam & 0xFFFF)) #define GET_Y_LPARAM(lParam) ((UINT16) ((lParam >> 16) & 0xFFFF)) /* RemoteApp Core Protocol Extension */ struct _WINDOW_STYLE { UINT32 style; const char* name; BOOL multi; }; typedef struct _WINDOW_STYLE WINDOW_STYLE; static const WINDOW_STYLE WINDOW_STYLES[] = { { WS_BORDER, "WS_BORDER", FALSE }, { WS_CAPTION, "WS_CAPTION", FALSE }, { WS_CHILD, "WS_CHILD", FALSE }, { WS_CLIPCHILDREN, "WS_CLIPCHILDREN", FALSE }, { WS_CLIPSIBLINGS, "WS_CLIPSIBLINGS", FALSE }, { WS_DISABLED, "WS_DISABLED", FALSE }, { WS_DLGFRAME, "WS_DLGFRAME", FALSE }, { WS_GROUP, "WS_GROUP", FALSE }, { WS_HSCROLL, "WS_HSCROLL", FALSE }, { WS_ICONIC, "WS_ICONIC", FALSE }, { WS_MAXIMIZE, "WS_MAXIMIZE", FALSE }, { WS_MAXIMIZEBOX, "WS_MAXIMIZEBOX", FALSE }, { WS_MINIMIZE, "WS_MINIMIZE", FALSE }, { WS_MINIMIZEBOX, "WS_MINIMIZEBOX", FALSE }, { WS_OVERLAPPED, "WS_OVERLAPPED", FALSE }, { WS_OVERLAPPEDWINDOW, "WS_OVERLAPPEDWINDOW", TRUE }, { WS_POPUP, "WS_POPUP", FALSE }, { WS_POPUPWINDOW, "WS_POPUPWINDOW", TRUE }, { WS_SIZEBOX, "WS_SIZEBOX", FALSE }, { WS_SYSMENU, "WS_SYSMENU", FALSE }, { WS_TABSTOP, "WS_TABSTOP", FALSE }, { WS_THICKFRAME, "WS_THICKFRAME", FALSE }, { WS_VISIBLE, "WS_VISIBLE", FALSE } }; static const WINDOW_STYLE EXTENDED_WINDOW_STYLES[] = { { WS_EX_ACCEPTFILES, "WS_EX_ACCEPTFILES", FALSE }, { WS_EX_APPWINDOW, "WS_EX_APPWINDOW", FALSE }, { WS_EX_CLIENTEDGE, "WS_EX_CLIENTEDGE", FALSE }, { WS_EX_COMPOSITED, "WS_EX_COMPOSITED", FALSE }, { WS_EX_CONTEXTHELP, "WS_EX_CONTEXTHELP", FALSE }, { WS_EX_CONTROLPARENT, "WS_EX_CONTROLPARENT", FALSE }, { WS_EX_DLGMODALFRAME, "WS_EX_DLGMODALFRAME", FALSE }, { WS_EX_LAYERED, "WS_EX_LAYERED", FALSE }, { WS_EX_LAYOUTRTL, "WS_EX_LAYOUTRTL", FALSE }, { WS_EX_LEFT, "WS_EX_LEFT", FALSE }, { WS_EX_LEFTSCROLLBAR, "WS_EX_LEFTSCROLLBAR", FALSE }, { WS_EX_LTRREADING, "WS_EX_LTRREADING", FALSE }, { WS_EX_MDICHILD, "WS_EX_MDICHILD", FALSE }, { WS_EX_NOACTIVATE, "WS_EX_NOACTIVATE", FALSE }, { WS_EX_NOINHERITLAYOUT, "WS_EX_NOINHERITLAYOUT", FALSE }, { WS_EX_NOPARENTNOTIFY, "WS_EX_NOPARENTNOTIFY", FALSE }, { WS_EX_OVERLAPPEDWINDOW, "WS_EX_OVERLAPPEDWINDOW", TRUE }, { WS_EX_PALETTEWINDOW, "WS_EX_PALETTEWINDOW", TRUE }, { WS_EX_RIGHT, "WS_EX_RIGHT", FALSE }, { WS_EX_RIGHTSCROLLBAR, "WS_EX_RIGHTSCROLLBAR", FALSE }, { WS_EX_RTLREADING, "WS_EX_RTLREADING", FALSE }, { WS_EX_STATICEDGE, "WS_EX_STATICEDGE", FALSE }, { WS_EX_TOOLWINDOW, "WS_EX_TOOLWINDOW", FALSE }, { WS_EX_TOPMOST, "WS_EX_TOPMOST", FALSE }, { WS_EX_TRANSPARENT, "WS_EX_TRANSPARENT", FALSE }, { WS_EX_WINDOWEDGE, "WS_EX_WINDOWEDGE", FALSE } }; void PrintWindowStyles(UINT32 style) { int i; WLog_INFO(TAG, "\tWindow Styles:\t{"); for (i = 0; i < ARRAYSIZE(WINDOW_STYLES); i++) { if (style & WINDOW_STYLES[i].style) { if (WINDOW_STYLES[i].multi) { if ((style & WINDOW_STYLES[i].style) != WINDOW_STYLES[i].style) continue; } WLog_INFO(TAG, "\t\t%s", WINDOW_STYLES[i].name); } } } void PrintExtendedWindowStyles(UINT32 style) { int i; WLog_INFO(TAG, "\tExtended Window Styles:\t{"); for (i = 0; i < ARRAYSIZE(EXTENDED_WINDOW_STYLES); i++) { if (style & EXTENDED_WINDOW_STYLES[i].style) { if (EXTENDED_WINDOW_STYLES[i].multi) { if ((style & EXTENDED_WINDOW_STYLES[i].style) != EXTENDED_WINDOW_STYLES[i].style) continue; } WLog_INFO(TAG, "\t\t%s", EXTENDED_WINDOW_STYLES[i].name); } } } void PrintRailWindowState(WINDOW_ORDER_INFO* orderInfo, WINDOW_STATE_ORDER* windowState) { if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW) WLog_INFO(TAG, "WindowCreate: WindowId: 0x%04X", orderInfo->windowId); else WLog_INFO(TAG, "WindowUpdate: WindowId: 0x%04X", orderInfo->windowId); WLog_INFO(TAG, "{"); if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER) { WLog_INFO(TAG, "\tOwnerWindowId: 0x%04X", windowState->ownerWindowId); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE) { WLog_INFO(TAG, "\tStyle: 0x%04X ExtendedStyle: 0x%04X", windowState->style, windowState->extendedStyle); PrintWindowStyles(windowState->style); PrintExtendedWindowStyles(windowState->extendedStyle); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW) { WLog_INFO(TAG, "\tShowState: %d", windowState->showState); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE) { char* title = NULL; ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string, windowState->titleInfo.length / 2, &title, 0, NULL, NULL); WLog_INFO(TAG, "\tTitleInfo: %s (length = %d)", title, windowState->titleInfo.length); free(title); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) { WLog_INFO(TAG, "\tClientOffsetX: %d ClientOffsetY: %d", windowState->clientOffsetX, windowState->clientOffsetY); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) { WLog_INFO(TAG, "\tClientAreaWidth: %d ClientAreaHeight: %d", windowState->clientAreaWidth, windowState->clientAreaHeight); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) { WLog_INFO(TAG, "\tRPContent: %d", windowState->RPContent); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) { WLog_INFO(TAG, "\tRootParentHandle: 0x%04X", windowState->rootParentHandle); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) { WLog_INFO(TAG, "\tWindowOffsetX: %d WindowOffsetY: %d", windowState->windowOffsetX, windowState->windowOffsetY); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) { WLog_INFO(TAG, "\tWindowClientDeltaX: %d WindowClientDeltaY: %d", windowState->windowClientDeltaX, windowState->windowClientDeltaY); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) { WLog_INFO(TAG, "\tWindowWidth: %d WindowHeight: %d", windowState->windowWidth, windowState->windowHeight); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) { UINT32 index; RECTANGLE_16* rect; WLog_INFO(TAG, "\tnumWindowRects: %d", windowState->numWindowRects); for (index = 0; index < windowState->numWindowRects; index++) { rect = &windowState->windowRects[index]; WLog_INFO(TAG, "\twindowRect[%d]: left: %d top: %d right: %d bottom: %d", index, rect->left, rect->top, rect->right, rect->bottom); } } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) { WLog_INFO(TAG, "\tvisibileOffsetX: %d visibleOffsetY: %d", windowState->visibleOffsetX, windowState->visibleOffsetY); } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) { UINT32 index; RECTANGLE_16* rect; WLog_INFO(TAG, "\tnumVisibilityRects: %d", windowState->numVisibilityRects); for (index = 0; index < windowState->numVisibilityRects; index++) { rect = &windowState->visibilityRects[index]; WLog_INFO(TAG, "\tvisibilityRect[%d]: left: %d top: %d right: %d bottom: %d", index, rect->left, rect->top, rect->right, rect->bottom); } } WLog_INFO(TAG, "}"); } static void PrintRailIconInfo(WINDOW_ORDER_INFO* orderInfo, ICON_INFO* iconInfo) { WLog_INFO(TAG, "ICON_INFO"); WLog_INFO(TAG, "{"); WLog_INFO(TAG, "\tbigIcon: %s", (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG) ? "true" : "false"); WLog_INFO(TAG, "\tcacheEntry; 0x%04X", iconInfo->cacheEntry); WLog_INFO(TAG, "\tcacheId: 0x%04X", iconInfo->cacheId); WLog_INFO(TAG, "\tbpp: %d", iconInfo->bpp); WLog_INFO(TAG, "\twidth: %d", iconInfo->width); WLog_INFO(TAG, "\theight: %d", iconInfo->height); WLog_INFO(TAG, "\tcbColorTable: %d", iconInfo->cbColorTable); WLog_INFO(TAG, "\tcbBitsMask: %d", iconInfo->cbBitsMask); WLog_INFO(TAG, "\tcbBitsColor: %d", iconInfo->cbBitsColor); WLog_INFO(TAG, "\tcolorTable: %p", iconInfo->colorTable); WLog_INFO(TAG, "\tbitsMask: %p", iconInfo->bitsMask); WLog_INFO(TAG, "\tbitsColor: %p", iconInfo->bitsColor); WLog_INFO(TAG, "}"); } LRESULT CALLBACK wf_RailWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { HDC hDC; int x, y; int width; int height; UINT32 xPos; UINT32 yPos; PAINTSTRUCT ps; UINT32 inputFlags; wfContext* wfc = NULL; rdpInput* input = NULL; rdpContext* context = NULL; wfRailWindow* railWindow; railWindow = (wfRailWindow*) GetWindowLongPtr(hWnd, GWLP_USERDATA); if (railWindow) wfc = railWindow->wfc; if (wfc) context = (rdpContext*) wfc; if (context) input = context->input; switch (msg) { case WM_PAINT: { if (!wfc) return 0; hDC = BeginPaint(hWnd, &ps); x = ps.rcPaint.left; y = ps.rcPaint.top; width = ps.rcPaint.right - ps.rcPaint.left + 1; height = ps.rcPaint.bottom - ps.rcPaint.top + 1; BitBlt(hDC, x, y, width, height, wfc->primary->hdc, railWindow->x + x, railWindow->y + y, SRCCOPY); EndPaint(hWnd, &ps); } break; case WM_LBUTTONDOWN: { if (!railWindow || !input) return 0; xPos = GET_X_LPARAM(lParam) + railWindow->x; yPos = GET_Y_LPARAM(lParam) + railWindow->y; inputFlags = PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON1; if (input) input->MouseEvent(input, inputFlags, xPos, yPos); } break; case WM_LBUTTONUP: { if (!railWindow || !input) return 0; xPos = GET_X_LPARAM(lParam) + railWindow->x; yPos = GET_Y_LPARAM(lParam) + railWindow->y; inputFlags = PTR_FLAGS_BUTTON1; if (input) input->MouseEvent(input, inputFlags, xPos, yPos); } break; case WM_RBUTTONDOWN: { if (!railWindow || !input) return 0; xPos = GET_X_LPARAM(lParam) + railWindow->x; yPos = GET_Y_LPARAM(lParam) + railWindow->y; inputFlags = PTR_FLAGS_DOWN | PTR_FLAGS_BUTTON2; if (input) input->MouseEvent(input, inputFlags, xPos, yPos); } break; case WM_RBUTTONUP: { if (!railWindow || !input) return 0; xPos = GET_X_LPARAM(lParam) + railWindow->x; yPos = GET_Y_LPARAM(lParam) + railWindow->y; inputFlags = PTR_FLAGS_BUTTON2; if (input) input->MouseEvent(input, inputFlags, xPos, yPos); } break; case WM_MOUSEMOVE: { if (!railWindow || !input) return 0; xPos = GET_X_LPARAM(lParam) + railWindow->x; yPos = GET_Y_LPARAM(lParam) + railWindow->y; inputFlags = PTR_FLAGS_MOVE; if (input) input->MouseEvent(input, inputFlags, xPos, yPos); } break; case WM_MOUSEWHEEL: break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } #define RAIL_DISABLED_WINDOW_STYLES (WS_BORDER | WS_THICKFRAME | WS_DLGFRAME | WS_CAPTION | \ WS_OVERLAPPED | WS_VSCROLL | WS_HSCROLL | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX) #define RAIL_DISABLED_EXTENDED_WINDOW_STYLES (WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE | WS_EX_WINDOWEDGE) static BOOL wf_rail_window_common(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, WINDOW_STATE_ORDER* windowState) { wfRailWindow* railWindow = NULL; wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; UINT32 fieldFlags = orderInfo->fieldFlags; PrintRailWindowState(orderInfo, windowState); if (fieldFlags & WINDOW_ORDER_STATE_NEW) { HANDLE hInstance; WCHAR* titleW = NULL; WNDCLASSEX wndClassEx; railWindow = (wfRailWindow*) calloc(1, sizeof(wfRailWindow)); if (!railWindow) return FALSE; railWindow->wfc = wfc; railWindow->dwStyle = windowState->style; railWindow->dwStyle &= ~RAIL_DISABLED_WINDOW_STYLES; railWindow->dwExStyle = windowState->extendedStyle; railWindow->dwExStyle &= ~RAIL_DISABLED_EXTENDED_WINDOW_STYLES; railWindow->x = windowState->windowOffsetX; railWindow->y = windowState->windowOffsetY; railWindow->width = windowState->windowWidth; railWindow->height = windowState->windowHeight; if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) { char* title = NULL; if (windowState->titleInfo.length == 0) { if (!(title = _strdup(""))) { WLog_ERR(TAG, "failed to duplicate empty window title string"); /* error handled below */ } } else if (ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string, windowState->titleInfo.length / 2, &title, 0, NULL, NULL) < 1) { WLog_ERR(TAG, "failed to convert window title"); /* error handled below */ } railWindow->title = title; } else { if (!(railWindow->title = _strdup("RdpRailWindow"))) WLog_ERR(TAG, "failed to duplicate default window title string"); } if (!railWindow->title) { free(railWindow); return FALSE; } ConvertToUnicode(CP_UTF8, 0, railWindow->title, -1, &titleW, 0); hInstance = GetModuleHandle(NULL); ZeroMemory(&wndClassEx, sizeof(WNDCLASSEX)); wndClassEx.cbSize = sizeof(WNDCLASSEX); wndClassEx.style = 0; wndClassEx.lpfnWndProc = wf_RailWndProc; wndClassEx.cbClsExtra = 0; wndClassEx.cbWndExtra = 0; wndClassEx.hIcon = NULL; wndClassEx.hCursor = NULL; wndClassEx.hbrBackground = NULL; wndClassEx.lpszMenuName = NULL; wndClassEx.lpszClassName = _T("RdpRailWindow"); wndClassEx.hInstance = hInstance; wndClassEx.hIconSm = NULL; RegisterClassEx(&wndClassEx); railWindow->hWnd = CreateWindowExW( railWindow->dwExStyle, /* dwExStyle */ _T("RdpRailWindow"), /* lpClassName */ titleW, /* lpWindowName */ railWindow->dwStyle, /* dwStyle */ railWindow->x, /* x */ railWindow->y, /* y */ railWindow->width, /* nWidth */ railWindow->height, /* nHeight */ NULL, /* hWndParent */ NULL, /* hMenu */ hInstance, /* hInstance */ NULL /* lpParam */ ); SetWindowLongPtr(railWindow->hWnd, GWLP_USERDATA, (LONG_PTR) railWindow); HashTable_Add(wfc->railWindows, (void*)(UINT_PTR) orderInfo->windowId, (void*) railWindow); free(titleW); UpdateWindow(railWindow->hWnd); return TRUE; } else { railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows, (void*)(UINT_PTR) orderInfo->windowId); } if (!railWindow) return TRUE; if ((fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) || (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)) { if (fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) { railWindow->x = windowState->windowOffsetX; railWindow->y = windowState->windowOffsetY; } if (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) { railWindow->width = windowState->windowWidth; railWindow->height = windowState->windowHeight; } SetWindowPos(railWindow->hWnd, NULL, railWindow->x, railWindow->y, railWindow->width, railWindow->height, 0); } if (fieldFlags & WINDOW_ORDER_FIELD_OWNER) { } if (fieldFlags & WINDOW_ORDER_FIELD_STYLE) { railWindow->dwStyle = windowState->style; railWindow->dwStyle &= ~RAIL_DISABLED_WINDOW_STYLES; railWindow->dwExStyle = windowState->extendedStyle; railWindow->dwExStyle &= ~RAIL_DISABLED_EXTENDED_WINDOW_STYLES; SetWindowLongPtr(railWindow->hWnd, GWL_STYLE, (LONG) railWindow->dwStyle); SetWindowLongPtr(railWindow->hWnd, GWL_EXSTYLE, (LONG) railWindow->dwExStyle); } if (fieldFlags & WINDOW_ORDER_FIELD_SHOW) { ShowWindow(railWindow->hWnd, windowState->showState); } if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) { char* title = NULL; WCHAR* titleW = NULL; if (windowState->titleInfo.length == 0) { if (!(title = _strdup(""))) { WLog_ERR(TAG, "failed to duplicate empty window title string"); return FALSE; } } else if (ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string, windowState->titleInfo.length / 2, &title, 0, NULL, NULL) < 1) { WLog_ERR(TAG, "failed to convert window title"); return FALSE; } free(railWindow->title); railWindow->title = title; ConvertToUnicode(CP_UTF8, 0, railWindow->title, -1, &titleW, 0); SetWindowTextW(railWindow->hWnd, titleW); free(titleW); } if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) { } if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) { } if (fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) { } if (fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT) { } if (fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT) { } if (fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) { UINT32 index; HRGN hWndRect; HRGN hWndRects; RECTANGLE_16* rect; if (windowState->numWindowRects > 0) { rect = &(windowState->windowRects[0]); hWndRects = CreateRectRgn(rect->left, rect->top, rect->right, rect->bottom); for (index = 1; index < windowState->numWindowRects; index++) { rect = &(windowState->windowRects[index]); hWndRect = CreateRectRgn(rect->left, rect->top, rect->right, rect->bottom); CombineRgn(hWndRects, hWndRects, hWndRect, RGN_OR); DeleteObject(hWndRect); } SetWindowRgn(railWindow->hWnd, hWndRects, TRUE); DeleteObject(hWndRects); } } if (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) { } if (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) { } UpdateWindow(railWindow->hWnd); return TRUE; } static BOOL wf_rail_window_delete(rdpContext* context, WINDOW_ORDER_INFO* orderInfo) { wfRailWindow* railWindow = NULL; wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; WLog_DBG(TAG, "RailWindowDelete"); railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows, (void*)(UINT_PTR) orderInfo->windowId); if (!railWindow) return TRUE; HashTable_Remove(wfc->railWindows, (void*)(UINT_PTR) orderInfo->windowId); DestroyWindow(railWindow->hWnd); free(railWindow); return TRUE; } static BOOL wf_rail_window_icon(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, WINDOW_ICON_ORDER* windowIcon) { HDC hDC; int bpp; int width; int height; HICON hIcon; BOOL bigIcon; ICONINFO iconInfo; BITMAPINFO bitmapInfo; wfRailWindow* railWindow; BITMAPINFOHEADER* bitmapInfoHeader; wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; WLog_DBG(TAG, "RailWindowIcon"); PrintRailIconInfo(orderInfo, windowIcon->iconInfo); railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows, (void*)(UINT_PTR) orderInfo->windowId); if (!railWindow) return TRUE; bigIcon = (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_BIG) ? TRUE : FALSE; hDC = GetDC(railWindow->hWnd); iconInfo.fIcon = TRUE; iconInfo.xHotspot = 0; iconInfo.yHotspot = 0; ZeroMemory(&bitmapInfo, sizeof(BITMAPINFO)); bitmapInfoHeader = &(bitmapInfo.bmiHeader); bpp = windowIcon->iconInfo->bpp; width = windowIcon->iconInfo->width; height = windowIcon->iconInfo->height; bitmapInfoHeader->biSize = sizeof(BITMAPINFOHEADER); bitmapInfoHeader->biWidth = width; bitmapInfoHeader->biHeight = height; bitmapInfoHeader->biPlanes = 1; bitmapInfoHeader->biBitCount = bpp; bitmapInfoHeader->biCompression = 0; bitmapInfoHeader->biSizeImage = height * width * ((bpp + 7) / 8); bitmapInfoHeader->biXPelsPerMeter = width; bitmapInfoHeader->biYPelsPerMeter = height; bitmapInfoHeader->biClrUsed = 0; bitmapInfoHeader->biClrImportant = 0; iconInfo.hbmMask = CreateDIBitmap(hDC, bitmapInfoHeader, CBM_INIT, windowIcon->iconInfo->bitsMask, &bitmapInfo, DIB_RGB_COLORS); iconInfo.hbmColor = CreateDIBitmap(hDC, bitmapInfoHeader, CBM_INIT, windowIcon->iconInfo->bitsColor, &bitmapInfo, DIB_RGB_COLORS); hIcon = CreateIconIndirect(&iconInfo); if (hIcon) { WPARAM wParam; LPARAM lParam; wParam = (WPARAM) bigIcon ? ICON_BIG : ICON_SMALL; lParam = (LPARAM) hIcon; SendMessage(railWindow->hWnd, WM_SETICON, wParam, lParam); } ReleaseDC(NULL, hDC); if (windowIcon->iconInfo->cacheEntry != 0xFFFF) { /* icon should be cached */ } return TRUE; } static BOOL wf_rail_window_cached_icon(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, WINDOW_CACHED_ICON_ORDER* windowCachedIcon) { WLog_DBG(TAG, "RailWindowCachedIcon"); return TRUE; } static void wf_rail_notify_icon_common(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, NOTIFY_ICON_STATE_ORDER* notifyIconState) { if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION) { } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP) { } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP) { } if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE) { } if (orderInfo->fieldFlags & WINDOW_ORDER_ICON) { ICON_INFO* iconInfo = &(notifyIconState->icon); PrintRailIconInfo(orderInfo, iconInfo); } if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON) { } } static BOOL wf_rail_notify_icon_create(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, NOTIFY_ICON_STATE_ORDER* notifyIconState) { wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; WLog_DBG(TAG, "RailNotifyIconCreate"); wf_rail_notify_icon_common(context, orderInfo, notifyIconState); return TRUE; } static BOOL wf_rail_notify_icon_update(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, NOTIFY_ICON_STATE_ORDER* notifyIconState) { wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; WLog_DBG(TAG, "RailNotifyIconUpdate"); wf_rail_notify_icon_common(context, orderInfo, notifyIconState); return TRUE; } static BOOL wf_rail_notify_icon_delete(rdpContext* context, WINDOW_ORDER_INFO* orderInfo) { wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; WLog_DBG(TAG, "RailNotifyIconDelete"); return TRUE; } static BOOL wf_rail_monitored_desktop(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, MONITORED_DESKTOP_ORDER* monitoredDesktop) { wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; WLog_DBG(TAG, "RailMonitorDesktop"); return TRUE; } static BOOL wf_rail_non_monitored_desktop(rdpContext* context, WINDOW_ORDER_INFO* orderInfo) { wfContext* wfc = (wfContext*) context; RailClientContext* rail = wfc->rail; WLog_DBG(TAG, "RailNonMonitorDesktop"); return TRUE; } void wf_rail_register_update_callbacks(rdpUpdate* update) { rdpWindowUpdate* window = update->window; window->WindowCreate = wf_rail_window_common; window->WindowUpdate = wf_rail_window_common; window->WindowDelete = wf_rail_window_delete; window->WindowIcon = wf_rail_window_icon; window->WindowCachedIcon = wf_rail_window_cached_icon; window->NotifyIconCreate = wf_rail_notify_icon_create; window->NotifyIconUpdate = wf_rail_notify_icon_update; window->NotifyIconDelete = wf_rail_notify_icon_delete; window->MonitoredDesktop = wf_rail_monitored_desktop; window->NonMonitoredDesktop = wf_rail_non_monitored_desktop; } /* RemoteApp Virtual Channel Extension */ /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_execute_result(RailClientContext* context, RAIL_EXEC_RESULT_ORDER* execResult) { WLog_DBG(TAG, "RailServerExecuteResult: 0x%04X", execResult->rawResult); return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_system_param(RailClientContext* context, RAIL_SYSPARAM_ORDER* sysparam) { return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_handshake(RailClientContext* context, RAIL_HANDSHAKE_ORDER* handshake) { RAIL_EXEC_ORDER exec; RAIL_SYSPARAM_ORDER sysparam; RAIL_HANDSHAKE_ORDER clientHandshake; RAIL_CLIENT_STATUS_ORDER clientStatus; wfContext* wfc = (wfContext*) context->custom; rdpSettings* settings = wfc->context.settings; clientHandshake.buildNumber = 0x00001DB0; context->ClientHandshake(context, &clientHandshake); ZeroMemory(&clientStatus, sizeof(RAIL_CLIENT_STATUS_ORDER)); clientStatus.flags = RAIL_CLIENTSTATUS_ALLOWLOCALMOVESIZE; context->ClientInformation(context, &clientStatus); if (settings->RemoteAppLanguageBarSupported) { RAIL_LANGBAR_INFO_ORDER langBarInfo; langBarInfo.languageBarStatus = 0x00000008; /* TF_SFT_HIDDEN */ context->ClientLanguageBarInfo(context, &langBarInfo); } ZeroMemory(&sysparam, sizeof(RAIL_SYSPARAM_ORDER)); sysparam.params = 0; sysparam.params |= SPI_MASK_SET_HIGH_CONTRAST; sysparam.highContrast.colorScheme.string = NULL; sysparam.highContrast.colorScheme.length = 0; sysparam.highContrast.flags = 0x7E; sysparam.params |= SPI_MASK_SET_MOUSE_BUTTON_SWAP; sysparam.mouseButtonSwap = FALSE; sysparam.params |= SPI_MASK_SET_KEYBOARD_PREF; sysparam.keyboardPref = FALSE; sysparam.params |= SPI_MASK_SET_DRAG_FULL_WINDOWS; sysparam.dragFullWindows = FALSE; sysparam.params |= SPI_MASK_SET_KEYBOARD_CUES; sysparam.keyboardCues = FALSE; sysparam.params |= SPI_MASK_SET_WORK_AREA; sysparam.workArea.left = 0; sysparam.workArea.top = 0; sysparam.workArea.right = settings->DesktopWidth; sysparam.workArea.bottom = settings->DesktopHeight; sysparam.dragFullWindows = FALSE; context->ClientSystemParam(context, &sysparam); ZeroMemory(&exec, sizeof(RAIL_EXEC_ORDER)); exec.RemoteApplicationProgram = settings->RemoteApplicationProgram; exec.RemoteApplicationWorkingDir = settings->ShellWorkingDirectory; exec.RemoteApplicationArguments = settings->RemoteApplicationCmdLine; context->ClientExecute(context, &exec); return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_handshake_ex(RailClientContext* context, RAIL_HANDSHAKE_EX_ORDER* handshakeEx) { return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_local_move_size(RailClientContext* context, RAIL_LOCALMOVESIZE_ORDER* localMoveSize) { return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_min_max_info(RailClientContext* context, RAIL_MINMAXINFO_ORDER* minMaxInfo) { return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_language_bar_info(RailClientContext* context, RAIL_LANGBAR_INFO_ORDER* langBarInfo) { return CHANNEL_RC_OK; } /** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT wf_rail_server_get_appid_response(RailClientContext* context, RAIL_GET_APPID_RESP_ORDER* getAppIdResp) { return CHANNEL_RC_OK; } void wf_rail_invalidate_region(wfContext* wfc, REGION16* invalidRegion) { int index; int count; RECT updateRect; RECTANGLE_16 windowRect; ULONG_PTR* pKeys = NULL; wfRailWindow* railWindow; const RECTANGLE_16* extents; REGION16 windowInvalidRegion; region16_init(&windowInvalidRegion); count = HashTable_GetKeys(wfc->railWindows, &pKeys); for (index = 0; index < count; index++) { railWindow = (wfRailWindow*) HashTable_GetItemValue(wfc->railWindows, (void*) pKeys[index]); if (railWindow) { windowRect.left = railWindow->x; windowRect.top = railWindow->y; windowRect.right = railWindow->x + railWindow->width; windowRect.bottom = railWindow->y + railWindow->height; region16_clear(&windowInvalidRegion); region16_intersect_rect(&windowInvalidRegion, invalidRegion, &windowRect); if (!region16_is_empty(&windowInvalidRegion)) { extents = region16_extents(&windowInvalidRegion); updateRect.left = extents->left - railWindow->x; updateRect.top = extents->top - railWindow->y; updateRect.right = extents->right - railWindow->x; updateRect.bottom = extents->bottom - railWindow->y; InvalidateRect(railWindow->hWnd, &updateRect, FALSE); } } } region16_uninit(&windowInvalidRegion); } BOOL wf_rail_init(wfContext* wfc, RailClientContext* rail) { rdpContext* context = (rdpContext*) wfc; wfc->rail = rail; rail->custom = (void*) wfc; rail->ServerExecuteResult = wf_rail_server_execute_result; rail->ServerSystemParam = wf_rail_server_system_param; rail->ServerHandshake = wf_rail_server_handshake; rail->ServerHandshakeEx = wf_rail_server_handshake_ex; rail->ServerLocalMoveSize = wf_rail_server_local_move_size; rail->ServerMinMaxInfo = wf_rail_server_min_max_info; rail->ServerLanguageBarInfo = wf_rail_server_language_bar_info; rail->ServerGetAppIdResponse = wf_rail_server_get_appid_response; wf_rail_register_update_callbacks(context->update); wfc->railWindows = HashTable_New(TRUE); return (wfc->railWindows != NULL); } void wf_rail_uninit(wfContext* wfc, RailClientContext* rail) { wfc->rail = NULL; rail->custom = NULL; HashTable_Free(wfc->railWindows); }
realjiangms/FreeRDP
client/Windows/wf_rail.c
C
apache-2.0
30,600
'use strict'; var common = require('../common'); var assert = require('assert'); var net = require('net'); var expected_bad_connections = 1; var actual_bad_connections = 0; var host = '********'; host += host; host += host; host += host; host += host; host += host; function do_not_call() { throw new Error('This function should not have been called.'); } var socket = net.connect(42, host, do_not_call); socket.on('error', function(err) { assert.equal(err.code, 'ENOTFOUND'); actual_bad_connections++; }); socket.on('lookup', function(err, ip, type) { assert(err instanceof Error); assert.equal(err.code, 'ENOTFOUND'); assert.equal(ip, undefined); assert.equal(type, undefined); }); process.on('exit', function() { assert.equal(actual_bad_connections, expected_bad_connections); });
dreamllq/node
test/parallel/test-net-dns-error.js
JavaScript
apache-2.0
806
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle(".NET Micro Framework Toolbox - Telnet Server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NETMFToolbox.com")] [assembly: AssemblyProduct(".NET Micro Framework Toolbox - Telnet Server")] [assembly: AssemblyCopyright("Copyright © NETMFToolbox.com 2011-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("4.2.0.0")] [assembly: AssemblyFileVersion("4.2.0.0")]
JakeLardinois/NetMF.Toolbox
Framework/NET.TelnetServer/Properties/AssemblyInfo (4.2).cs
C#
apache-2.0
952
/* * This file is part of ATLAS. It is subject to the license terms in * the LICENSE file found in the top-level directory of this distribution. * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt) * You may not use this file except in compliance with the License. */ package de.dfki.asr.atlas.convert.collada; import de.dfki.asr.atlas.business.AssetManager; import de.dfki.asr.atlas.business.FolderHasher; import de.dfki.asr.atlas.convert.ExportContext; import de.dfki.asr.atlas.model.Blob; import de.dfki.asr.atlas.model.Color3D; import de.dfki.asr.atlas.model.Folder; import de.dfki.asr.atlas.model.Material; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import org.collada._2008._03.colladaschema.*; import org.collada._2008._03.colladaschema.FxCommonColorOrTextureType.Color; import org.collada._2008._03.colladaschema.FxCommonColorOrTextureType.Texture; import org.collada._2008._03.colladaschema.FxCommonFloatOrParamType.Float; import org.collada._2008._03.colladaschema.ImageType.InitFrom; import org.collada._2008._03.colladaschema.ProfileCommonType.Technique; import org.collada._2008._03.colladaschema.ProfileCommonType.Technique.Phong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ColladaMaterialExporter { private final Logger log = LoggerFactory.getLogger(ColladaMaterialExporter.class); private final AssetManager assetManager; private SimpleCOLLADADocument document; private String assetName; private ProfileCommonType profile; private EffectType effect; private Technique technique; private InstanceGeometryType geometryNode; private ExportContext context; public ColladaMaterialExporter(ExportContext context) { assetManager = context.getAssetManager(); this.context = context; } public void exportMaterial(String assetName, Folder materialFolder, InstanceGeometryType geometryNode, SimpleCOLLADADocument document, String materialSymbol) { String materialId = matrialId(materialFolder); this.geometryNode = geometryNode; this.assetName = assetName; this.document = document; if (!materialAlreadyInLibrary(materialId)) { createEnclosingTags(materialId); addPhongType(materialFolder); addMaterialToLibrary(materialFolder, materialId); addEffectToLibrary(); } addMaterialReferenceToGeometry(materialId, materialSymbol); } private void createEnclosingTags(String materialId) { effect = new EffectType(); profile = new ProfileCommonType(); technique = new Technique(); profile.setTechnique(technique); effect.setId(materialId + "-effect"); effect.getProfileCOMMONsAndProfileBRIDGEsAndProfileGLES2s().add(profile); } private void addMaterialReferenceToGeometry(String materialId, String materialSymbol) { BindMaterialType bind = new BindMaterialType(); BindMaterialType.TechniqueCommon matTechnique = new BindMaterialType.TechniqueCommon(); InstanceMaterialType matRef = new InstanceMaterialType(); matRef.setSymbol(materialSymbol); matRef.setTarget("#" + materialId); matTechnique.getInstanceMaterials().add(matRef); bind.setTechniqueCommon(matTechnique); geometryNode.setBindMaterial(bind); } private void addEffectToLibrary() { document.getLibrary(LibraryEffectsType.class).getEffects().add(effect); } private void addMaterialToLibrary(Folder materialFolder, String materialId) { MaterialType mat = new MaterialType(); mat.setId(materialId); mat.setName(materialFolder.getName()); InstanceEffectType instanceEffect = new InstanceEffectType(); instanceEffect.setUrl("#" + materialId + "-effect"); mat.setInstanceEffect(instanceEffect); document.getLibrary(LibraryMaterialsType.class).getMaterials().add(mat); } private void addPhongType(Folder materialFolder) { Phong phong = new Phong(); processMaterialBlobsForFolder(materialFolder, phong); for (Folder child : materialFolder.getChildFolders()) { processMaterialBlobsForFolder(child, phong); } technique.setPhong(phong); technique.setSid("common"); } private void processMaterialBlobsForFolder(Folder folder, Phong phong) { Map<String, String> blobs = folder.getBlobs(); Set<Map.Entry<String, String>> entries = blobs.entrySet(); for(Map.Entry<String, String> entry : entries){ switch (entry.getKey()) { case "material": fillPhongProperties(assetManager.getBlobOfAsset(assetName, entry.getValue()), phong); break; case "diffuse": case "specular": case "ambient": case "emissive": addTextureFromBlob(folder, assetManager.getBlobOfAsset(assetName, entry.getValue()), phong); break; default: log.warn("Encountered unknown blob in material " + entry.getKey()); } } } private void addTextureFromBlob(Folder blobFolder, Blob blob, Phong phong) { addImageToLibrary(blobFolder, blob); addSamplerToProfile(blob); FxCommonColorOrTextureType texType = new FxCommonColorOrTextureType(); Texture tex = new Texture(); tex.setTexcoord("TEX0"); //We currently only support one set of texcoords tex.setTexture("hash-"+blob.getHash() + "-sampler"); texType.setTexture(tex); switch(blobFolder.getTypeOfBlob(blob.getHash())) { case "diffuse": phong.setDiffuse(texType); break; case "ambient": phong.setAmbient(texType); break; case "emissive": phong.setEmission(texType); break; case "specular": phong.setSpecular(texType); break; } } private void addSamplerToProfile(Blob blob) { FxCommonNewparamType samplerParam = new FxCommonNewparamType(); samplerParam.setSid("hash-"+blob.getHash() + "-sampler"); FxSampler2DType samplerType = new FxSampler2DType(); InstanceImageType img = new InstanceImageType(); img.setUrl("#"+ "hash-" + blob.getHash()); samplerType.setInstanceImage(img); samplerParam.setSampler2D(samplerType); profile.getNewparams().add(samplerParam); } private void addImageToLibrary(Folder blobFolder, Blob blob) { ImageType img = new ImageType(); img.setId("hash-"+blob.getHash()); img.setName(blobFolder.getAttribute("filename")); InitFrom init = new InitFrom(); init.setRef(blobFolder.getAttribute("filename")); //TODO: Is the subtype always the same as the file ending? img.setInitFrom(init); document.getLibrary(LibraryImagesType.class).getImages().add(img); context.declareExternalReference(blobFolder); } private void fillPhongProperties(Blob blob, Phong phong) { Material mat = Material.fromInputStream(blob.getData()); phong.setAmbient(convertToColladaColorType(mat.ambient, mat.opacity)); phong.setEmission(convertToColladaColorType(mat.emissive, mat.opacity)); phong.setDiffuse(convertToColladaColorType(mat.diffuse, mat.opacity)); phong.setSpecular(convertToColladaColorType(mat.specular, mat.opacity)); phong.setShininess(convertToColladaFloatType(mat.shininess)); } private FxCommonFloatOrParamType convertToColladaFloatType(float floatIn) { FxCommonFloatOrParamType floatType = new FxCommonFloatOrParamType(); Float colladaFloat = new Float(); colladaFloat.setValue((double) floatIn); floatType.setFloat(colladaFloat); return floatType; } private FxCommonColorOrTextureType convertToColladaColorType(Color3D colorIn, float opacity) { FxCommonColorOrTextureType colorType = new FxCommonColorOrTextureType(); Color color = new Color(); List<Double> components = color.getValues(); components.add(new Double(colorIn.r)); components.add(new Double(colorIn.g)); components.add(new Double(colorIn.b)); components.add(new Double(opacity)); colorType.setColor(color); return colorType; } private boolean materialAlreadyInLibrary(final String materialId) { List<MaterialType> mats = document.getLibrary(LibraryMaterialsType.class).getMaterials(); MaterialType mat = CollectionUtils.find(mats, new Predicate<MaterialType>() { @Override public boolean evaluate(MaterialType t) { return t.getId().equals(materialId); } }); return (mat != null); } private String matrialId(Folder materialFolder) { return "hash-"+new FolderHasher(materialFolder).toString(); } }
dfki-asr/atlas-server
src/main/java/de/dfki/asr/atlas/convert/collada/ColladaMaterialExporter.java
Java
apache-2.0
8,169
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en-GB" xml:lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>nmod:comp</title> <link rel="root" href=""/> <!-- for JS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/> <link rel="stylesheet" type="text/css" href="../../css/style.css"/> <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/> <link rel="stylesheet" type="text/css" href="../../css/hint.css"/> <script type="text/javascript" src="../../lib/ext/head.load.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.2/anchor.min.js"></script> <script>document.addEventListener("DOMContentLoaded", function(event) {anchors.add();});</script> <!-- Set up this custom Google search at https://cse.google.com/cse/business/settings?cx=001145188882102106025:dl1mehhcgbo --> <!-- DZ 2021-01-22: I am temporarily hiding the search field to find out whether it slows down loading of the title page. <script> (function() { var cx = '001145188882102106025:dl1mehhcgbo'; var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true; gcse.src = 'https://cse.google.com/cse.js?cx=' + cx; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s); })(); </script> --> <!-- <link rel="shortcut icon" href="favicon.ico"/> --> </head> <body> <div id="main" class="center"> <div id="hp-header"> <table width="100%"><tr><td width="50%"> <span class="header-text"><a href="http://universaldependencies.org/#language-ug">home</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/edit/pages-source/_ug/dep/nmod-comp.md" target="#">edit page</a></span> <span class="header-text"><a href="https://github.com/universaldependencies/docs/issues">issue tracker</a></span> </td><td> <gcse:search></gcse:search> </td></tr></table> </div> <hr/> <div class="v2complete"> This page pertains to UD version 2. </div> <div id="content"> <noscript> <div id="noscript"> It appears that you have Javascript disabled. Please consider enabling Javascript for this page to see the visualizations. </div> </noscript> <!-- The content may include scripts and styles, hence we must load the shared libraries before the content. --> <script type="text/javascript"> console.time('loading libraries'); var root = '../../'; // filled in by jekyll head.js( // External libraries // DZ: Copied from embedding.html. I don't know which one is needed for what, so I'm currently keeping them all. root + 'lib/ext/jquery.min.js', root + 'lib/ext/jquery.svg.min.js', root + 'lib/ext/jquery.svgdom.min.js', root + 'lib/ext/jquery.timeago.js', root + 'lib/ext/jquery-ui.min.js', root + 'lib/ext/waypoints.min.js', root + 'lib/ext/jquery.address.min.js' ); </script> <h2><code>nmod:comp</code>: comparative modifier of an adjective or adverb</h2> <p>This subtype of <a href="">nmod</a> is used for marking comparative modifier of an <a href="tr-pos/Adj">adjective</a> or <a href="tr-pos/Adv">adverb</a>.</p> <p><strong>Note:</strong> Under UD v2 guidelines, the standard of comparison should be a subtype of <code class="language-plaintext highlighter-rouge">obl</code> rather than <code class="language-plaintext highlighter-rouge">nmod</code>. This should be fixed in the future.</p> <pre><code class="language-sdparse">Türkiye'den sıcak bir ülke \n A country warmer than Turkey nmod:comp(sıcak, Türkiye'den) </code></pre> <pre><code class="language-sdparse">Benden çok okudu . \n He\/she read more than me (more than I did) nmod:comp(çok, Benden) </code></pre> <!-- Interlanguage links updated St lis 3 20:58:58 CET 2021 --> <!-- "in other languages" links --> <hr/> nmod:comp in other languages: [<a href="../../kpv/dep/nmod-comp.html">kpv</a>] [<a href="../../mdf/dep/nmod-comp.html">mdf</a>] [<a href="../../myv/dep/nmod-comp.html">myv</a>] [<a href="../../tr/dep/nmod-comp.html">tr</a>] [<a href="../../ug/dep/nmod-comp.html">ug</a>] </div> <!-- support for embedded visualizations --> <script type="text/javascript"> var root = '../../'; // filled in by jekyll head.js( // We assume that external libraries such as jquery.min.js have already been loaded outside! // (See _layouts/base.html.) // brat helper modules root + 'lib/brat/configuration.js', root + 'lib/brat/util.js', root + 'lib/brat/annotation_log.js', root + 'lib/ext/webfont.js', // brat modules root + 'lib/brat/dispatcher.js', root + 'lib/brat/url_monitor.js', root + 'lib/brat/visualizer.js', // embedding configuration root + 'lib/local/config.js', // project-specific collection data root + 'lib/local/collections.js', // Annodoc root + 'lib/annodoc/annodoc.js', // NOTE: non-local libraries 'https://spyysalo.github.io/conllu.js/conllu.js' ); var webFontURLs = [ // root + 'static/fonts/Astloch-Bold.ttf', root + 'static/fonts/PT_Sans-Caption-Web-Regular.ttf', root + 'static/fonts/Liberation_Sans-Regular.ttf' ]; var setupTimeago = function() { jQuery("time.timeago").timeago(); }; head.ready(function() { setupTimeago(); // mark current collection (filled in by Jekyll) Collections.listing['_current'] = 'ug'; // perform all embedding and support functions Annodoc.activate(Config.bratCollData, Collections.listing); }); </script> <!-- google analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-55233688-1', 'auto'); ga('send', 'pageview'); </script> <div id="footer"> <p class="footer-text">&copy; 2014–2021 <a href="http://universaldependencies.org/introduction.html#contributors" style="color:gray">Universal Dependencies contributors</a>. Site powered by <a href="http://spyysalo.github.io/annodoc" style="color:gray">Annodoc</a> and <a href="http://brat.nlplab.org/" style="color:gray">brat</a></p>. </div> </div> </body> </html>
UniversalDependencies/universaldependencies.github.io
ug/dep/nmod-comp.html
HTML
apache-2.0
7,229
/* +----------------------------------------------------------------------+ | Zan | +----------------------------------------------------------------------+ | Copyright (c) 2016-2017 Zan Group <https://github.com/youzan/zan> | | Copyright (c) 2012-2016 Swoole Team <http://github.com/swoole> | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | zan@zanphp.io so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | | Zan Group <zan@zanphp.io> | +----------------------------------------------------------------------+ */ #include "swoole.h" #include "list.h" #include "swWork.h" #include "swSignal.h" #include "swServer.h" #include "swBaseOperator.h" #include "swProtocol/websocket.h" #include "swFactory.h" #include "swExecutor.h" static int swUDPThread_start(swServer *serv); static int swReactorThread_loop_dgram(swThreadParam *param); static int swTCPThread_start(swServer *serv); static int swReactorThread_loop_stream(swThreadParam *param); static void swHeartbeatThread_loop(swThreadParam *param); static int swReactorThread_onPipeWrite(swReactor *reactor, swEvent *ev); static int swReactorThread_onPipeReceive(swReactor *reactor, swEvent *ev); static int swReactorThread_onRead(swReactor *reactor, swEvent *ev); static int swReactorThread_onWrite(swReactor *reactor, swEvent *ev); static int swReactorThread_onPackage(swReactor *reactor, swEvent *event); static int swUDPThread_start(swServer *serv) { swThreadParam *param = NULL; pthread_t thread_id; swListenPort *ls = NULL; int index = serv->reactor_num; LL_FOREACH(serv->listen_list, ls) { param = SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swThreadParam)); if (swSocket_is_dgram(ls->type)) { if (ls->type == SW_SOCK_UDP) { serv->connection_list[ls->sock].info.addr.inet_v4.sin_port = htons(ls->port); } else { serv->connection_list[ls->sock].info.addr.inet_v6.sin6_port = htons(ls->port); } serv->connection_list[ls->sock].fd = ls->sock; serv->connection_list[ls->sock].socket_type = ls->type; serv->connection_list[ls->sock].object = ls; param->object = ls; param->pti = index++; if (pthread_create(&thread_id, NULL, (void * (*)(void *)) swReactorThread_loop_dgram, (void *) param) < 0) { swSysError("pthread_create[udp_listener] fail"); return SW_ERR; } ls->thread_id = thread_id; } } return SW_OK; } /** * udp listener thread */ static int swReactorThread_loop_dgram(swThreadParam *param) { swEvent event; swListenPort *ls = param->object; int fd = ls->sock; SwooleTG.factory_lock_target = 0; SwooleTG.factory_target_worker = -1; SwooleTG.id = param->pti; SwooleTG.type = SW_THREAD_UDP; swSignal_none(); //blocking swSetNonBlock(fd,0); event.fd = fd; while (SwooleG.running == 1) { swReactorThread_onPackage(NULL, &event); } pthread_exit(0); return 0; } static int swTCPThread_start(swServer *serv) { swListenPort *ls = NULL; LL_FOREACH(serv->listen_list, ls) { if (!swSocket_is_dgram(ls->type)) { SwooleG.main_reactor->add(SwooleG.main_reactor, ls->sock, SW_FD_LISTEN); } } #ifdef HAVE_PTHREAD_BARRIER //init thread barrier pthread_barrier_init(&serv->barrier, NULL, serv->reactor_num + 1); #endif swThreadParam *param = NULL; swReactorThread *thread = NULL; pthread_t pidt; int index = 0; //create reactor thread for (index = 0; index < serv->reactor_num; index++) { thread = &(serv->reactor_threads[index]); param = SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swThreadParam)); if (param == NULL) { swError("malloc failed"); return SW_ERR; } param->object = serv; param->pti = index; if (pthread_create(&pidt, NULL, (void * (*)(void *)) swReactorThread_loop_stream, (void *) param) < 0) { swError("pthread_create[tcp_reactor] failed. Error: %s[%d]", strerror(errno), errno); } else{ thread->thread_id = pidt; } } #ifdef HAVE_PTHREAD_BARRIER //wait reactor thread pthread_barrier_wait(&serv->barrier); #else SW_START_SLEEP; #endif return SW_OK; } /** * ReactorThread tcp reactor Loop */ static int swReactorThread_loop_stream(swThreadParam *param) { swServer *serv = SwooleG.serv; int reactor_id = param->pti; SwooleTG.factory_lock_target = 0; SwooleTG.factory_target_worker = -1; SwooleTG.id = reactor_id; SwooleTG.type = SW_THREAD_REACTOR; swReactorThread *thread = swServer_get_thread(serv, reactor_id); swReactor *reactor = &thread->reactor; swoole_cpu_setAffinity(reactor_id,serv); if (swReactor_init(reactor, SW_REACTOR_MAXEVENTS) < 0) { return SW_ERR; } swSignal_none(); reactor->ptr = serv; reactor->id = reactor_id; reactor->thread = 1; reactor->socket_list = serv->connection_list; reactor->max_socket = serv->max_connection; reactor->onFinish = NULL; reactor->onTimeout = NULL; reactor->close = swReactorThread_close; reactor->setHandle(reactor, SW_FD_CLOSE, swReactorThread_onClose); reactor->setHandle(reactor, SW_FD_PIPE | SW_EVENT_READ, swReactorThread_onPipeReceive); reactor->setHandle(reactor, SW_FD_PIPE | SW_EVENT_WRITE, swReactorThread_onPipeWrite); //set protocol function point swReactorThread_set_protocol(serv, reactor); if (serv->factory_mode == SW_MODE_PROCESS) { #ifdef SW_USE_RINGBUFFER int j = 0; thread->pipe_read_list = sw_calloc(serv->reactor_pipe_num, sizeof(int)); if (thread->pipe_read_list == NULL) { swSysError("thread->buffer_pipe create failed"); return SW_ERR; } #endif int index = 0, pipe_fd = -1; for (index = 0; index < serv->worker_num; index++) { if ((index % serv->reactor_num) == reactor_id) { pipe_fd = serv->workers[index].pipe_master; //for request swBuffer *buffer = swBuffer_new(sizeof(swEventData)); if (!buffer) { swError("create buffer failed."); break; } serv->connection_list[pipe_fd].in_buffer = buffer; //for response swSetNonBlock(pipe_fd,1); reactor->add(reactor, pipe_fd, SW_FD_PIPE); /** * mapping reactor_id and worker pipe */ serv->connection_list[pipe_fd].from_id = reactor_id; serv->connection_list[pipe_fd].fd = pipe_fd; serv->connection_list[pipe_fd].object = sw_malloc(sizeof(swLock)); /** * create pipe lock */ if (swMutex_create(serv->connection_list[pipe_fd].object, 0) < 0) { swError("create pipe mutex lock failed."); break; } #ifdef SW_USE_RINGBUFFER thread->pipe_read_list[j++] = pipe_fd; #endif } } } //wait other thread #ifdef HAVE_PTHREAD_BARRIER pthread_barrier_wait(&serv->barrier); #else SW_START_SLEEP; #endif struct timeval tm={5,0}; //main loop reactor->wait(reactor, &tm); //shutdown reactor->free(reactor); pthread_exit(0); return SW_OK; } static void swHeartbeatThread_start(swServer *serv) { swThreadParam *param; pthread_t thread_id; param = SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swThreadParam)); if (param == NULL) { swError("heartbeat_param malloc fail\n"); return; } param->object = serv; param->pti = 0; if (pthread_create(&thread_id, NULL, (void * (*)(void *)) swHeartbeatThread_loop, (void *) param) < 0) { swSysError("pthread_create[hbcheck] fail."); } SwooleG.heartbeat_pidt = thread_id; } static void swHeartbeatThread_loop(swThreadParam *param) { swSignal_none(); swServer *serv = param->object; swDataHead notify_ev; swConnection *conn; swReactor *reactor; int fd; int serv_max_fd; int serv_min_fd; int checktime; SwooleTG.type = SW_THREAD_HEARTBEAT; bzero(&notify_ev, sizeof(notify_ev)); notify_ev.type = SW_EVENT_CLOSE; while (SwooleG.running) { serv_max_fd = swServer_get_maxfd(serv); serv_min_fd = swServer_get_minfd(serv); checktime = (int) time(NULL) - serv->heartbeat_idle_time; //遍历到最大fd for (fd = serv_min_fd; fd <= serv_max_fd; fd++) { swTrace("check fd=%d", fd); conn = swServer_connection_get(serv, fd); if (conn != NULL && conn->active == 1 && conn->fdtype == SW_FD_TCP) { if (conn->protect || conn->last_time > checktime) { continue; } notify_ev.fd = fd; notify_ev.from_id = conn->from_id; conn->close_force = 1; conn->close_notify = 1; conn->close_wait = 1; if (serv->factory_mode != SW_MODE_PROCESS) { if (serv->factory_mode == SW_MODE_SINGLE) { reactor = SwooleG.main_reactor; } else { reactor = &serv->reactor_threads[conn->from_id].reactor; } } else { reactor = &serv->reactor_threads[conn->from_id].reactor; } //notify to reactor thread reactor->set(reactor, fd, SW_FD_TCP | SW_EVENT_WRITE); } } sleep(serv->heartbeat_check_interval); } pthread_exit(0); } #ifdef SW_USE_RINGBUFFER static sw_inline void swReactorThread_yield(swReactorThread *thread) { swEvent event; swServer *serv = SwooleG.serv; int i; for (i = 0; i < serv->reactor_pipe_num; i++) { event.fd = thread->pipe_read_list[i]; swReactorThread_onPipeReceive(&thread->reactor, &event); } swYield(); } static sw_inline void* swReactorThread_alloc(swReactorThread *thread, uint32_t size) { void *ptr = NULL; int try_count = 0; while (1) { ptr = thread->buffer_input->alloc(thread->buffer_input, size); if (ptr == NULL) { if (try_count > SW_RINGBUFFER_WARNING) { swWarn("memory pool is full. Wait memory collect. alloc(%d)", size); usleep(1000); try_count = 0; } try_count++; swReactorThread_yield(thread); continue; } break; } //debug("%p\n", ptr); return ptr; } #endif #ifdef SW_USE_OPENSSL static sw_inline int swReactorThread_verify_ssl_state(swListenPort *port, swConnection *conn) { if (conn->ssl_state == 0 && conn->ssl) { int ret = swSSL_accept(conn); if (ret == SW_READY) { if (port->ssl_client_cert_file) { swDispatchData task; ret = swSSL_get_client_certificate(conn->ssl, task.data.data, sizeof(task.data.data)); if (ret < 0) { goto no_client_cert; } else { swFactory *factory = &SwooleG.serv->factory; task.target_worker_id = -1; task.data.info.fd = conn->fd; task.data.info.type = SW_EVENT_CONNECT; task.data.info.from_id = conn->from_id; task.data.info.len = ret; if (factory->dispatch(factory, &task) < 0) { return SW_OK; } } } no_client_cert: if (SwooleG.serv->onConnect) { swServer_connection_ready(SwooleG.serv, conn->fd, conn->from_id); } return SW_OK; } else if (ret == SW_WAIT) { return SW_OK; } else { return SW_ERR; } } return SW_OK; } #endif /** * for udp */ static int swReactorThread_onPackage(swReactor *reactor, swEvent *event) { int fd = event->fd; int ret = -1; swServer *serv = SwooleG.serv; swConnection *server_sock = &serv->connection_list[fd]; swDispatchData task; swSocketAddress info; swDgramPacket pkt; swFactory *factory = &serv->factory; info.len = sizeof(info.addr); bzero(&task.data.info, sizeof(task.data.info)); task.data.info.from_fd = fd; task.data.info.from_id = SwooleTG.id; int socket_type = server_sock->socket_type; switch(socket_type) { case SW_SOCK_UDP6: task.data.info.type = SW_EVENT_UDP6; break; case SW_SOCK_UNIX_DGRAM: task.data.info.type = SW_EVENT_UNIX_DGRAM; break; case SW_SOCK_UDP: default: task.data.info.type = SW_EVENT_UDP; break; } char packet[SW_BUFFER_SIZE_UDP] = {0}; ret = recvfrom(fd, packet, SW_BUFFER_SIZE_UDP, 0, (struct sockaddr *) &info.addr, &info.len); if (ret > 0) { pkt.length = ret; //IPv4 if (socket_type == SW_SOCK_UDP) { pkt.port = ntohs(info.addr.inet_v4.sin_port); pkt.addr.v4.s_addr = info.addr.inet_v4.sin_addr.s_addr; task.data.info.fd = pkt.addr.v4.s_addr; } //IPv6 else if (socket_type == SW_SOCK_UDP6) { pkt.port = ntohs(info.addr.inet_v6.sin6_port); memcpy(&pkt.addr.v6, &info.addr.inet_v6.sin6_addr, sizeof(info.addr.inet_v6.sin6_addr)); memcpy(&task.data.info.fd, &info.addr.inet_v6.sin6_addr, sizeof(task.data.info.fd)); } //Unix Dgram else { pkt.addr.un.path_length = strlen(info.addr.un.sun_path) + 1; pkt.length += pkt.addr.un.path_length; pkt.port = 0; memcpy(&task.data.info.fd, info.addr.un.sun_path + pkt.addr.un.path_length - 6, sizeof(task.data.info.fd)); } task.target_worker_id = -1; uint32_t header_size = sizeof(pkt); //dgram header memcpy(task.data.data, &pkt, sizeof(pkt)); //unix dgram if (socket_type == SW_SOCK_UNIX_DGRAM ) { header_size += pkt.addr.un.path_length; memcpy(task.data.data + sizeof(pkt), info.addr.un.sun_path, pkt.addr.un.path_length); } //dgram body if (pkt.length > SW_BUFFER_SIZE - sizeof(pkt)) { task.data.info.len = SW_BUFFER_SIZE; } else { task.data.info.len = pkt.length + sizeof(pkt); } //dispatch packet header memcpy(task.data.data + header_size, packet, task.data.info.len - header_size); uint32_t send_n = pkt.length + header_size; uint32_t offset = 0; /** * lock target */ SwooleTG.factory_lock_target = 1; if (factory->dispatch(factory, &task) < 0) { return SW_ERR; } send_n -= task.data.info.len; if (send_n == 0) { /** * unlock */ SwooleTG.factory_target_worker = -1; SwooleTG.factory_lock_target = 0; return ret; } offset = SW_BUFFER_SIZE - header_size; while (send_n > 0) { task.data.info.len = send_n > SW_BUFFER_SIZE ? SW_BUFFER_SIZE : send_n; memcpy(task.data.data, packet + offset, task.data.info.len); send_n -= task.data.info.len; offset += task.data.info.len; if (factory->dispatch(factory, &task) < 0) { break; } } /** * unlock */ SwooleTG.factory_target_worker = -1; SwooleTG.factory_lock_target = 0; } return ret; } /** * [ReactorThread] worker pipe can write. */ static int swReactorThread_onPipeWrite(swReactor *reactor, swEvent *ev) { int ret = 0; swBuffer_trunk *trunk = NULL; swEventData *send_data = NULL; swConnection *conn = NULL; swServer *serv = reactor->ptr; swBuffer *buffer = serv->connection_list[ev->fd].in_buffer; swLock *lock = serv->connection_list[ev->fd].object; //lock thread lock->lock(lock); while (!swBuffer_empty(buffer)) { trunk = swBuffer_get_trunk(buffer); send_data = trunk->store.ptr; //server active close, discard data. if (swEventData_is_stream(send_data->info.type)) { //send_data->info.fd is session_id conn = swServer_connection_verify(serv, send_data->info.fd); if (conn == NULL || conn->closed) { #ifdef SW_USE_RINGBUFFER swReactorThread *thread = swServer_get_thread(SwooleG.serv, SwooleTG.id); swPackage package; memcpy(&package, send_data->data, sizeof(package)); thread->buffer_input->free(thread->buffer_input, package.data); #endif if (conn && conn->closed) { swNotice("Session#%d is closed by server.", send_data->info.fd); } swBuffer_pop_trunk(buffer, trunk); continue; } } ret = write(ev->fd, trunk->store.ptr, trunk->length); if (ret < 0) { //release lock lock->unlock(lock); #ifdef HAVE_KQUEUE return (errno == EAGAIN || errno == ENOBUFS) ? SW_OK : SW_ERR; #else return errno == EAGAIN ? SW_OK : SW_ERR; #endif } else { swBuffer_pop_trunk(buffer, trunk); } } //remove EPOLLOUT event if (swBuffer_empty(buffer)) { if (SwooleG.serv->connection_list[ev->fd].from_id == SwooleTG.id) { ret = reactor->set(reactor, ev->fd, SW_FD_PIPE | SW_EVENT_READ); } else { ret = reactor->del(reactor, ev->fd); } if (ret < 0) { swSysError("reactor->set(%d) failed.", ev->fd); } } //release lock lock->unlock(lock); return SW_OK; } /** * receive data from worker process pipe */ static int swReactorThread_onPipeReceive(swReactor *reactor, swEvent *ev) { int n; swEventData resp; swSendData _send; swPackage_response pkg_resp; swWorker *worker; #ifdef SW_REACTOR_RECV_AGAIN while (1) #endif { n = read(ev->fd, &resp, sizeof(resp)); if (n > 0) { memcpy(&_send.info, &resp.info, sizeof(resp.info)); if (_send.info.type == SW_EVENT_DENY_REQUEST) { swServer* serv = SwooleG.serv; int target_worker_id = _send.info.worker_id; serv->workers[target_worker_id].deny_request = 1; swNotice("[Master] set worker exit.[work_id=%d]", target_worker_id); return SW_OK; } else if(_send.info.type == SW_EVENT_DENY_EXIT) { swServer* serv = SwooleG.serv; int target_worker_id = _send.info.worker_id; serv->workers[target_worker_id].deny_request = 0; swNotice("[Master] set worker idle.[work_id=%d]", target_worker_id); return SW_OK; } if (_send.info.from_fd == SW_RESPONSE_SMALL) { _send.data = resp.data; _send.length = resp.info.len; swReactorThread_send(&_send); } else { memcpy(&pkg_resp, resp.data, sizeof(pkg_resp)); worker = swServer_get_worker(SwooleG.serv, pkg_resp.worker_id); _send.data = worker->send_shm; _send.length = pkg_resp.length; swReactorThread_send(&_send); worker->lock.unlock(&worker->lock); } } else if (errno == EAGAIN) { return SW_OK; } else { swSysError("read(worker_pipe) failed."); return SW_ERR; } } return SW_OK; } static int swReactorThread_onRead(swReactor *reactor, swEvent *event) { if (event->socket->from_fd == 0) { return SW_OK; } swServer *serv = reactor->ptr; swListenPort *port = swServer_get_port(serv, event->fd); #ifdef SW_USE_OPENSSL if (swReactorThread_verify_ssl_state(port, event->socket) < 0) { return swReactorThread_close(reactor, event->fd); } #endif event->socket->last_time = SwooleGS->now; return port->onRead(reactor, port, event); } static int swReactorThread_onWrite(swReactor *reactor, swEvent *ev) { int ret; swServer *serv = SwooleG.serv; int fd = ev->fd; if (serv->factory_mode == SW_MODE_PROCESS) { assert(fd % serv->reactor_num == reactor->id); assert(fd % serv->reactor_num == SwooleTG.id); } swConnection *conn = swServer_connection_get(serv, fd); if (conn->active == 0) { return SW_OK; } //notify worker process else if (conn->connect_notify) { swServer_connection_ready(serv, fd, reactor->id); conn->connect_notify = 0; return reactor->set(reactor, fd, SW_EVENT_TCP | SW_EVENT_READ); } else if (conn->close_notify) { swDataHead close_event; close_event.type = SW_EVENT_CLOSE; close_event.from_id = reactor->id; close_event.fd = fd; if (serv->factory.notify(&serv->factory, &close_event) < 0) { swWarn("send notification [fd=%d] failed.", fd); } conn->close_notify = 0; return SW_OK; } else if (serv->disable_notify && conn->close_force) { return swReactorThread_close(reactor, fd); } swBuffer_trunk *chunk = NULL; while (!swBuffer_empty(conn->out_buffer)) { chunk = swBuffer_get_trunk(conn->out_buffer); if (chunk->type == SW_CHUNK_CLOSE) { close_fd: reactor->close(reactor, fd); return SW_OK; } else if (chunk->type == SW_CHUNK_SENDFILE) { ret = swConnection_onSendfile(conn, chunk); } else { ret = swConnection_buffer_send(conn); } if (ret < 0) { if (conn->close_wait) { goto close_fd; } else if (conn->send_wait) { return SW_OK; } } } if (conn->overflow && conn->out_buffer->length < SwooleG.socket_buffer_size) { conn->overflow = 0; } //remove EPOLLOUT event if (swBuffer_empty(conn->out_buffer)) { reactor->set(reactor, fd, SW_FD_TCP | SW_EVENT_READ); } return SW_OK; } /** * close connection */ int swReactorThread_close(swReactor *reactor, int fd) { swServer *serv = SwooleG.serv; swConnection *conn = swServer_connection_get(serv, fd); if (conn == NULL) { swWarn("[Reactor]connection not found. fd=%d|max_fd=%d", fd, swServer_get_maxfd(serv)); return SW_ERR; } if (!conn->removed) { reactor->del(reactor, fd); } if (serv->factory_mode == SW_MODE_PROCESS) { assert(fd % serv->reactor_num == reactor->id); assert(fd % serv->reactor_num == SwooleTG.id); } sw_stats_incr(&SwooleStats->close_count); sw_stats_decr(&SwooleStats->connection_num); swTrace("Close Event.fd=%d|from=%d", fd, reactor->id); swListenPort *port = swServer_get_port(serv, fd); //clear output buffer if (port->open_eof_check || port->open_length_check || port->open_mqtt_protocol) { if (conn->object) { swServer_free_buffer(serv, fd); conn->object = NULL; } } else if (port->open_http_protocol) { if (conn->object) { if (conn->http_upgrade) { swServer_free_buffer(serv, fd); conn->websocket_status = 0; } else { swHttpRequest_free(conn); } } } #ifdef SW_REACTOR_USE_SESSION swSession *session = swServer_get_session(serv, conn->session_id); session->fd = 0; #endif /** * reset maxfd, for connection_list */ if (fd == swServer_get_maxfd(serv)) { SwooleGS->lock.lock(&SwooleGS->lock); int find_max_fd = fd - 1; swTrace("set_maxfd=%d|close_fd=%d\n", find_max_fd, fd); /** * Find the new max_fd */ for (; serv->connection_list[find_max_fd].active == 0 && find_max_fd > swServer_get_minfd(serv); find_max_fd--) ; swServer_set_maxfd(serv, find_max_fd); SwooleGS->lock.unlock(&SwooleGS->lock); } return swReactor_close(reactor, fd); } /** * close the connection */ int swReactorThread_onClose(swReactor *reactor, swEvent *event) { swServer *serv = reactor->ptr; if (serv->factory_mode == SW_MODE_SINGLE) { return swReactorProcess_onClose(reactor, event); } int fd = event->fd; swDataHead notify_ev; bzero(&notify_ev, sizeof(notify_ev)); assert(fd % serv->reactor_num == reactor->id); assert(fd % serv->reactor_num == SwooleTG.id); notify_ev.from_id = reactor->id; notify_ev.fd = fd; notify_ev.type = SW_EVENT_CLOSE; swConnection *conn = swServer_connection_get(SwooleG.serv, fd); if (conn == NULL || conn->active == 0) { return SW_ERR; } else if (serv->disable_notify) { swReactorThread_close(reactor, fd); return SW_OK; } else if (reactor->del(reactor, fd) == 0) { return SwooleG.factory->notify(SwooleG.factory, &notify_ev); } else { return SW_ERR; } } int swReactorThread_send2worker(void *data, int len, uint16_t target_worker_id) { swServer *serv = SwooleG.serv; int ret = -1; swWorker *worker = &(serv->workers[target_worker_id]); //reactor thread if (SwooleTG.type == SW_THREAD_REACTOR) { int pipe_fd = worker->pipe_master; int thread_id = serv->connection_list[pipe_fd].from_id; swReactorThread *thread = swServer_get_thread(serv, thread_id); swLock *lock = serv->connection_list[pipe_fd].object; //lock thread lock->lock(lock); swBuffer *buffer = serv->connection_list[pipe_fd].in_buffer; if (swBuffer_empty(buffer)) { ret = write(pipe_fd, (void *) data, len); #ifdef HAVE_KQUEUE if (ret < 0 && (errno == EAGAIN || errno == ENOBUFS)) #else if (ret < 0 && errno == EAGAIN) #endif { if (thread->reactor.set(&thread->reactor, pipe_fd, SW_FD_PIPE | SW_EVENT_READ | SW_EVENT_WRITE) < 0) { swSysError("reactor->set(%d, PIPE | READ | WRITE) failed.", pipe_fd); } goto append_pipe_buffer; } } else { append_pipe_buffer: if (buffer->length > serv->pipe_buffer_size) { swYield(); swSocket_wait(pipe_fd, SW_SOCKET_OVERFLOW_WAIT, SW_EVENT_WRITE); } if (swBuffer_append(buffer, data, len) < 0) { swWarn("append to pipe_buffer failed."); ret = SW_ERR; } else { ret = SW_OK; } } //release thread lock lock->unlock(lock); } //master/udp thread else { int pipe_fd = worker->pipe_master; ret = swSocket_write_blocking(pipe_fd, data, len); } return ret; } /** * send to client or append to out_buffer */ int swReactorThread_send(swSendData *_send) { swServer *serv = SwooleG.serv; uint32_t session_id = _send->info.fd; void *_send_data = _send->data; uint32_t _send_length = _send->length; swConnection *conn = swServer_connection_verify(serv, session_id); if (!conn) { if (_send->info.type == SW_EVENT_TCP) { swNotice("send %d byte failed, session#%d does not exist.", _send_length, session_id); } else { swNotice("send event$[%d] failed, session#%d does not exist.", _send->info.type, session_id); } return SW_ERR; } int fd = conn->fd; swReactor *reactor = (serv->factory_mode == SW_MODE_SINGLE)? &(serv->reactor_threads[0].reactor):&(serv->reactor_threads[conn->from_id].reactor); /** * Reset send buffer, Immediately close the connection. */ if (_send->info.type == SW_EVENT_CLOSE && conn->close_reset) { goto close_fd; } if (swBuffer_empty(conn->out_buffer)) { /** * close connection. */ if (_send->info.type == SW_EVENT_CLOSE) { close_fd: reactor->close(reactor, fd); return SW_OK; } #ifdef SW_REACTOR_SYNC_SEND //Direct send if (_send->info.type != SW_EVENT_SENDFILE) { if (!conn->direct_send) { goto buffer_send; } int n; direct_send: n = swConnection_send(conn, _send_data, _send_length, 0); if (n == _send_length) { return SW_OK; } else if (n > 0) { _send_data += n; _send_length -= n; goto buffer_send; } else if (errno == EINTR) { goto direct_send; } else { goto buffer_send; } } #endif //buffer send else { #ifdef SW_REACTOR_SYNC_SEND buffer_send: #endif if (!conn->out_buffer) { conn->out_buffer = swBuffer_new(SW_BUFFER_SIZE); if (conn->out_buffer == NULL) { return SW_ERR; } } } } swBuffer_trunk *trunk; //close connection if (_send->info.type == SW_EVENT_CLOSE) { trunk = swBuffer_new_trunk(conn->out_buffer, SW_CHUNK_CLOSE, 0); trunk->store.data.val1 = _send->info.type; } //sendfile to client else if (_send->info.type == SW_EVENT_SENDFILE) { swConnection_sendfile_async(conn, _send_data); } //send data else { //connection is closed if (conn->removed) { swNotice("connection#%d is closed by client.", fd); return SW_ERR; } //connection output buffer overflow if (conn->out_buffer->length >= serv->buffer_output_size) { swNotice("connection#%d output buffer overflow.", fd); conn->overflow = 1; } int _length = _send_length; void* _pos = _send_data; int _n; //buffer enQueue while (_length > 0) { _n = _length >= SW_BUFFER_SIZE_BIG ? SW_BUFFER_SIZE_BIG : _length; swBuffer_append(conn->out_buffer, _pos, _n); _pos += _n; _length -= _n; } } //listen EPOLLOUT event if (reactor->set(reactor, fd, SW_EVENT_TCP | SW_EVENT_WRITE | SW_EVENT_READ) < 0 && (errno == EBADF || errno == ENOENT)) { goto close_fd; } return SW_OK; } void swReactorThread_set_protocol(swServer *serv, swReactor *reactor) { //UDP Packet reactor->setHandle(reactor, SW_FD_UDP, swReactorThread_onPackage); //Write reactor->setHandle(reactor, SW_FD_TCP | SW_EVENT_WRITE, swReactorThread_onWrite); //Read reactor->setHandle(reactor, SW_FD_TCP | SW_EVENT_READ, swReactorThread_onRead); swListenPort *ls = NULL; //listen the all tcp port LL_FOREACH(serv->listen_list, ls) { if (!swSocket_is_dgram(ls->type)) { swPort_set_protocol(ls); } } } int swReactorThread_create(swServer *serv) { ///init reactor thread pool serv->reactor_threads = SwooleG.memory_pool->alloc(SwooleG.memory_pool, (serv->reactor_num * sizeof(swReactorThread))); if (!serv->reactor_threads) { swError("calloc[reactor_threads] fail.alloc_size=%d", (int )(serv->reactor_num * sizeof(swReactorThread))); return SW_ERR; } /** * alloc the memory for connection_list */ serv->connection_list = (serv->factory_mode == SW_MODE_PROCESS)? sw_shm_calloc(serv->max_connection, sizeof(swConnection)): sw_calloc(serv->max_connection, sizeof(swConnection)); if (!serv->connection_list) { swError("calloc[1] failed"); return SW_ERR; } //create factry object int ret = (serv->factory_mode == SW_MODE_THREAD)? swFactoryThread_create(&(serv->factory), serv->worker_num): ((serv->factory_mode == SW_MODE_PROCESS)? swFactoryProcess_create(&(serv->factory), serv->worker_num): swFactory_create(&(serv->factory))); if (ret < 0) { swError("create factory failed"); } return ret < 0? SW_ERR:SW_OK; } /** * proxy模式 * 在单独的n个线程中接受维持TCP连接 */ int swReactorThread_start(swServer *serv) { swReactor *main_reactor = SwooleG.memory_pool->alloc(SwooleG.memory_pool, sizeof(swReactor)); if (swReactor_init(main_reactor, SW_REACTOR_MAXEVENTS) < 0) { swError("Reactor create error"); return SW_ERR; } /** * master thread loop */ SwooleTG.type = SW_THREAD_MASTER; SwooleTG.factory_target_worker = -1; SwooleTG.factory_lock_target = 0; SwooleTG.id = 0; SwooleTG.update_time = 1; SwooleG.main_reactor = main_reactor; SwooleG.pid = getpid(); SwooleG.process_type = SW_PROCESS_MASTER; main_reactor->thread = 1; main_reactor->socket_list = serv->connection_list; main_reactor->disable_accept = 0; main_reactor->enable_accept = swServer_enable_accept; #ifdef HAVE_SIGNALFD if (SwooleG.use_signalfd) { swSignalfd_setup(main_reactor); } #endif swServer_store_listen_socket(serv); //listen UDP, 一个端口一个线程监听 if (serv->have_udp_sock == 1 && swUDPThread_start(serv) < 0) { swError("udp thread start failed."); return SW_ERR; } #ifdef HAVE_REUSEPORT SwooleG.reuse_port = 0; #endif //listen TCP if (serv->have_tcp_sock == 1 && swTCPThread_start(serv) < 0) { swError("tcp thread start failed."); return SW_ERR; } /** * heartbeat thread */ if (serv->heartbeat_check_interval >= 1 && serv->heartbeat_check_interval <= serv->heartbeat_idle_time) { swTrace("hb timer start, time: %d live time:%d", serv->heartbeat_check_interval, serv->heartbeat_idle_time); swHeartbeatThread_start(serv); } /** * set a special id */ main_reactor->id = serv->reactor_num; main_reactor->ptr = serv; main_reactor->setHandle(main_reactor, SW_FD_LISTEN, swServer_master_onAccept); if (serv->onStart) { serv->onStart(serv); } struct timeval tmo; tmo.tv_sec = 1; //for seconds timer tmo.tv_usec = 0; return main_reactor->wait(main_reactor, &tmo);; } int swReactorThread_dispatch(swConnection *conn, char *data, uint32_t length) { swFactory *factory = SwooleG.factory; swDispatchData task; memset(&task, 0, sizeof(task)); task.data.info.fd = conn->fd; task.data.info.from_id = conn->from_id; swTrace("send string package, size=%u bytes.", length); #ifdef SW_USE_RINGBUFFER swServer *serv = SwooleG.serv; swReactorThread *thread = swServer_get_thread(serv, SwooleTG.id); int target_worker_id = swServer_worker_schedule(serv, conn->fd); swPackage package; package.length = length; package.data = swReactorThread_alloc(thread, package.length); task.data.info.type = SW_EVENT_PACKAGE; task.data.info.len = sizeof(package); task.target_worker_id = target_worker_id; //swoole_dump_bin(package.data, 's', buffer->length); memcpy(package.data, data, package.length); memcpy(task.data.data, &package, sizeof(package)); //dispatch failed, free the memory. if (factory->dispatch(factory, &task) < 0) { thread->buffer_input->free(thread->buffer_input, package.data); } else { return SW_OK; } #else task.data.info.type = SW_EVENT_PACKAGE_START; task.target_worker_id = -1; /** * lock target */ SwooleTG.factory_lock_target = 1; size_t send_n = length; size_t offset = 0; while (send_n > 0) { if (send_n > SW_BUFFER_SIZE) { task.data.info.len = SW_BUFFER_SIZE; } else { task.data.info.type = SW_EVENT_PACKAGE_END; task.data.info.len = send_n; } task.data.info.fd = conn->fd; memcpy(task.data.data, data + offset, task.data.info.len); send_n -= task.data.info.len; offset += task.data.info.len; swTrace("dispatch, type=%d|len=%d\n", task.data.info.type, task.data.info.len); if (factory->dispatch(factory, &task) < 0) { break; } } /** * unlock */ SwooleTG.factory_target_worker = -1; SwooleTG.factory_lock_target = 0; #endif return SW_OK; } void swReactorThread_free(swServer *serv) { if (SwooleGS->start == 0) { return; } if (serv->have_tcp_sock == 1) { int i = 0; swReactorThread *thread = NULL; for (i = 0; i < serv->reactor_num; i++) { thread = &(serv->reactor_threads[i]); thread->reactor.running = 0; SW_START_SLEEP; if (thread->thread_id && pthread_cancel(thread->thread_id) != 0) { swSysError("pthread_cancel(%ld) failed.",(long)thread->thread_id); } //wait thread if (thread->thread_id && pthread_join(thread->thread_id, NULL) != 0) { swSysError("pthread_join(%ld) failed.", (long)thread->thread_id); } //release the lock SwooleGS->lock.unlock(&SwooleGS->lock); #ifdef SW_USE_RINGBUFFER thread->buffer_input->destroy(thread->buffer_input); #endif } } if (serv->have_udp_sock == 1) { swListenPort *ls; LL_FOREACH(serv->listen_list, ls) { if (swSocket_is_dgram(ls->type)) { if (ls->thread_id && pthread_cancel(ls->thread_id) != 0) { swSysError("pthread_cancel(%ld) failed.",(long)ls->thread_id); } if (ls->thread_id && pthread_join(ls->thread_id, NULL) != 0) { swSysError("pthread_join(%ld) failed.", (long)ls->thread_id); } } } } }
springleng/zan
zan-extension/src/network/ReactorThread.c
C
apache-2.0
40,783
# Copyright 2014 Open Source Robotics Foundation, 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. """ flowlabels are abbreviations that can be used to identify a flow. Flows do not have a single unique attribute, which makes them difficult to identify. flows solve that problem. flowlabels have 2 parts: origin node index destination node index Example: flowlabel 1_2 means the flow from the node at index 1 to the node at index 2 """ import re def parse_flowlabel(flowlabel): """ Parses a flowlabel into a tuple """ result = re.findall("(^\d+)(_)(\d+$)", flowlabel) if len(result) == 0: raise Exception("Invalid flowlabel %s"%flowlabel) return (int(result[0][0]), int(result[0][2])) def gen_flowlabel(origin_index, destination_index): """ generate a flowlabel """ return "%d_%d"%(origin_index, destination_index)
viccro/diarc
fabrik/flowlabel.py
Python
apache-2.0
1,392
#include <SFML/System.hpp> #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #ifndef LIGHTH #define LIGHTH struct Wall { Wall (sf::Vector2f p1,sf::Vector2f p2) { pt1=p1; pt2=p2; } // Pt1 et Pt2 sont les deux extrémités du mur sf::Vector2f pt1; sf::Vector2f pt2; }; // Wall_Entity est une variable qui permet de représenter dans le programme un mur struct Wall_Entity { Wall_Entity (int id) { m_ID=id; } int ID() { return m_ID; } private: int m_ID; }; // Light_Entity est une variable qui permet de représenter dans le programme une lumière struct Light_Entity { Light_Entity (){m_Dynamic=false,m_ID=0;} Light_Entity (int id,bool d) { m_ID=id; m_Dynamic=d; } int ID() { return m_ID; } bool Dynamic() { return m_Dynamic; } private: int m_ID; bool m_Dynamic; }; class Light { public : // Constructeur et destructeur Light(); Light(sf::Vector2f position, float intensity, float radius, int quality, sf::Color color); ~Light(); // Afficher la lumière void Draw(sf::RenderTarget *App); // Calculer la lumière virtual void Generate(std::vector <Wall> &m_wall); // Ajouter un triangle à la lumière, en effet, les lumières sont composée de triangles void AddTriangle(sf::Vector2f pt1,sf::Vector2f pt2, int minimum_wall,std::vector <Wall> &m_wall); // Changer différents attributs de la lumière void SetIntensity(float); void SetRadius(float); void SetQuality(int); void SetColor(sf::Color); void SetPosition(sf::Vector2f); virtual void SetOtherParameter(unsigned, float); // Retourner différents attributs de la lumière float GetIntensity(); float GetRadius(); int GetQuality(); sf::Color GetColor(); sf::Vector2f GetPosition(); // Une petite bool pour savoir si la lumière est allumée ou éteinte bool m_actif; protected : //Position à l'écran sf::Vector2f m_position; //Intensité, gère la transparence ( entre 0 et 255 ) float m_intensity; //Rayon de la lumière float m_radius; //Couleur de la lumière sf::Color m_color; //Tableau dynamique de Shape, ce sont ces shapes de type triangle qui compose la lumière std::vector <sf::VertexArray> m_shape; private : //Qualité de la lumière, c'est à dire le nombre de triangles par défaut qui la compose. int m_quality; }; #endif
anthonycorbacho/SFML-light
header/Light.h
C
apache-2.0
2,598
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.6.0_32) on Mon Oct 13 19:43:27 PKT 2014 --> <title>Objects</title> <meta name="date" content="2014-10-13"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Objects"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Objects.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/linq4android/dependencies/java7/Arrays.html" title="class in org.linq4android.dependencies.java7"><span class="strong">PREV CLASS</span></a></li> <li>NEXT CLASS</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/linq4android/dependencies/java7/Objects.html" target="_top">FRAMES</a></li> <li><a href="Objects.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>SUMMARY:&nbsp;</li> <li>NESTED&nbsp;|&nbsp;</li> <li>FIELD&nbsp;|&nbsp;</li> <li>CONSTR&nbsp;|&nbsp;</li> <li><a href="#method_summary">METHOD</a></li> </ul> <ul class="subNavList"> <li>DETAIL:&nbsp;</li> <li>FIELD&nbsp;|&nbsp;</li> <li>CONSTR&nbsp;|&nbsp;</li> <li><a href="#method_detail">METHOD</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <p class="subTitle">org.linq4android.dependencies.java7</p> <h2 title="Class Objects" class="title">Class Objects</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.linq4android.dependencies.java7.Objects</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <strong>Objects</strong> extends java.lang.Object</pre> <div class="block">This class consists of <code>static</code> utility methods for operating on objects. These utilities include <code>null</code>-safe or <code>null</code>-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.</div> <dl><dt><span class="strong">Since:</span></dt> <dd>1.7</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static &lt;T&gt;&nbsp;int</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#compare(T, T, java.util.Comparator)">compare</a></strong>(T&nbsp;a, T&nbsp;b, java.util.Comparator&lt;? super T&gt;&nbsp;c)</code> <div class="block">Returns 0 if the arguments are identical and <code>c.compare(a, b)</code> otherwise.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#deepEquals(java.lang.Object, java.lang.Object)">deepEquals</a></strong>(java.lang.Object&nbsp;a, java.lang.Object&nbsp;b)</code> <div class="block">Returns <code>true</code> if the arguments are deeply equal to each other and <code>false</code> otherwise.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#equals(java.lang.Object, java.lang.Object)">equals</a></strong>(java.lang.Object&nbsp;a, java.lang.Object&nbsp;b)</code> <div class="block">Returns <code>true</code> if the arguments are equal to each other and <code>false</code> otherwise.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#hash(java.lang.Object...)">hash</a></strong>(java.lang.Object...&nbsp;values)</code> <div class="block">Generates a hash code for a sequence of input values.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#hashCode(java.lang.Object)">hashCode</a></strong>(java.lang.Object&nbsp;o)</code> <div class="block">Returns the hash code of a non-<code>null</code> argument and 0 for a <code>null</code> argument.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static &lt;T&gt;&nbsp;T</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#requireNonNull(T)">requireNonNull</a></strong>(T&nbsp;obj)</code> <div class="block">Checks that the specified object reference is not <code>null</code>.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static &lt;T&gt;&nbsp;T</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#requireNonNull(T, java.lang.String)">requireNonNull</a></strong>(T&nbsp;obj, java.lang.String&nbsp;message)</code> <div class="block">Checks that the specified object reference is not <code>null</code> and throws a customized <code>NullPointerException</code> if it is.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#toString(java.lang.Object)">toString</a></strong>(java.lang.Object&nbsp;o)</code> <div class="block">Returns the result of calling <code>toString</code> for a non-<code>null</code> argument and <code>"null"</code> for a <code>null</code> argument.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../org/linq4android/dependencies/java7/Objects.html#toString(java.lang.Object, java.lang.String)">toString</a></strong>(java.lang.Object&nbsp;o, java.lang.String&nbsp;nullDefault)</code> <div class="block">Returns the result of calling <code>toString</code> on the first argument if the first argument is not <code>null</code> and returns the second argument otherwise.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="equals(java.lang.Object, java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public static&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;a, java.lang.Object&nbsp;b)</pre> <div class="block">Returns <code>true</code> if the arguments are equal to each other and <code>false</code> otherwise. Consequently, if both arguments are <code>null</code>, <code>true</code> is returned and if exactly one argument is <code>null</code>, <code>false</code> is returned. Otherwise, equality is determined by using the <code>equals</code> method of the first argument.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>a</code> - an object</dd><dd><code>b</code> - an object to be compared with <code>a</code> for equality</dd> <dt><span class="strong">Returns:</span></dt><dd><code>true</code> if the arguments are equal to each other and <code>false</code> otherwise</dd><dt><span class="strong">See Also:</span></dt><dd><code>Object.equals(Object)</code></dd></dl> </li> </ul> <a name="deepEquals(java.lang.Object, java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>deepEquals</h4> <pre>public static&nbsp;boolean&nbsp;deepEquals(java.lang.Object&nbsp;a, java.lang.Object&nbsp;b)</pre> <div class="block">Returns <code>true</code> if the arguments are deeply equal to each other and <code>false</code> otherwise. Two <code>null</code> values are deeply equal. If both arguments are arrays, the algorithm in <a href="../../../../org/linq4android/dependencies/java7/Arrays.html#deepEquals(java.lang.Object[], java.lang.Object[])"><code>Arrays.deepEquals</code></a> is used to determine equality. Otherwise, equality is determined by using the <code>equals</code> method of the first argument.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>a</code> - an object</dd><dd><code>b</code> - an object to be compared with <code>a</code> for deep equality</dd> <dt><span class="strong">Returns:</span></dt><dd><code>true</code> if the arguments are deeply equal to each other and <code>false</code> otherwise</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../org/linq4android/dependencies/java7/Arrays.html#deepEquals(java.lang.Object[], java.lang.Object[])"><code>Arrays.deepEquals(Object[], Object[])</code></a>, <a href="../../../../org/linq4android/dependencies/java7/Objects.html#equals(java.lang.Object, java.lang.Object)"><code>equals(Object, Object)</code></a></dd></dl> </li> </ul> <a name="hashCode(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public static&nbsp;int&nbsp;hashCode(java.lang.Object&nbsp;o)</pre> <div class="block">Returns the hash code of a non-<code>null</code> argument and 0 for a <code>null</code> argument.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>o</code> - an object</dd> <dt><span class="strong">Returns:</span></dt><dd>the hash code of a non-<code>null</code> argument and 0 for a <code>null</code> argument</dd><dt><span class="strong">See Also:</span></dt><dd><code>Object.hashCode()</code></dd></dl> </li> </ul> <a name="hash(java.lang.Object...)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hash</h4> <pre>public static&nbsp;int&nbsp;hash(java.lang.Object...&nbsp;values)</pre> <div class="block">Generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling <a href="../../../../org/linq4android/dependencies/java7/Arrays.html#hashCode(java.lang.Object[])"><code>Arrays.hashCode(Object[])</code></a>. <p>This method is useful for implementing <code>Object.hashCode()</code> on objects containing multiple fields. For example, if an object that has three fields, <code>x</code>, <code>y</code>, and <code>z</code>, one could write: <blockquote><pre> &#064;Override public int hashCode() { return Objects.hash(x, y, z); } </pre></blockquote> <b>Warning: When a single object reference is supplied, the returned value does not equal the hash code of that object reference.</b> This value can be computed by calling <a href="../../../../org/linq4android/dependencies/java7/Objects.html#hashCode(java.lang.Object)"><code>hashCode(Object)</code></a>.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>values</code> - the values to be hashed</dd> <dt><span class="strong">Returns:</span></dt><dd>a hash value of the sequence of input values</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../org/linq4android/dependencies/java7/Arrays.html#hashCode(java.lang.Object[])"><code>Arrays.hashCode(Object[])</code></a>, <code>List#hashCode</code></dd></dl> </li> </ul> <a name="toString(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public static&nbsp;java.lang.String&nbsp;toString(java.lang.Object&nbsp;o)</pre> <div class="block">Returns the result of calling <code>toString</code> for a non-<code>null</code> argument and <code>"null"</code> for a <code>null</code> argument.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>o</code> - an object</dd> <dt><span class="strong">Returns:</span></dt><dd>the result of calling <code>toString</code> for a non-<code>null</code> argument and <code>"null"</code> for a <code>null</code> argument</dd><dt><span class="strong">See Also:</span></dt><dd><code>Object.toString()</code>, <code>String.valueOf(Object)</code></dd></dl> </li> </ul> <a name="toString(java.lang.Object, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public static&nbsp;java.lang.String&nbsp;toString(java.lang.Object&nbsp;o, java.lang.String&nbsp;nullDefault)</pre> <div class="block">Returns the result of calling <code>toString</code> on the first argument if the first argument is not <code>null</code> and returns the second argument otherwise.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>o</code> - an object</dd><dd><code>nullDefault</code> - string to return if the first argument is <code>null</code></dd> <dt><span class="strong">Returns:</span></dt><dd>the result of calling <code>toString</code> on the first argument if it is not <code>null</code> and the second argument otherwise.</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../org/linq4android/dependencies/java7/Objects.html#toString(java.lang.Object)"><code>toString(Object)</code></a></dd></dl> </li> </ul> <a name="compare(java.lang.Object,java.lang.Object,java.util.Comparator)"> <!-- --> </a><a name="compare(T, T, java.util.Comparator)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>compare</h4> <pre>public static&nbsp;&lt;T&gt;&nbsp;int&nbsp;compare(T&nbsp;a, T&nbsp;b, java.util.Comparator&lt;? super T&gt;&nbsp;c)</pre> <div class="block">Returns 0 if the arguments are identical and <code>c.compare(a, b)</code> otherwise. Consequently, if both arguments are <code>null</code> 0 is returned. <p>Note that if one of the arguments is <code>null</code>, a <code>NullPointerException</code> may or may not be thrown depending on what ordering policy, if any, the <code>Comparator</code> chooses to have for <code>null</code> values.</div> <dl><dt><span class="strong">Type Parameters:</span></dt><dd><code>T</code> - the type of the objects being compared</dd><dt><span class="strong">Parameters:</span></dt><dd><code>a</code> - an object</dd><dd><code>b</code> - an object to be compared with <code>a</code></dd><dd><code>c</code> - the <code>Comparator</code> to compare the first two arguments</dd> <dt><span class="strong">Returns:</span></dt><dd>0 if the arguments are identical and <code>c.compare(a, b)</code> otherwise.</dd><dt><span class="strong">See Also:</span></dt><dd><code>Comparable</code>, <code>Comparator</code></dd></dl> </li> </ul> <a name="requireNonNull(java.lang.Object)"> <!-- --> </a><a name="requireNonNull(T)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>requireNonNull</h4> <pre>public static&nbsp;&lt;T&gt;&nbsp;T&nbsp;requireNonNull(T&nbsp;obj)</pre> <div class="block">Checks that the specified object reference is not <code>null</code>. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below: <blockquote><pre> public Foo(Bar bar) { this.bar = Objects.requireNonNull(bar); } </pre></blockquote></div> <dl><dt><span class="strong">Type Parameters:</span></dt><dd><code>T</code> - the type of the reference</dd><dt><span class="strong">Parameters:</span></dt><dd><code>obj</code> - the object reference to check for nullity</dd> <dt><span class="strong">Returns:</span></dt><dd><code>obj</code> if not <code>null</code></dd></dl> </li> </ul> <a name="requireNonNull(java.lang.Object,java.lang.String)"> <!-- --> </a><a name="requireNonNull(T, java.lang.String)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>requireNonNull</h4> <pre>public static&nbsp;&lt;T&gt;&nbsp;T&nbsp;requireNonNull(T&nbsp;obj, java.lang.String&nbsp;message)</pre> <div class="block">Checks that the specified object reference is not <code>null</code> and throws a customized <code>NullPointerException</code> if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below: <blockquote><pre> public Foo(Bar bar, Baz baz) { this.bar = Objects.requireNonNull(bar, "bar must not be null"); this.baz = Objects.requireNonNull(baz, "baz must not be null"); } </pre></blockquote></div> <dl><dt><span class="strong">Type Parameters:</span></dt><dd><code>T</code> - the type of the reference</dd><dt><span class="strong">Parameters:</span></dt><dd><code>obj</code> - the object reference to check for nullity</dd><dd><code>message</code> - detail message to be used in the event that a <code>NullPointerException</code> is thrown</dd> <dt><span class="strong">Returns:</span></dt><dd><code>obj</code> if not <code>null</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Objects.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/linq4android/dependencies/java7/Arrays.html" title="class in org.linq4android.dependencies.java7"><span class="strong">PREV CLASS</span></a></li> <li>NEXT CLASS</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/linq4android/dependencies/java7/Objects.html" target="_top">FRAMES</a></li> <li><a href="Objects.html" target="_top">NO FRAMES</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>SUMMARY:&nbsp;</li> <li>NESTED&nbsp;|&nbsp;</li> <li>FIELD&nbsp;|&nbsp;</li> <li>CONSTR&nbsp;|&nbsp;</li> <li><a href="#method_summary">METHOD</a></li> </ul> <ul class="subNavList"> <li>DETAIL:&nbsp;</li> <li>FIELD&nbsp;|&nbsp;</li> <li>CONSTR&nbsp;|&nbsp;</li> <li><a href="#method_detail">METHOD</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
ziaagikian/linq4android
core/doc/org/linq4android/dependencies/java7/Objects.html
HTML
apache-2.0
21,073
/* * Copyright (c) 2016-present, RxJava Contributors. * * 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 io.reactivex.rxjava3.internal.operators.flowable; import static io.reactivex.rxjava3.internal.util.ExceptionHelper.timeoutMessage; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.List; import java.util.concurrent.*; import org.junit.*; import org.mockito.InOrder; import org.reactivestreams.*; import io.reactivex.rxjava3.core.*; import io.reactivex.rxjava3.exceptions.TestException; import io.reactivex.rxjava3.internal.subscriptions.BooleanSubscription; import io.reactivex.rxjava3.plugins.RxJavaPlugins; import io.reactivex.rxjava3.processors.PublishProcessor; import io.reactivex.rxjava3.schedulers.*; import io.reactivex.rxjava3.subscribers.TestSubscriber; import io.reactivex.rxjava3.testsupport.*; public class FlowableTimeoutTests extends RxJavaTest { private PublishProcessor<String> underlyingSubject; private TestScheduler testScheduler; private Flowable<String> withTimeout; private static final long TIMEOUT = 3; private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; @Before public void setUp() { underlyingSubject = PublishProcessor.create(); testScheduler = new TestScheduler(); withTimeout = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler); } @Test public void shouldNotTimeoutIfOnNextWithinTimeout() { Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); withTimeout.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); verify(subscriber).onNext("One"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(subscriber, never()).onError(any(Throwable.class)); ts.cancel(); } @Test public void shouldNotTimeoutIfSecondOnNextWithinTimeout() { Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); withTimeout.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("Two"); verify(subscriber).onNext("Two"); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(subscriber, never()).onError(any(Throwable.class)); ts.cancel(); } @Test public void shouldTimeoutIfOnNextNotWithinTimeout() { TestSubscriberEx<String> subscriber = new TestSubscriberEx<>(); withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(TIMEOUT, TIME_UNIT)); } @Test public void shouldTimeoutIfSecondOnNextNotWithinTimeout() { TestSubscriberEx<String> subscriber = new TestSubscriberEx<>(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); subscriber.assertValue("One"); testScheduler.advanceTimeBy(TIMEOUT + 1, TimeUnit.SECONDS); subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(TIMEOUT, TIME_UNIT), "One"); ts.cancel(); } @Test public void shouldCompleteIfUnderlyingComletes() { Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onComplete(); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); ts.cancel(); } @Test public void shouldErrorIfUnderlyingErrors() { Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); withTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onError(new UnsupportedOperationException()); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); verify(subscriber).onError(any(UnsupportedOperationException.class)); ts.cancel(); } @Test public void shouldSwitchToOtherIfOnNextNotWithinTimeout() { Flowable<String> other = Flowable.just("a", "b", "c"); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(4, TimeUnit.SECONDS); underlyingSubject.onNext("Two"); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber, times(1)).onNext("One"); inOrder.verify(subscriber, times(1)).onNext("a"); inOrder.verify(subscriber, times(1)).onNext("b"); inOrder.verify(subscriber, times(1)).onNext("c"); inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); ts.cancel(); } @Test public void shouldSwitchToOtherIfOnErrorNotWithinTimeout() { Flowable<String> other = Flowable.just("a", "b", "c"); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(4, TimeUnit.SECONDS); underlyingSubject.onError(new UnsupportedOperationException()); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber, times(1)).onNext("One"); inOrder.verify(subscriber, times(1)).onNext("a"); inOrder.verify(subscriber, times(1)).onNext("b"); inOrder.verify(subscriber, times(1)).onNext("c"); inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); ts.cancel(); } @Test public void shouldSwitchToOtherIfOnCompletedNotWithinTimeout() { Flowable<String> other = Flowable.just("a", "b", "c"); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(4, TimeUnit.SECONDS); underlyingSubject.onComplete(); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber, times(1)).onNext("One"); inOrder.verify(subscriber, times(1)).onNext("a"); inOrder.verify(subscriber, times(1)).onNext("b"); inOrder.verify(subscriber, times(1)).onNext("c"); inOrder.verify(subscriber, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); ts.cancel(); } @Test public void shouldSwitchToOtherAndCanBeUnsubscribedIfOnNextNotWithinTimeout() { PublishProcessor<String> other = PublishProcessor.create(); Flowable<String> source = underlyingSubject.timeout(TIMEOUT, TIME_UNIT, testScheduler, other); Subscriber<String> subscriber = TestHelper.mockSubscriber(); TestSubscriber<String> ts = new TestSubscriber<>(subscriber); source.subscribe(ts); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); underlyingSubject.onNext("One"); testScheduler.advanceTimeBy(4, TimeUnit.SECONDS); underlyingSubject.onNext("Two"); other.onNext("a"); other.onNext("b"); ts.cancel(); // The following messages should not be delivered. other.onNext("c"); other.onNext("d"); other.onComplete(); InOrder inOrder = inOrder(subscriber); inOrder.verify(subscriber, times(1)).onNext("One"); inOrder.verify(subscriber, times(1)).onNext("a"); inOrder.verify(subscriber, times(1)).onNext("b"); inOrder.verifyNoMoreInteractions(); } @Test public void shouldTimeoutIfSynchronizedFlowableEmitFirstOnNextNotWithinTimeout() throws InterruptedException { final CountDownLatch exit = new CountDownLatch(1); final CountDownLatch timeoutSetuped = new CountDownLatch(1); final TestSubscriberEx<String> subscriber = new TestSubscriberEx<>(); new Thread(new Runnable() { @Override public void run() { Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); try { timeoutSetuped.countDown(); exit.await(); } catch (InterruptedException e) { e.printStackTrace(); } subscriber.onNext("a"); subscriber.onComplete(); } }).timeout(1, TimeUnit.SECONDS, testScheduler) .subscribe(subscriber); } }).start(); timeoutSetuped.await(); testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(1, TimeUnit.SECONDS)); exit.countDown(); // exit the thread } @Test public void shouldUnsubscribeFromUnderlyingSubscriptionOnTimeout() throws InterruptedException { // From https://github.com/ReactiveX/RxJava/pull/951 final Subscription s = mock(Subscription.class); Flowable<String> never = Flowable.unsafeCreate(new Publisher<String>() { @Override public void subscribe(Subscriber<? super String> subscriber) { subscriber.onSubscribe(s); } }); TestScheduler testScheduler = new TestScheduler(); Flowable<String> observableWithTimeout = never.timeout(1000, TimeUnit.MILLISECONDS, testScheduler); TestSubscriberEx<String> subscriber = new TestSubscriberEx<>(); observableWithTimeout.subscribe(subscriber); testScheduler.advanceTimeBy(2000, TimeUnit.MILLISECONDS); subscriber.assertFailureAndMessage(TimeoutException.class, timeoutMessage(1000, TimeUnit.MILLISECONDS)); verify(s, times(1)).cancel(); } @Test public void shouldUnsubscribeFromUnderlyingSubscriptionOnDispose() { final PublishProcessor<String> processor = PublishProcessor.create(); final TestScheduler scheduler = new TestScheduler(); final TestSubscriber<String> subscriber = processor .timeout(100, TimeUnit.MILLISECONDS, scheduler) .test(); assertTrue(processor.hasSubscribers()); subscriber.cancel(); assertFalse(processor.hasSubscribers()); } @Test public void timedAndOther() { Flowable.never().timeout(100, TimeUnit.MILLISECONDS, Flowable.just(1)) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1); } @Test public void disposed() { TestHelper.checkDisposed(PublishProcessor.create().timeout(1, TimeUnit.DAYS)); TestHelper.checkDisposed(PublishProcessor.create().timeout(1, TimeUnit.DAYS, Flowable.just(1))); } @Test public void timedErrorOther() { Flowable.error(new TestException()) .timeout(1, TimeUnit.DAYS, Flowable.just(1)) .test() .assertFailure(TestException.class); } @Test public void timedError() { Flowable.error(new TestException()) .timeout(1, TimeUnit.DAYS) .test() .assertFailure(TestException.class); } @Test public void timedEmptyOther() { Flowable.empty() .timeout(1, TimeUnit.DAYS, Flowable.just(1)) .test() .assertResult(); } @Test public void timedEmpty() { Flowable.empty() .timeout(1, TimeUnit.DAYS) .test() .assertResult(); } @Test public void badSource() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); subscriber.onNext(1); subscriber.onComplete(); subscriber.onNext(2); subscriber.onError(new TestException()); subscriber.onComplete(); } } .timeout(1, TimeUnit.DAYS) .test() .assertResult(1); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void badSourceOther() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); subscriber.onNext(1); subscriber.onComplete(); subscriber.onNext(2); subscriber.onError(new TestException()); subscriber.onComplete(); } } .timeout(1, TimeUnit.DAYS, Flowable.just(3)) .test() .assertResult(1); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void timedTake() { PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<Integer> ts = pp.timeout(1, TimeUnit.DAYS) .take(1) .test(); assertTrue(pp.hasSubscribers()); pp.onNext(1); assertFalse(pp.hasSubscribers()); ts.assertResult(1); } @Test public void timedFallbackTake() { PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<Integer> ts = pp.timeout(1, TimeUnit.DAYS, Flowable.just(2)) .take(1) .test(); assertTrue(pp.hasSubscribers()); pp.onNext(1); assertFalse(pp.hasSubscribers()); ts.assertResult(1); } @Test public void fallbackErrors() { Flowable.never() .timeout(1, TimeUnit.MILLISECONDS, Flowable.error(new TestException())) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void onNextOnTimeoutRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler sch = new TestScheduler(); final PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriberEx<Integer> ts = pp.timeout(1, TimeUnit.SECONDS, sch).to(TestHelper.<Integer>testConsumer()); Runnable r1 = new Runnable() { @Override public void run() { pp.onNext(1); } }; Runnable r2 = new Runnable() { @Override public void run() { sch.advanceTimeBy(1, TimeUnit.SECONDS); } }; TestHelper.race(r1, r2); if (ts.values().size() != 0) { if (ts.errors().size() != 0) { ts.assertFailure(TimeoutException.class, 1); ts.assertErrorMessage(timeoutMessage(1, TimeUnit.SECONDS)); } else { ts.assertValuesOnly(1); } } else { ts.assertFailure(TimeoutException.class); ts.assertErrorMessage(timeoutMessage(1, TimeUnit.SECONDS)); } } } @Test public void onNextOnTimeoutRaceFallback() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler sch = new TestScheduler(); final PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriberEx<Integer> ts = pp.timeout(1, TimeUnit.SECONDS, sch, Flowable.just(2)).to(TestHelper.<Integer>testConsumer()); Runnable r1 = new Runnable() { @Override public void run() { pp.onNext(1); } }; Runnable r2 = new Runnable() { @Override public void run() { sch.advanceTimeBy(1, TimeUnit.SECONDS); } }; TestHelper.race(r1, r2); if (ts.isTerminated()) { int c = ts.values().size(); if (c == 1) { int v = ts.values().get(0); assertTrue("" + v, v == 1 || v == 2); } else { ts.assertResult(1, 2); } } else { ts.assertValuesOnly(1); } } } @Test public void doubleOnSubscribeFallback() { TestHelper.checkDoubleOnSubscribeFlowable(f -> f.timeout(1, TimeUnit.MINUTES, Flowable.<Object>never())); } }
ReactiveX/RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableTimeoutTests.java
Java
apache-2.0
18,918
package com.tedmemo.db; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; /** * Created by Ted on 14-8-6. */ @DatabaseTable(tableName = "memoinfo") public class MemoItemInfo implements Serializable { private static final long serialVersionUID = -6919461967497580385L; /**Memo Id,Add by self*/ @DatabaseField(allowGeneratedIdInsert=true, columnName="id", generatedId=true) private int _mId; @DatabaseField(columnName="is_read") private boolean _mIsRead; @DatabaseField(columnName="json_text") private String _mJsonText; @DatabaseField(columnName="text") private String _mText; /**对应的标签id*/ @DatabaseField(columnName="icon_id") private int _mIconId; /**时间*/ @DatabaseField(columnName="updated") private long _mUpdated; public MemoItemInfo(){ } public int get_mId() { return _mId; } public void set_mId(int _mId) { this._mId = _mId; } public boolean is_mIsRead() { return _mIsRead; } public void set_mIsRead(boolean _mIsRead) { this._mIsRead = _mIsRead; } public String get_mJsonText() { return _mJsonText; } public void set_mJsonText(String _mJsonText) { this._mJsonText = _mJsonText; } public String get_mText() { return _mText; } public void set_mText(String _mText) { this._mText = _mText; } public long get_mUpdated() { return _mUpdated; } public int get_mIconId() { return _mIconId; } public void set_mIconId(int _mIconId) { this._mIconId = _mIconId; } public void set_mUpdated(long _mUpdated) { this._mUpdated = _mUpdated; } }
xiongwei-git/TedMemo
src/com/tedmemo/db/MemoItemInfo.java
Java
apache-2.0
1,804
#!/bin/bash #placeholder for deployment script. set -ex case "$1" in 'nonha' ) cp nosdn/juju-deployer/ovs.yaml ./bundles.yaml ;; 'ha' ) cp nosdn/juju-deployer/ovs-ha.yaml ./bundles.yaml ;; 'tip' ) cp nosdn/juju-deployer/ovs-tip.yaml ./bundles.yaml cp common/source/* ./ sed -i -- "s|branch: master|branch: stable/$2|g" ./*.yaml ;; * ) cp nosdn/juju-deployer/ovs.yaml ./bundles.yaml ;; esac case "$3" in 'orangepod2' ) cp maas/orange/pod2/control-interfaces.host trusty/ubuntu-nodes-controller/network/interfaces.host cp maas/orange/pod2/lxc-add-more-interfaces trusty/ubuntu-nodes-controller/lxc/add-more-interfaces cp maas/orange/pod2/compute-interfaces.host trusty/ubuntu-nodes-compute/network/interfaces.host cp maas/orange/pod2/lxc-add-more-interfaces trusty/ubuntu-nodes-compute/lxc/add-more-interfaces # As per your lab vip address list be deafult uses 10.4.1.11 - 10.4.1.20 sed -i -- 's/10.4.1.1/192.168.2.2/g' ./bundles.yaml # choose the correct interface to use for data network sed -i -- 's/#os-data-network: 10.4.8.0\/21/os-data-network: 192.168.12.0\/24/g' ./bundles.yaml # Choose the external port to go out from gateway to use. sed -i -- 's/# "ext-port": "eth1"/ "ext-port": "eth1"/g' ./bundles.yaml ;; 'intelpod6' ) # As environment does not need special treatment for interfaces for MAAS 1.9 sed -i -- 's/local:trusty\/ubuntu-nodes-controller/cs:trusty\/ubuntu/g' ./bundles.yaml sed -i -- 's/local:trusty\/ubuntu-nodes-compute/cs:trusty\/ubuntu/g' ./bundles.yaml # As per your lab vip address list be deafult uses 10.4.1.21 - 10.4.1.29 sed -i -- 's/10.4.1.1/10.4.1.2/g' ./bundles.yaml # choose the correct interface to use for data network sed -i -- 's/#os-data-network: 10.4.8.0\/21/os-data-network: 10.4.9.0\/24/g' ./bundles.yaml # Choose the external port to go out from gateway to use. sed -i -- 's/# "ext-port": "eth1"/ "ext-port": "eth2"/g' ./bundles.yaml ;; 'intelpod5' ) # As environment does not need special treatment for interfaces for MAAS 1.9 sed -i -- 's/local:trusty\/ubuntu-nodes-controller/cs:trusty\/ubuntu/g' ./bundles.yaml sed -i -- 's/local:trusty\/ubuntu-nodes-compute/cs:trusty\/ubuntu/g' ./bundles.yaml # As per your lab vip address list be deafult uses 10.4.1.21 - 10.4.1.29 sed -i -- 's/10.4.1.1/10.4.1.2/g' ./bundles.yaml # choose the correct interface to use for data network sed -i -- 's/#os-data-network: 10.4.8.0\/21/os-data-network: 10.4.9.0\/24/g' ./bundles.yaml # Choose the external port to go out from gateway to use. sed -i -- 's/# "ext-port": "eth1"/ "ext-port": "eth2.724"/g' ./bundles.yaml ;; 'attvirpod1' ) # As virtual environment does not need special treatment for interfaces. sed -i -- 's/local:trusty\/ubuntu-nodes-controller/cs:trusty\/ubuntu/g' ./bundles.yaml sed -i -- 's/local:trusty\/ubuntu-nodes-compute/cs:trusty\/ubuntu/g' ./bundles.yaml # As per your lab vip address list be deafult uses 10.4.1.11 - 10.4.1.20 sed -i -- 's/10.4.1.1/192.168.10.1/g' ./bundles.yaml # Choose the external port to go out from gateway to use. sed -i -- 's/# "ext-port": "eth1"/ "ext-port": "eth1"/g' ./bundles.yaml ;; 'ravello' ) sed -i -- 's/local:trusty\/ubuntu-nodes-controller/cs:trusty\/ubuntu/g' ./bundles.yaml sed -i -- 's/local:trusty\/ubuntu-nodes-compute/cs:trusty\/ubuntu/g' ./bundles.yaml sed -i -- 's/10.4.1.1/10.20.0.1/g' ./bundles.yaml sed -i -- 's/# "ext-port": "eth1"/ "ext-port": "eth1"/g' ./bundles.yaml ;; 'default' ) sed -i -- 's/local:trusty\/ubuntu-nodes-controller/cs:trusty\/ubuntu/g' ./bundles.yaml sed -i -- 's/local:trusty\/ubuntu-nodes-compute/cs:trusty\/ubuntu/g' ./bundles.yaml sed -i -- 's/10.4.1.1/192.168.122.1/g' ./bundles.yaml sed -i -- 's/# "ext-port": "eth1"/ "ext-port": "eth1"/g' ./bundles.yaml ;; esac echo "... Deployment Started ...." case "$1" in 'nonha' ) juju-deployer -vW -d -c bundles.yaml trusty-"$2"-nodes juju-deployer -vW -d -t 3600 -c bundles.yaml trusty-"$2" ;; 'ha' ) juju-deployer -vW -d -c bundles.yaml trusty-"$2"-nodes juju-deployer -vW -d -t 3600 -c bundles.yaml trusty-"$2" ;; 'tip' ) juju-deployer -vW -d -c bundles.yaml trusty-"$2"-nodes juju-deployer -vW -d -t 3600 -c bundles.yaml trusty-"$2" ;; * ) juju-deployer -vW -d -c bundles.yaml trusty-"$2"-nodes juju-deployer -vW -d -t 3600 -c bundles.yaml trusty-"$2" ;; esac
opnfv/opnfv-ravello-demo
joid/ci/nosdn/01-deploybundle.sh
Shell
apache-2.0
4,978
package br.com.viewria.servlets; import java.util.ArrayList; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import spring.corp.framework.exceptions.UserException; import spring.corp.framework.i18n.ManagerMessage; import spring.corp.framework.security.EmailHolder; import spring.corp.framework.security.IdHolder; import spring.corp.framework.security.NameHolder; import spring.corp.framework.utils.StringUtils; import spring.corp.framework.view.InputHolder; import spring.corp.framework.view.ServletContextHolder; public class ProcessRequest<T> extends AbstractServlet<T> { private static final long serialVersionUID = 1L; private ServletContext servletContext; public ProcessRequest(ServletContext servletContext) { this.servletContext = servletContext; } public T executeWebClassSpring(ServletRequest request, ServletResponse response, String webClassId, String invoke) { WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); Object webClass = webApplicationContext.getBean(webClassId); if (webClass == null) { String message = ManagerMessage.getMessage("view.webclassid.invalido", new Object[] { webClassId }); throw new UserException(message); } return executeWebClass(request, response, webClass, invoke); } public void preExecute(ServletRequest request, ServletResponse response) { InputHolder.set(new ArrayList<UserException>()); ServletContextHolder.set(servletContext); HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession session = httpRequest.getSession(true); String id = (String) session.getAttribute("id"); if (!StringUtils.isBlank(id)) { IdHolder.set(Long.valueOf(id)); } String nome = (String) session.getAttribute("name"); NameHolder.set(nome); String email = (String) session.getAttribute("email"); EmailHolder.set(email); } public void posExecute(ServletRequest request, ServletResponse response) { InputHolder.clear(); ServletContextHolder.clear(); NameHolder.clear(); IdHolder.clear(); } }
g6tech/spring-corp-test
project/viewria/src/main/java/br/com/viewria/servlets/ProcessRequest.java
Java
apache-2.0
2,363
/** * **************************************************************************** * Copyright (c) 2008 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * SAP AG - initial API and implementation * ***************************************************************************** */ package org.eclipse.mat.snapshot.model; /** * Interface for an array object in the heap dump. * * @noimplement */ public interface IArray extends IObject { /** * Returns the length of the object. */ public int getLength(); }
ritterliu/AutoMemoryAnalysis
src/org/eclipse/mat/snapshot/model/IArray.java
Java
apache-2.0
748
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ /** * Internal dependencies */ import createSolid from '../createSolid'; describe('createSolid', () => { it('should convert with specifying opacity', () => { expect(createSolid(255, 0, 0)).toStrictEqual({ color: { r: 255, g: 0, b: 0 }, }); }); it('should convert with full opacity', () => { expect(createSolid(0, 255, 0, 1)).toStrictEqual({ color: { r: 0, g: 255, b: 0 }, }); }); it('should convert with less than full opacity', () => { expect(createSolid(0, 0, 255, 0.1)).toStrictEqual({ color: { r: 0, g: 0, b: 255, a: 0.1 }, }); }); });
GoogleForCreators/web-stories-wp
packages/patterns/src/test/createSolid.js
JavaScript
apache-2.0
1,195
""" Ecks plugin to collect system memory usage information Copyright 2011 Chris Read (chris.read@gmail.com) 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. """ def get_memory(parent, host, community): """ This is a plugin to be loaded by Ecks return a tuple containing (total_swap, avail_swap, total_real, avail_real, mem_buffer, mem_cached). Values are in kiloBytes """ memory = (1,3,6,1,4,1,2021,4) # UCD-SNMP-MIB data = parent.get_snmp_data(host, community, memory, 1) if data: return map(parent._build_answer, parent._extract(data, int, 3), parent._extract(data, int, 4), parent._extract(data, int, 5), parent._extract(data, int, 6), parent._extract(data, int, 14), parent._extract(data, int, 15), )[0]
cread/ecks
ecks/plugins/memory.py
Python
apache-2.0
1,335
# Lepiurus strigosus Dumort. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Parapholis/Parapholis strigosa/ Syn. Lepiurus strigosus/README.md
Markdown
apache-2.0
183
using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Diagnostics; using System.IO; using Kitware.VTK; namespace ActiViz.Examples { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void renderWindowControl1_Load(object sender, EventArgs e) { try { WriteVTI(); } catch(Exception ex) { MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK); } } private void WriteVTI() { // Path to vtk data must be set as an environment variable // VTK_DATA_ROOT = "C:\VTK\vtkdata-5.8.0" vtkTesting test = vtkTesting.New(); string root = test.GetDataRoot(); string filePath = System.IO.Path.Combine(root, @"Data\test_vti.vti"); vtkImageData imageData = vtkImageData.New(); imageData.SetDimensions(3, 4, 5); imageData.SetNumberOfScalarComponents(1); imageData.SetScalarTypeToDouble(); int[] dims = imageData.GetDimensions(); // Fill every entry of the image data with "2.0" /* we can do this in unsafe mode which looks pretty similar to the c++ version but then you must declare at the very top of your file the "preprocessor" directive #define UNSAFE * or whatever name you choose for the following preprocessor #if statement */ #if UNSAFE unsafe { for(int z = 0; z < dims[2]; z++) { for(int y = 0; y < dims[1]; y++) { for(int x = 0; x < dims[0]; x++) { double* pixel = (double*)imageData.GetScalarPointer(x, y, z).ToPointer(); // c++ version: // double* pixel = static_cast<double*>(imageData->GetScalarPointer(x,y,z)); pixel[0] = 2.0; } } } } #else /* or we can do it in managed mode */ int size = imageData.GetScalarSize(); IntPtr ptr = Marshal.AllocHGlobal(size); for(int z = 0; z < dims[2]; z++) { for(int y = 0; y < dims[1]; y++) { for(int x = 0; x < dims[0]; x++) { ptr = imageData.GetScalarPointer(x, y, z); Marshal.Copy(new double[] { 2.0 }, 0, ptr, 1); } } } Marshal.FreeHGlobal(ptr); #endif vtkXMLImageDataWriter writer = vtkXMLImageDataWriter.New(); writer.SetFileName(filePath); writer.SetInputConnection(imageData.GetProducerPort()); writer.Write(); // Read and display file for verification that it was written correctly vtkXMLImageDataReader reader = vtkXMLImageDataReader.New(); if(reader.CanReadFile(filePath) == 0) { MessageBox.Show("Cannot read file \"" + filePath + "\"", "Error", MessageBoxButtons.OK); return; } reader.SetFileName(filePath); reader.Update(); // Convert the image to a polydata vtkImageDataGeometryFilter imageDataGeometryFilter = vtkImageDataGeometryFilter.New(); imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()); imageDataGeometryFilter.Update(); vtkDataSetMapper mapper = vtkDataSetMapper.New(); mapper.SetInputConnection(imageDataGeometryFilter.GetOutputPort()); // actor vtkActor actor = vtkActor.New(); actor.SetMapper(mapper); actor.GetProperty().SetPointSize(4); // get a reference to the renderwindow of our renderWindowControl1 vtkRenderWindow renderWindow = renderWindowControl1.RenderWindow; // renderer vtkRenderer renderer = renderWindow.GetRenderers().GetFirstRenderer(); // set background color renderer.SetBackground(0.2, 0.3, 0.4); // add our actor to the renderer renderer.AddActor(actor); } } }
lorensen/VTKExamples
src/CSharp/IO/WriteVTI.cs
C#
apache-2.0
4,073
# 为什么推荐我们用markdown > 原创:余俊卿 转载请:<yujunqing@meizu.com> ---- > 一种适用于网络的书写语言 Markdown 是一种轻量级标记语言,使用易读易写的纯文本格式编写文档,然后转换成有效的XHTML(或者HTML)文档。 在我们还在用office、txt、html富文本编辑器等撰写文档的时候,殊不知世界上最活跃的程序员们正用markdown在github和博客上传播和展示着他们的成果。 优点: 简而言之,markdown是为在互联网上展示而生的编写文档的语法,它是传统的 **数据+展示** 里的那一个**数据**,当你需要展示的时候有相当高的兼容性和良好的结构性。 #### 1. 易读易写 语法简单,常用语法5分钟即可完全掌握,难道作为程序员的你会告诉我用鼠标在富文本编辑器上选择功能 比直接在markdown编辑器里打几个代号更容易? 就算是markdown的原生文本,在一些简单地符号包裹下,也结构简洁明了,更何况在大部分的世界性的博客上都支持将markdown转化成经过排版的网页来展示,即使最次,本地也可以用工具直接生成html的页面。 #### 2. 适用于网络 Markdown 语法的目标是:成为一种适用于网络的书写语言。从已经搭建好的gitbook页面或者gitlab的README页面都能看到这种语言是否利于网络传播。 而传统的doc文档本地看看还可以,在线的话,难道还要加载一个flash插件? #### 3. 兼容html语言 markdown定义的符号并不是html能展示的全部,正因为这样,markdown才能简单好用、转码效率高,让大家能尽量用类似的语法来展示内容。 但同时,markdown也是完全兼容html标签的,一些复杂的效果可以用html标签来完成。 #### 4. 结构一致,降低同行交流的隔阂 看看github上优秀的开源库的作者们,无一例外用markdown展示自己的成果。 #### 5. 和git完美结合 git对文本格式的文件支持有多强就无需赘述了吧。markdown和git的结合能保证你的文档的安全性(多个git仓库,求你删)、完整性(改错了,revert!)。总之就是很酷。 #### 6. gitbook markdown文档可以汇集成一本gitbook,用非常良好的排版展示给别人。 同时也可以生成pdf、ebook等。 #### 7. 其它 此外常用git也是对我们工作能力的加强,殊不知前几月刚来魅族时,连git都是只听其名而不曾用过,而到现在几乎完全离不开git了。 markdown基于文本的格式存储也方便我们在本地使用find、grep等命令快速查找需要的文档。 git是非常强大的协作工具,让多人共同编辑、维护文档变得很容易。
kenaiX/snowball
为什么推荐我们用markdown/README.md
Markdown
apache-2.0
2,863
# Module google/wiki40b-lm-it/1 Embeddings and negative log likelihood from a language model trained on Italian from Wiki40B dataset with sentence-piece vocabulary size 32k. <!-- task: text-language-model --> <!-- asset-path: legacy --> <!-- fine-tunable: false --> <!-- format: hub --> <!-- language: it --> <!-- network-architecture: transformer-xl --> <!-- dataset: wiki40b --> <!-- colab: https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/wiki40b_lm.ipynb --> ## Overview The Wiki40B-lm module includes language models trained on the newly published cleaned-up Wiki40B dataset available on TFDS. The training setup is based on the paper “Wiki-40B: Multilingual Language Model Dataset” [1]. This specific module is trained on Italian available in Wiki40B dataset. It is trained using a 12 layers Transformer XL model [2]. The input to the module is variable length text in Italian, and the output is a 768 dimensional vector of the input word embeddings, activations of all layers, and the negative log likelihood of the text. ## Details A medium sized Transformer-XL of 12 layers, with hidden size 768, and 12 attention heads with 64 dimensions, leading to a total number of 141.4M parameters. A 32k vocabulary spm model learned from sampling 10k examples from Italian Wiki40B. ### Input The module takes **a single sentence** as input. ### Prerequisites This module relies on the [Tensorflow Text library](https://github.com/tensorflow/text) for input preprocessing (please make sure the TensorFlow version you use is compatible with Tensorflow Text library). On [RaggedTensorToTensor](https://www.tensorflow.org/api_docs/python/tf/raw_ops/RaggedTensorToTensor), which is only available after TF version 2.1.0. The memory for the colab needs to be more than 20GB to run the generation demo. ```python !pip install --quiet tensorflow_text ``` ### Example use ```python import numpy as np import tensorflow.compat.v1 as tf import tensorflow_hub as hub import tensorflow_text as tf_text tf.disable_eager_execution() n_layer = 12 d_model = 768 max_gen_len = 128 def generate(module, inputs, mems): """Generate text.""" inputs = tf.dtypes.cast(inputs, tf.int64) generation_input_dict = dict(input_tokens=inputs) mems_dict = {} for i in range(n_layer): mems_dict["mem_{}".format(i)] = mems[i] generation_input_dict.update(mems_dict) generation_outputs = module(generation_input_dict, signature="prediction", as_dict=True) probs = generation_outputs["probs"] new_mems = [] for i in range(n_layer): new_mems.append(generation_outputs["new_mem_{}".format(i)]) return probs, new_mems g = tf.Graph() with g.as_default(): module = hub.Module("https://tfhub.dev/google/wiki40b-lm-it/1") text = ["\n_START_ARTICLE_\n28th Street (linea IRT Lexington Avenue)\n_START_SECTION_\nStoria\n_START_PARAGRAPH_\nLa stazione, i cui lavori di costruzione ebbero inizio nel 1900, venne aperta il 27 ottobre 1904, come"] # Word embeddings. embeddings = module(dict(text=text), signature="word_embeddings", as_dict=True) embeddings = embeddings["word_embeddings"] # Activations at each layer. activations = module(dict(text=text),signature="activations", as_dict=True) activations = activations["activations"] # Negative log likelihood of the text, and perplexity. neg_log_likelihood = module(dict(text=text), signature="neg_log_likelihood", as_dict=True) neg_log_likelihood = neg_log_likelihood["neg_log_likelihood"] ppl = tf.exp(tf.reduce_mean(neg_log_likelihood, axis=1)) # Tokenization and detokenization with the sentencepiece model. token_ids = module(dict(text=text), signature="tokenization", as_dict=True) token_ids = token_ids["token_ids"] detoken_text = module(dict(token_ids=token_ids), signature="detokenization", as_dict=True) detoken_text = detoken_text["text"] # Generation mems_np = [np.zeros([1, 0, d_model], dtype=np.float32) for _ in range(n_layer)] inputs_np = token_ids sampled_ids = [] for step in range(max_gen_len): probs, mems_np = generate(module, inputs_np, mems_np) sampled_id = tf.random.categorical(tf.math.log(probs[0]), num_samples=1, dtype=tf.int32) sampled_id = tf.squeeze(sampled_id) sampled_ids.append(sampled_id) inputs_np = tf.reshape(sampled_id, [1, 1]) sampled_ids = tf.expand_dims(sampled_ids, axis=0) generated_text = module(dict(token_ids=sampled_ids), signature="detokenization", as_dict=True) generated_text = generated_text["text"] init_op = tf.group([tf.global_variables_initializer(), tf.tables_initializer()]) # Initialize session. with tf.Session(graph=g) as session: session.run(init_op) embeddings, neg_log_likelihood, ppl, activations, token_ids, detoken_text, generated_text = session.run([ embeddings, neg_log_likelihood, ppl, activations, token_ids, detoken_text, generated_text]) ``` ## Reference [1] Mandy Guo, Zihang Dao, Denny Vrandecic, Rami Al-Rfou. [Wiki-40B: Multilingual Language Model Dataset](https://research.google/pubs/pub49029/). To appear, LREC, May 2020. [2] Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov. [Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context](https://arxiv.org/abs/1901.02860). ACL, July 2019.
tensorflow/tfhub.dev
assets/docs/google/models/wiki40b-lm-it/1.md
Markdown
apache-2.0
5,456
/* * 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.felix.dm.test.annotation; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.provision; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import java.util.Dictionary; import java.util.Hashtable; import org.apache.felix.dm.Component; import org.apache.felix.dm.DependencyManager; import org.apache.felix.dm.test.Base; import org.apache.felix.dm.test.BundleGenerator; import org.apache.felix.dm.test.bundle.annotation.sequencer.Sequencer; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.Configuration; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; /** * Use case: Tests an aspect service implemented as a dynamic proxy, and ensure that its lifecycle methods are properly invoked * (init/start/stop/destroy methods). */ @RunWith(JUnit4TestRunner.class) public class AspectLifecycleWithDynamicProxyAnnotationTest extends AnnotationBase { @Configuration public static Option[] configuration() { return options( systemProperty(DMLOG_PROPERTY).value( "true" ), provision( mavenBundle().groupId("org.osgi").artifactId("org.osgi.compendium").version(Base.OSGI_SPEC_VERSION), mavenBundle().groupId("org.apache.felix").artifactId("org.apache.felix.dependencymanager").versionAsInProject(), mavenBundle().groupId("org.apache.felix").artifactId("org.apache.felix.dependencymanager.runtime").versionAsInProject()), provision( new BundleGenerator() .set(Constants.BUNDLE_SYMBOLICNAME, "AspectLifecycleDynamicProxyTest") .set("Export-Package", "org.apache.felix.dm.test.bundle.annotation.sequencer") .set("Private-Package", "org.apache.felix.dm.test.bundle.annotation.aspectlifecycledynamicproxy") .set("Import-Package", "*") .set("-plugin", "org.apache.felix.dm.annotation.plugin.bnd.AnnotationPlugin") .build())); } @Test public void testAnnotatedAspect(BundleContext context) { DependencyManager m = new DependencyManager(context); // Provide the Sequencer server to the ServiceProvider service Dictionary props = new Hashtable() {{ put("test", "aspectLifecycle.ServiceProvider"); }}; m.add(m.createComponent().setImplementation(this).setInterface(Sequencer.class.getName(), props)); // Check if the ServiceProvider has been injected in the AspectTest service. m_ensure.waitForStep(1, 10000); // Provide the Sequencer server to the ServiceProviderAspect service props = new Hashtable() {{ put("test", "aspectLifecycle.ServiceProviderAspect"); }}; Component seq = m.createComponent().setImplementation(this).setInterface(Sequencer.class.getName(), props); m.add(seq); // Check if the AspectTest has been injected with the aspect m_ensure.waitForStep(3, 10000); // Remove the ServiceProviderAspect service m.remove(seq); // And check if the aspect has been called in its stop/destroy methods. m_ensure.waitForStep(7, 10000); } }
boneman1231/org.apache.felix
trunk/dependencymanager/test/src/test/java/org/apache/felix/dm/test/annotation/AspectLifecycleWithDynamicProxyAnnotationTest.java
Java
apache-2.0
4,203
package io.hightide.exceptions; /** * @author <a href="mailto:gpan@groundzerolabs.com">George Panagiotopoulos</a> */ public class HandlerInitializationException extends RuntimeException { public HandlerInitializationException(String message, Throwable cause) { super(message, cause); } }
gzlabs/hightide
hightide-core/src/main/java/io/hightide/exceptions/HandlerInitializationException.java
Java
apache-2.0
308
% % author: Ni Qingliang % date: 2011-02-11 % \startcomponent cpn-overview \product fusion-splicer-SD \chapter{技术选择} 相对于现有产品,下一代熔接机软件的最大变化在于 OS 的引入, OS 的引入屏蔽了许多硬件细节, 使得我们可以更加专注于业务。 进而使得我们可以基于OS构建我们自己的软件平台, 以支持多种产品,并减少代码复用的难度; 在形成一个完整的软件平台后,可以缩短产品的开发周期,有利于快速推出新产品。 目前我们计划选用 GNU / Linux, 这也是目前的趋势,在嵌入式软件领域,还有其他许多 OS, 如 VxWorks、 Windows Embedded 等, GNU / Linux 最大的好处在于免费, 而且由于社区大量开发人员的参与, 很容易找到交流的对象,芯片厂商的支持目前也已经很成熟了。 另外,我们还可以方便的重用其他开源软件, 以减少我们的工作量。 \useURL[yoctoAddr][https://www.yoctoproject.org/] \startnotepar 严格意义上讲, GNU / Linux 只是 OS 的内核, 诸如 Arch、 openSUSE、 Redhat 才能称为 OS, 此处我们选用 GNU / Linux 作为 OS 内核, 用 Yocto (是一个 OS 构建系统,基于 OpenEmbedded,详情参见\from[yoctoAddr]) 来构建我们自己的 OS,或者叫 Linux Distribution。 \stopnotepar GUI 是熔接机软件的一个重要组成部分, 为了照顾老客户,应当尽量减少其变动; 而由于触摸屏的引入,可能会有所调整, 但要遵循 PLA (principle of lease astonishment)。 对于 GUI,目前考虑还是继续采用 QT(E), 当然也有其他 GUI 框架,如 Android, 但是 Android 的性能需要进一步评估 (Google 发布 NDK 应该也有性能方面的原因), 目前我们对 Android 不是太熟悉, 保守起见,我们还是选用 QT(E)。 \useURL[sailFishAddr][https://sailfishos.org/] \startnotepar 本来 GUI 是 OS 的一部分,此处我们选用 QT 只用在我们自己的应用程序上, OS 没有囊括 GUI。 当然,现在也有基于 QT 的嵌入式 OS,比如 SailFish(参见 \from[sailFishAddr]), 后续开发可以考虑。 另外 QT 本身是跨 OS 的,如果我们的其他产品用了 Windows Embedded 等 OS, 可以保证我们的 GUI 在不同产品上的一致性。 \stopnotepar 至于开发语言,嵌入式领域用的最多的就是 C 和 C++, 另外 QT 本身的开发语言就是 C++, 所以我们考虑采用 C++, 虽然 C++ 易学难精,但是一般的开发应该不会有太大问题, 选用 C++ 主要是要利用其面向对象的特性, 面向对象也是目前软件开发中最常用的编程思想, 虽然用 C 也可以写出面向对象的代码, 但毕竟不如语言本身就支持此特性来的方便, 当然面向对象还具备诸如易维护、质量高、效率高、易扩展等其他好处, 也会为我们的软件开发工作带来极大便利。 \startnotepar 虽然 Android 采用 Java 为主要编程语言, 但是 NDK 的引入使其可以与 C / C++ 开发的代码方便得进行交互。 如果以后考虑采用 Android, 那么可以仅用 Java 实现 GUI, 而业务逻辑还是采用 C / C++ 来开发。 \stopnotepar 熔接机软件还有一个特点,就是大量的参数。 在架构设计时也要充分考虑。 充分利用 C++ 的面向对象特性, 将所有参数分门别类,进行层次划分,以达到“高内聚”与“低耦合”的目标。 \section{关于开发过程的控制} 引入软件版本控制, 软件的版本控制最主要的是管理源代码。 目前业界已经都转向了分布式版本控制系统,如 git、 mercurial。 两种工具就功能而言没有太大区别,使用那种完全取决于个人喜好。 目前 Linux 内核、各种嵌入式 OS 构建系统等使用的都是 git, 我们在开发时不可避免要使用这些软件, 为了更好的互操作,选用 git 作为我们软件的版本控制系统。 \startnotepar dailybuild、 autotest 等可以在开发过程种视具体情况逐步实施。 \stopnotepar \stopcomponent
walkthetalk/libem
doc/cpn-overview.tex
TeX
apache-2.0
4,157
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2017-09-14 23:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('organization', '0004_teacher_image'), ('courses', '0006_auto_20170914_2345'), ] operations = [ migrations.AddField( model_name='course', name='teacher', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='organization.Teacher', verbose_name='\u8bb2\u5e08'), ), ]
LennonChin/Django-Practices
MxOnline/apps/courses/migrations/0007_course_teacher.py
Python
apache-2.0
640
# git_reposcan # About This tool scans the current directory for git repositories and prints out all branches for each found repository. # Usage ### One time usage Simply just ```source``` the file ```git_reposcan.sh``` and run the function ```git_reposcan```. $ source ~/git_reposcan.sh $ git_reposcan -- puppet-nagios-nrpe -- * fix-broken-debian6-nrpe-init master remotes/origin/HEAD -> origin/master remotes/origin/fix-broken-debian6-nrpe-init remotes/origin/master -- puppet-bamboo_agent -- * add-INIT-INFO-to-init-script master remotes/origin/HEAD -> origin/master remotes/origin/add-INIT-INFO-to-init-script remotes/origin/master ### Everyday usage - create a directory named ```.functions``` in your home directory - copy ```git_reposcan.sh``` into this directory - let ```.bash_profile``` source all files in ```$HOME/.functions``` everytime you login Contents of ```$HOME``` $ ls -la $HOME ... 0 drwxr-x--- 2 alexanderfahlke alexanderfahlke 4096 Mar 24 15:37 .functions ... Contents of ```$HOME/.functions``` $ ls -la $HOME/.functions ... -rw-r----- 1 alexanderfahlke alexanderfahlke 956 Mar 24 15:37 git_reposcan.sh ... Contents of ```$HOME/.bash_profile``` ... if [[ -d $HOME/.functions ]]; then for func in $(find -L "${HOME}/.functions" -type f -and -not -name '.gitignore'); do [[ -r "$func" ]] && [[ -f "$func" ]] && source "$func" done unset func fi ...
alexanderfahlke/unix-toolbox
functions/git_reposcan/README.md
Markdown
apache-2.0
1,543
package com.github.pixelrunstudios.GdxTest; public class BorderBlockHolder implements BlockHolder{ protected int width; protected int height; public BorderBlockHolder(int width, int height){ this.width = width; this.height = height; } @Override public boolean hasBlock(int x, int y, float tick){ if(x == 0 || x == width - 1 || y == 0 || y == height - 1){ return true; } return false; } @Override public boolean allowFood(int x, int y){ return !hasBlock(x, y, 0); } }
PixelRunStudios/GdxTest
core/src/com/github/pixelrunstudios/GdxTest/BorderBlockHolder.java
Java
apache-2.0
497
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_06) on Sun Jun 08 16:48:33 CEST 2008 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> Uses of Package org.apache.commons.logging.impl (SLF4J 1.5.2 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Package org.apache.commons.logging.impl (SLF4J 1.5.2 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/commons/logging/impl/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>org.apache.commons.logging.impl</B></H2> </CENTER> No usage of org.apache.commons.logging.impl <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/commons/logging/impl/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright © 2005-2008 <a href="http://www.qos.ch">QOS.ch</a>. All Rights Reserved. </BODY> </HTML>
stumoodie/VisualLanguageToolkit
lib/slf4j-1.5.2/site/apidocs/org/apache/commons/logging/impl/package-use.html
HTML
apache-2.0
5,831
/* * stream_iterator.cc * Copyright 2014-2015 John Lawson * * 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. */ #include "stream_iterator.h" #include <iostream> /* Need iostream for std::cin. */ #include "equiv_quiver_matrix.h" namespace cluster { template<class T> StreamIterator<T>::StreamIterator() : has_next_(false), str_(), input_(&std::cin, NullDeleter()) {} template<class T> StreamIterator<T>::StreamIterator(std::istream& stream) : input_(&stream, NullDeleter()) { has_next_ = static_cast<bool>(std::getline(*input_, str_)); } template<class T> std::shared_ptr<T> StreamIterator<T>::next() { std::shared_ptr<T> result = std::make_shared<T>(str_); do { has_next_ = static_cast<bool>(std::getline(*input_, str_)); } while (has_next_ && str_[0] != '{'); return std::move(result); } template<class T> bool StreamIterator<T>::has_next() { return has_next_; } template class StreamIterator<IntMatrix>; template class StreamIterator<QuiverMatrix>; template class StreamIterator<EquivQuiverMatrix>; }
jwlawson/qv
src/stream_iterator.cc
C++
apache-2.0
1,563
# Copyright 2015 Isotoma Limited # # 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. from touchdown.core import argument, resource, serializers from .provisioner import Provisioner class Output(resource.Resource): resource_name = "output" name = argument.String() provisioner = argument.Resource(Provisioner) class OutputAsString(serializers.Serializer): def __init__(self, resource): self.resource = resource def render(self, runner, object): if self.pending(runner, object): return serializers.Pending(self.resource) # Extract the contents from the file on the (potentially remote) target service = runner.get_service(self.resource.provisioner.target, "describe") client = service.get_client() return client.get_path_contents(self.resource.name) def pending(self, runner, object): provisioner = runner.get_service(self.resource.provisioner, "apply") return provisioner.object["Result"] == "Pending" def dependencies(self, object): return frozenset((self.resource,)) argument.String.register_adapter(Output, lambda r: OutputAsString(r)) class OutputAsBytes(serializers.Serializer): def __init__(self, resource): self.resource = resource def render(self, runner, object): if self.pending(runner, object): return serializers.Pending(self.resource) # Extract the contents from the file on the (potentially remote) target service = runner.get_service(self.resource.provisioner.target, "describe") client = service.get_client() return client.get_path_bytes(self.resource.name) def pending(self, runner, object): provisioner = runner.get_service(self.resource.provisioner, "apply") return provisioner.object["Result"] == "Pending" def dependencies(self, object): return frozenset((self.resource,)) argument.Bytes.register_adapter(Output, lambda r: OutputAsBytes(r))
yaybu/touchdown
touchdown/provisioner/output.py
Python
apache-2.0
2,488
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2022] EMBL-European Bioinformatics Institute # # 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. =pod =head1 NAME transfer_ig_genes.pl =head1 DESCRIPTION This script transfers IG gene segments from a source ("query") DB to an output ("target") DB. In the process, if the "query" gene segment overlaps at the exon level with a gene (of a specified biotype) in the target DB, the "query" gene will *overwrite* the "target" one. Note: the script expects the query DB to contain *no other gene types* except Ig gene segments. =head1 OPTIONS =head2 DB connection: =head3 DB containing query (source) Ig gene segments -qydbuser Read-only username to connect to query DB -qydbhost Where the query DB is -qydbname query DB name -qydbport Port to connect to query DB =head3 DB containing target (output) genes (some of them to be overwritten by "query" genes) -tgdbuser Username to connect to target DB with write permissions -tgdbpass Password to connect to target DB -tgdbhost Where the target DB is -tgdbname target DB name -tgdbport Port to connect to target DB =head3 DB containing DNA sequences. You must provide such details if your query and/or target DB contains no DNA sequence. -dnadbuser Read-only username to connect to DNA DB -dnadbhost Where the DNA DB is -dnadbname DNA DB name -dnadbport Port to connect to DNA DB -path The version of the assembly you want to fetch DNA sequences from (e.g "GRCh37", "NCBIM37") ----------------------------------------------------------------------- =head2 Analysis and output options: -tgbiotypes A list of biotypes of target genes which should be compared against query genes *and* can be replaced by query genes if substantial exon overlap is found between the query and target. The list should be comma-separated with no whitespace, e.g."protein_coding,pseudogene" -sub_biotypes Optional. A boolean flag to indicate whether a biotype substitution check needs to be done. Switched off by default. The check mainly concerns copying Ig gene segments from Vega DB (query DB) to a target DB which already contains some Ig gene segments from Ensembl. Vega Ig gene segments always have priority over Ensembl ones, so Vega Ig models will overwrite Ensembl ones. However, Ensembl Ig models sometimes have more detailed biotypes (e.g. "IG_V_gene" instead of simply "IG_gene"), and we want to keep the more elaborate biotypes. Therefore, the script can check if the target gene has a biotype starting with "IG*", and if yes, the script will assign the original target's biotype onto the overwriting Vega Ig model. -verbose A boolean option to get more print statements to follow the script. Set to 0 (not verbose) by default. =cut #!/usr/bin/env perl use strict; use warnings; use Getopt::Long qw(:config no_ignore_case); use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::DBSQL::DBAdaptor; use Digest::MD5 qw(md5_hex); my ( $dbname, $dbhost, $dbuser, $dbport, $tgdbname, $tgdbhost, $tgdbuser, $tgdbport, $tgdbpass, $path, @tg_biotypes, %tg_biotypes, $tg_biotypes, $dna_dbuser, $dna_dbhost, $dna_dbname, $dna_dbport ); $dbuser = 'ensro' ; $dbport = 3306 ; $tgdbuser = 'ensro' ; $tgdbport = 3306 ; $dna_dbuser = 'ensro' ; $dna_dbport = 3306 ; my $sub_biotypes = 0; my $verbose = 0; GetOptions( 'qydbname|dbname|db|D=s' => \$dbname, 'qydbuser|dbuser|user|u=s' => \$dbuser, 'qydbhost|dbhost|host|h=s' => \$dbhost, 'qydbport|dbport|port|P=s' => \$dbport, 'tgdbname=s' => \$tgdbname, 'tgdbuser=s' => \$tgdbuser, 'tgdbhost=s' => \$tgdbhost, 'tgdbport=s' => \$tgdbport, 'tgdbpass=s' => \$tgdbpass, 'tgbiotypes=s' => \$tg_biotypes, 'dnadbuser:s' => \$dna_dbuser, 'dnadbhost:s' => \$dna_dbhost, 'dnadbname:s' => \$dna_dbname, 'dnadbport:s' => \$dna_dbport, 'sub_biotypes!'=> \$sub_biotypes, 'verbose!' => \$verbose, 'path=s' => \$path ); my $qy_db = Bio::EnsEMBL::DBSQL::DBAdaptor-> new( '-dbname' => $dbname, '-host' => $dbhost, '-user' => $dbuser, '-port' => $dbport, ); my $tg_db = Bio::EnsEMBL::DBSQL::DBAdaptor-> new( '-dbname' => $tgdbname, '-host' => $tgdbhost, '-user' => $tgdbuser, '-port' => $tgdbport, '-pass' => $tgdbpass ); my $qyDB_has_DNA = check_if_DB_contains_DNA($qy_db); my $tgDB_has_DNA = check_if_DB_contains_DNA($tg_db); if ($qyDB_has_DNA == 0 || $tgDB_has_DNA == 0) { if (!defined $dna_dbname || !defined $dna_dbhost) { throw ("You must provide both -dnadbname and -dnadbhost on the commandline to connect to ". "DNA_DB or else the code will die when trying to fully load genes."); } my $dnadb = Bio::EnsEMBL::DBSQL::DBAdaptor-> new( -dbname => $dna_dbname, -host => $dna_dbhost, -user => $dna_dbuser, -port => $dna_dbport, -path => $path ); if ($qyDB_has_DNA == 0) { print "Attaching DNA_DB to " . $qy_db->dbc->dbname . "\n"; $qy_db->dnadb($dnadb); } if ($tgDB_has_DNA ==0) { print "Attaching DNA_DB to " . $tg_db->dbc->dbname . "\n"; $tg_db->dnadb($dnadb); } } print "\n"; if ($tg_biotypes) { @tg_biotypes = split (",",$tg_biotypes); print "This is your array of transcript biotypes which can be overwritten by Ig models should there be exon overlap : ",join(" - ",@tg_biotypes),"\n"; map { $tg_biotypes{$_} = 1 } @tg_biotypes; } else { map { $tg_biotypes{$_} = 1 } ('protein_coding', 'pseudogene'); } $verbose and print STDERR "\nCurrent target db gene summary:\n" . &gene_stats_string . "\n"; my (@genes, %genes_by_slice); $verbose and print STDERR "Fetching new genes...\n"; if (@ARGV) { foreach my $slid (@ARGV) { my $sl = $qy_db->get_SliceAdaptor->fetch_by_name($slid); my $tl_sl = $qy_db->get_SliceAdaptor->fetch_by_region('toplevel', $sl->seq_region_name); my @genes = @{$sl->get_all_Genes}; @genes = map { $_->transfer($tl_sl) } @genes; push @{$genes_by_slice{$sl->seq_region_name}}, @genes; } } else { @genes = @{$qy_db->get_GeneAdaptor->fetch_all}; } ######################################################### # Fully load query DB (source) Ig genes to keep their # protein annotation features ######################################################### my ($new_sid_hash, $pep_feat_hash); $verbose and print STDERR "Fully loading genes...\n"; $pep_feat_hash = &fully_load_genes(\@genes); ######################################################## # Find relationships between new genes and old geneset ######################################################## $verbose and print STDERR "Comparing new genes to current...\n"; my ($genes_to_delete_hash, $stable_id_event_hash); if ($sub_biotypes){ ($genes_to_delete_hash, $stable_id_event_hash) = &compare_new_genes_with_current_genes(\@genes, 1); }else{ ($genes_to_delete_hash, $stable_id_event_hash) = &compare_new_genes_with_current_genes(\@genes, 0); } ######################################################## # remove old genes and store new ones ######################################################## $verbose and print STDERR "Storing new genes...\n"; @genes = @{&store_genes($pep_feat_hash, \@genes)}; $verbose and print "Removing interfering old genes...\n"; foreach my $g (values %$genes_to_delete_hash) { $tg_db->get_GeneAdaptor->remove($g); } $verbose and printf(STDERR "Done (%s removed, %d added)\n%s\n", scalar(keys %$genes_to_delete_hash), scalar(@genes), &gene_stats_string); ############################################################## sub fully_load_genes { my $glist = shift; my $prot_feat_hash = {}; foreach my $g (@$glist) { foreach my $t (@{$g->get_all_Transcripts}) { foreach my $e (@{$t->get_all_Exons}) { $e->get_all_supporting_features; } my $tr = $t->translation; if (defined $tr) { # adaptor cascade for gene does not handle protein # features. In order to do that here, we have to keep # the the translation object so that we can obtain # its new dbID after storage $prot_feat_hash->{$tr->dbID} = [$tr]; foreach my $pf (@{$tr->get_all_ProteinFeatures}) { push @{$prot_feat_hash->{$tr->dbID}}, $pf; } } $t->get_all_supporting_features; } } return $prot_feat_hash; } ###################################################################### ###################################################################### sub store_genes { my ($prot_feat_hash, $glist) = @_; my $g_adap = $tg_db->get_GeneAdaptor; my $p_adap = $tg_db->get_ProteinFeatureAdaptor; my $dbea = $tg_db->get_DBEntryAdaptor; foreach my $g (@$glist) { $g_adap->store($g); } # At this point, all translations should have new dbIDs. # We can now store the protein features foreach my $old_dbid (keys %$prot_feat_hash) { my ($trn, @feats) = @{$prot_feat_hash->{$old_dbid}}; my $new_dbid = $trn->dbID; foreach my $f (@feats) { $p_adap->store($f, $new_dbid); } } # finally, refetch the stored genes from the target database # so that they we are working exclusively with target databases # adaptors from here on in my @tg_genes; foreach my $g (@$glist) { my $ng = $g_adap->fetch_by_dbID($g->dbID); foreach my $t (@{$ng->get_all_Transcripts}) { $t->get_all_supporting_features; $t->translation; foreach my $e (@{$t->get_all_Exons}) { $e->get_all_supporting_features; } } push @tg_genes, $ng; } return \@tg_genes; } ###################################################################### sub compare_new_genes_with_current_genes { my ($glist, $sub_biotypes) = @_; my (%by_slice, %genes_to_remove, %stable_id_event); map { push @{$by_slice{$_->slice->seq_region_name}}, $_ } @$glist; foreach my $sr_id (keys %by_slice) { my @g = sort { $a->start <=> $b->start } @{$by_slice{$sr_id}}; my $tg_tl_slice = $tg_db->get_SliceAdaptor->fetch_by_region('toplevel', $sr_id); foreach my $g (@g) { # Need to fully load the genes $g->load(); my $oslice = $tg_db->get_SliceAdaptor->fetch_by_region('toplevel', $sr_id, $g->start, $g->end); my @ogenes = map { $_->transfer($tg_tl_slice) } @{$oslice->get_all_Genes}; @ogenes = grep { exists($tg_biotypes{$_->biotype}) } @ogenes; # print "YOUR HAVE THIS ORIGINAL GENES: ",scalar(@ogenes),"\n"; if (@ogenes) { foreach my $t (@{$g->get_all_Transcripts}) { my @exons = @{$g->get_all_Exons}; foreach my $og (@ogenes) { # Fully load the genes $og->load(); foreach my $ot (@{$og->get_all_Transcripts}) { my $has_exon_overlap = 0; PAIR: foreach my $oe (@{$ot->get_all_Exons}) { foreach my $e (@exons) { if ($e->strand == $oe->strand and $e->overlaps($oe)) { $has_exon_overlap = 1; last PAIR; } } } if ($has_exon_overlap) { # transcripts $t and $ot have exon overlap # therefore: # delete gene $og (and all transcripts) # map $og to $g # map $ot to $t # map $ot->translation to $t->translation # Do a biotype check here if "sub_biotypes" flag # is set to 1. # If the original/target gene (to be replaced) has # an "IG*" biotype, we keep the target biotype as # it's already quite specific. # i.e. we do replace the target gene *model* with # the query *model* but the replaced gene will # retain its original biotype. if ($sub_biotypes == 1){ if ($og->biotype =~/IG/){ $g->biotype($og->biotype); $t->biotype($ot->biotype); } } $genes_to_remove{$og->dbID} = $og; } } } } } } } return (\%genes_to_remove, \%stable_id_event); } ###################################################################### sub gene_stats_string { my $summary_string = ""; my $sql = "select biotype, count(*) from gene group by biotype order by biotype"; my $st = $tg_db->dbc->prepare($sql); $st->execute; while(my ($tp, $c) = $st->fetchrow_array) { $summary_string .= sprintf("%-20s %5d\n", $tp, $c); } $st->finish; return $summary_string; } ####################################################################### sub check_if_DB_contains_DNA { my ($db) = @_; my $sql_command = "select count(*) from dna"; my $sth = $db->dbc->prepare($sql_command); $sth->execute(); my @dna_array = $sth->fetchrow_array; if ($dna_array[0] > 0) { print "Your DB ". $db->dbc->dbname ." contains DNA sequences. No need to attach a ". "DNA_DB to it.\n" if ($verbose); return 1; } else { print "Your DB ". $db->dbc->dbname ." does not contain DNA sequences.\n" if ($verbose); return 0; } }
Ensembl/ensembl-analysis
scripts/ig/transfer_gene_segments.pl
Perl
apache-2.0
15,232
/* * 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.beam.runners.dataflow.worker; import static org.junit.Assert.assertThat; import java.io.IOException; import java.util.Collection; import java.util.Collections; import org.apache.beam.runners.core.KeyedWorkItem; import org.apache.beam.runners.core.StateNamespace; import org.apache.beam.runners.core.StateNamespaces; import org.apache.beam.runners.core.TimerInternals.TimerData; import org.apache.beam.runners.dataflow.worker.WindmillKeyedWorkItem.FakeKeyedWorkItemCoder; import org.apache.beam.runners.dataflow.worker.windmill.Windmill; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.CollectionCoder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.StringUtf8Coder; import org.apache.beam.sdk.state.TimeDomain; import org.apache.beam.sdk.testing.CoderProperties; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.transforms.windowing.IntervalWindow; import org.apache.beam.sdk.transforms.windowing.PaneInfo; import org.apache.beam.sdk.transforms.windowing.PaneInfo.Timing; import org.apache.beam.sdk.util.WindowedValue; import org.apache.beam.vendor.grpc.v1p26p0.com.google.protobuf.ByteString; import org.hamcrest.Matchers; import org.joda.time.Instant; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** Tests for {@link WindmillKeyedWorkItem}. */ @RunWith(JUnit4.class) public class WindmillKeyedWorkItemTest { private static final String STATE_FAMILY = "state"; private static final String KEY = "key"; private static final ByteString SERIALIZED_KEY = ByteString.copyFromUtf8(KEY); private static final Coder<IntervalWindow> WINDOW_CODER = IntervalWindow.getCoder(); @SuppressWarnings({"unchecked", "rawtypes"}) private static final Coder<Collection<? extends BoundedWindow>> WINDOWS_CODER = (Coder) CollectionCoder.of(WINDOW_CODER); private static final Coder<String> VALUE_CODER = StringUtf8Coder.of(); private static final IntervalWindow WINDOW_1 = new IntervalWindow(new Instant(0), new Instant(10)); private static final StateNamespace STATE_NAMESPACE_1 = StateNamespaces.window(WINDOW_CODER, WINDOW_1); private static final IntervalWindow WINDOW_2 = new IntervalWindow(new Instant(10), new Instant(20)); private static final StateNamespace STATE_NAMESPACE_2 = StateNamespaces.window(WINDOW_CODER, WINDOW_2); @Mock private StreamingModeExecutionContext mockContext; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void testElementIteration() throws Exception { Windmill.WorkItem.Builder workItem = Windmill.WorkItem.newBuilder().setKey(SERIALIZED_KEY).setWorkToken(17); Windmill.InputMessageBundle.Builder chunk1 = workItem.addMessageBundlesBuilder(); chunk1.setSourceComputationId("computation"); addElement(chunk1, 5, "hello", WINDOW_1, paneInfo(0)); addElement(chunk1, 7, "world", WINDOW_2, paneInfo(2)); Windmill.InputMessageBundle.Builder chunk2 = workItem.addMessageBundlesBuilder(); chunk2.setSourceComputationId("computation"); addElement(chunk2, 6, "earth", WINDOW_1, paneInfo(1)); KeyedWorkItem<String, String> keyedWorkItem = new WindmillKeyedWorkItem<>( KEY, workItem.build(), WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); assertThat( keyedWorkItem.elementsIterable(), Matchers.contains( WindowedValue.of("hello", new Instant(5), WINDOW_1, paneInfo(0)), WindowedValue.of("world", new Instant(7), WINDOW_2, paneInfo(2)), WindowedValue.of("earth", new Instant(6), WINDOW_1, paneInfo(1)))); } private void addElement( Windmill.InputMessageBundle.Builder chunk, long timestamp, String value, IntervalWindow window, PaneInfo pane) throws IOException { ByteString encodedMetadata = WindmillSink.encodeMetadata(WINDOWS_CODER, Collections.singletonList(window), pane); chunk .addMessagesBuilder() .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(new Instant(timestamp))) .setData(ByteString.copyFromUtf8(value)) .setMetadata(encodedMetadata); } private PaneInfo paneInfo(int index) { return PaneInfo.createPane(false, false, Timing.EARLY, index, -1); } /** Make sure that event time timers are processed before other timers. */ @Test public void testTimerOrdering() throws Exception { Windmill.WorkItem workItem = Windmill.WorkItem.newBuilder() .setKey(SERIALIZED_KEY) .setWorkToken(17) .setTimers( Windmill.TimerBundle.newBuilder() .addTimers( makeSerializedTimer(STATE_NAMESPACE_1, 0, Windmill.Timer.Type.REALTIME)) .addTimers( makeSerializedTimer(STATE_NAMESPACE_1, 1, Windmill.Timer.Type.WATERMARK)) .addTimers( makeSerializedTimer(STATE_NAMESPACE_1, 2, Windmill.Timer.Type.REALTIME)) .addTimers( makeSerializedTimer(STATE_NAMESPACE_2, 3, Windmill.Timer.Type.WATERMARK)) .build()) .build(); KeyedWorkItem<String, String> keyedWorkItem = new WindmillKeyedWorkItem<>(KEY, workItem, WINDOW_CODER, WINDOWS_CODER, VALUE_CODER); assertThat( keyedWorkItem.timersIterable(), Matchers.contains( makeTimer(STATE_NAMESPACE_1, 1, TimeDomain.EVENT_TIME), makeTimer(STATE_NAMESPACE_2, 3, TimeDomain.EVENT_TIME), makeTimer(STATE_NAMESPACE_1, 0, TimeDomain.PROCESSING_TIME), makeTimer(STATE_NAMESPACE_1, 2, TimeDomain.PROCESSING_TIME))); } private static Windmill.Timer makeSerializedTimer( StateNamespace ns, long timestamp, Windmill.Timer.Type type) { return Windmill.Timer.newBuilder() .setTag( WindmillTimerInternals.timerTag( WindmillNamespacePrefix.SYSTEM_NAMESPACE_PREFIX, TimerData.of( ns, new Instant(timestamp), new Instant(timestamp), WindmillTimerInternals.timerTypeToTimeDomain(type)))) .setTimestamp(WindmillTimeUtils.harnessToWindmillTimestamp(new Instant(timestamp))) .setType(type) .setStateFamily(STATE_FAMILY) .build(); } private static TimerData makeTimer(StateNamespace ns, long timestamp, TimeDomain domain) { return TimerData.of(ns, new Instant(timestamp), new Instant(timestamp), domain); } @Test public void testCoderIsSerializableWithWellKnownCoderType() { CoderProperties.coderSerializable( FakeKeyedWorkItemCoder.of( KvCoder.of(GlobalWindow.Coder.INSTANCE, GlobalWindow.Coder.INSTANCE))); } }
iemejia/incubator-beam
runners/google-cloud-dataflow-java/worker/src/test/java/org/apache/beam/runners/dataflow/worker/WindmillKeyedWorkItemTest.java
Java
apache-2.0
7,859
/* * Copyright 2011-2022 GatlingCorp (https://gatling.io) * * 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 io.gatling.http.check.sse import io.gatling.commons.validation.Validation import io.gatling.core.check.{ Check, CheckResult } import io.gatling.core.session.{ Expression, Session } final class SseCheck(wrapped: Check[String]) extends Check[String] { override def check(message: String, session: Session, preparedCache: Check.PreparedCache): Validation[CheckResult] = wrapped.check(message, session, preparedCache) override def checkIf(condition: Expression[Boolean]): SseCheck = new SseCheck(wrapped.checkIf(condition)) override def checkIf(condition: (String, Session) => Validation[Boolean]): SseCheck = new SseCheck(wrapped.checkIf(condition)) }
gatling/gatling
gatling-http/src/main/scala/io/gatling/http/check/sse/SseCheck.scala
Scala
apache-2.0
1,290
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.plaidapp.core.util; import android.content.res.ColorStateList; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.URLSpan; import android.text.util.Linkify; import android.widget.TextView; import androidx.annotation.ColorInt; import in.uncod.android.bypass.LoadImageCallback; import in.uncod.android.bypass.Markdown; import in.uncod.android.bypass.style.TouchableUrlSpan; /** * Utility methods for working with HTML. */ public class HtmlUtils { private HtmlUtils() { } /** * Work around some 'features' of TextView and URLSpans. i.e. vanilla URLSpans do not react to * touch so we replace them with our own {@link TouchableUrlSpan} * & {@link LinkTouchMovementMethod} to fix this. * <p/> * Setting a custom MovementMethod on a TextView also alters touch handling (see * TextView#fixFocusableAndClickableSettings) so we need to correct this. */ public static void setTextWithNiceLinks(TextView textView, CharSequence input) { textView.setText(input); textView.setMovementMethod(LinkTouchMovementMethod.getInstance()); textView.setFocusable(false); textView.setClickable(false); textView.setLongClickable(false); } static SpannableStringBuilder linkifyPlainLinks( CharSequence input, ColorStateList linkTextColor, @ColorInt int linkHighlightColor) { final SpannableString plainLinks = new SpannableString(input); // copy of input // Linkify doesn't seem to work as expected on M+ // TODO: figure out why //Linkify.addLinks(plainLinks, Linkify.WEB_URLS); final URLSpan[] urlSpans = plainLinks.getSpans(0, plainLinks.length(), URLSpan.class); // add any plain links to the output final SpannableStringBuilder ssb = new SpannableStringBuilder(input); for (URLSpan urlSpan : urlSpans) { ssb.removeSpan(urlSpan); ssb.setSpan(new TouchableUrlSpan(urlSpan.getURL(), linkTextColor, linkHighlightColor), plainLinks.getSpanStart(urlSpan), plainLinks.getSpanEnd(urlSpan), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return ssb; } /** * Parse Markdown and plain-text links. * <p/> * {@link Markdown} does not handle plain text links (i.e. not md syntax) and requires a * {@code String} input (i.e. squashes any spans). {@link Linkify} handles plain links but also * removes any existing spans. So we can't just run our input through both. * <p/> * Instead we use the markdown lib, then take a copy of the output and Linkify * <strong>that</strong>. We then find any {@link URLSpan}s and add them to the markdown output. * Best of both worlds. */ public static CharSequence parseMarkdownAndPlainLinks( String input, Markdown markdown, ColorStateList linkTextColors, @ColorInt int highlightColor, LoadImageCallback loadImageCallback) { CharSequence markedUp = markdown.markdownToSpannable(input, linkTextColors, highlightColor, loadImageCallback); return linkifyPlainLinks(markedUp, linkTextColors, highlightColor); } }
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/util/HtmlUtils.java
Java
apache-2.0
3,982
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.adwords.awreporting.model.entities; import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvField; import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvReport; import com.google.api.ads.adwords.awreporting.model.csv.annotation.MoneyField; import com.google.api.ads.adwords.awreporting.model.util.BigDecimalUtil; import com.google.api.ads.adwords.awreporting.model.util.UrlHashUtil; import com.google.api.ads.adwords.lib.jaxb.v201502.ReportDefinitionReportType; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * Specific report class for ReportDestinationUrl * * @author marcwan@google.com (Marc Wandschneider) */ @Entity @com.googlecode.objectify.annotation.Entity @Table(name = "AW_ReportDestinationUrl") @CsvReport(value = ReportDefinitionReportType.DESTINATION_URL_REPORT) public class ReportDestinationUrl extends ReportBase { @Column(name = "ADGROUPID") @CsvField(value = "Ad group ID", reportField = "AdGroupId") private Long adGroupId; @Column(name = "ADGROUPNAME") @CsvField(value = "Ad group", reportField = "AdGroupName") private String adGroupName; @Column(name = "ADGROUPSTATUS") @CsvField(value = "Ad group state", reportField = "AdGroupStatus") private String adGroupStatus; @Column(name = "CAMPAIGNID") @CsvField(value = "Campaign ID", reportField = "CampaignId") private Long campaignId; @Column(name = "CAMPAIGNNAME") @CsvField(value = "Campaign", reportField = "CampaignName") private String campaignName; @Column(name = "CAMPAIGNSTATUS") @CsvField(value = "Campaign state", reportField = "CampaignStatus") private String campaignStatus; @Column(name = "CRITERIADESTINATIONURL") @CsvField(value = "Keyword/Placement destination URL", reportField = "CriteriaDestinationUrl") private String criteriaDestinationUrl; @Column(name = "CRITERIAPARAMETERS") @CsvField(value = "Keyword / Placement", reportField = "CriteriaParameters") private String criteriaParameters; @Column(name = "CRITERIASTATUS") @CsvField(value = "Keyword/Placement state", reportField = "CriteriaStatus") private String criteriaStatus; @Column(name = "CRITERIATYPENAME") @CsvField(value = "Match type", reportField = "CriteriaTypeName") private String criteriaTypeName; @Column(name = "EFFECTIVEDESTINATIONURL", length = 2048) @CsvField(value = "Destination URL", reportField = "EffectiveDestinationUrl") private String effectiveDestinationUrl; @Column(name = "ISNEGATIVE") @CsvField(value = "Is negative", reportField = "IsNegative") private String isNegative; @Column(name = "ACTIVE_VIEW_CPM") @CsvField(value = "Active View avg. CPM", reportField = "ActiveViewCpm") @MoneyField private BigDecimal activeViewCpm; @Column(name = "ACTIVE_VIEW_IMPRESSIONS") @CsvField(value = "Active View avg. CPM", reportField = "ActiveViewImpressions") private Long activeViewImpressions; @Column(name = "CONVERSION_TRACKER_ID") @CsvField(value = "Conversion Tracker Id", reportField = "ConversionTrackerId") private Long conversionTrackerId; /** * Hibernate needs an empty constructor */ public ReportDestinationUrl() { } public ReportDestinationUrl(Long topAccountId, Long accountId) { this.topAccountId = topAccountId; this.accountId = accountId; } @Override public void setId() { // Generating unique id after having accountId, campaignId, adGroupId and date this.id = ""; if (this.getAccountId() != null) { this.id += this.getAccountId() + "-"; } if (this.getCampaignId() != null) { this.id += this.getCampaignId() + "-"; } if (this.getAdGroupId() != null) { this.id += this.getAdGroupId() + "-"; } if (this.getCriteriaParameters() != null) { this.id += this.getCriteriaParameters() + "-"; } // Generating a SHA-1 Hash of the URLs for ID generation if (this.getEffectiveDestinationUrl() != null) { this.id += UrlHashUtil.createUrlHash(this.getEffectiveDestinationUrl()); } this.id += setIdDates(); // Adding extra fields for unique ID if (this.getAdNetwork() != null && this.getAdNetwork().length() > 0) { this.id += "-" + this.getAdNetwork(); } if (this.getAdNetworkPartners() != null && this.getAdNetworkPartners().length() > 0) { this.id += "-" + this.getAdNetworkPartners(); } if (this.getDevice() != null && this.getDevice().length() > 0) { this.id += "-" + this.getDevice(); } if (this.getClickType() != null && this.getClickType().length() > 0) { this.id += "-" + this.getClickType(); } } public Long getAdGroupId() { return adGroupId; } public void setAdGroupId(Long adGroupId) { this.adGroupId = adGroupId; } public String getAdGroupName() { return adGroupName; } public void setAdGroupName(String adGroupName) { this.adGroupName = adGroupName; } public String getAdGroupStatus() { return adGroupStatus; } public void setAdGroupStatus(String adGroupStatus) { this.adGroupStatus = adGroupStatus; } public Long getCampaignId() { return campaignId; } public void setCampaignId(Long campaignId) { this.campaignId = campaignId; } public String getCampaignName() { return campaignName; } public void setCampaignName(String campaignName) { this.campaignName = campaignName; } public String getCampaignStatus() { return campaignStatus; } public void setCampaignStatus(String campaignStatus) { this.campaignStatus = campaignStatus; } public String getCriteriaDestinationUrl() { return criteriaDestinationUrl; } public void setCriteriaDestinationUrl(String criteriaDestinationUrl) { this.criteriaDestinationUrl = criteriaDestinationUrl; } public String getCriteriaParameters() { return criteriaParameters; } public void setCriteriaParameters(String criteriaParameters) { this.criteriaParameters = criteriaParameters; } public String getCriteriaStatus() { return criteriaStatus; } public void setCriteriaStatus(String criteriaStatus) { this.criteriaStatus = criteriaStatus; } public String getCriteriaTypeName() { return criteriaTypeName; } public void setCriteriaTypeName(String criteriaTypeName) { this.criteriaTypeName = criteriaTypeName; } public String getEffectiveDestinationUrl() { return effectiveDestinationUrl; } public void setEffectiveDestinationUrl(String effectiveDestinationUrl) { this.effectiveDestinationUrl = effectiveDestinationUrl; } public String getIsNegative() { return isNegative; } public void setIsNegative(String isNegative) { this.isNegative = isNegative; } public String getActiveViewCpm() { return BigDecimalUtil.formatAsReadable(activeViewCpm); } public BigDecimal getActiveViewCpmBigDecimal() { return activeViewCpm; } public void setActiveViewCpm(String activeViewCpm) { this.activeViewCpm = BigDecimalUtil.parseFromNumberStringPercentage(activeViewCpm); } public Long getActiveViewImpressions() { return activeViewImpressions; } public void setActiveViewImpressions(Long activeViewImpressions) { this.activeViewImpressions = activeViewImpressions; } public Long getConversionTrackerId() { return conversionTrackerId; } public void setConversionTrackerId(Long conversionTrackerId) { this.conversionTrackerId = conversionTrackerId; } }
tsib0/aw-reporting
aw-reporting-model/src/main/java/com/google/api/ads/adwords/awreporting/model/entities/ReportDestinationUrl.java
Java
apache-2.0
8,183
package pub.ayada.scala.sparkUtils.etl.transform import scala.xml.Node import org.apache.spark.sql.DataFrame import org.apache.spark.sql.hive.HiveContext import org.apache.spark.storage.StorageLevel import pub.ayada.scala.utils.DateTimeUtils import pub.ayada.scala.sparkUtils.cmn.UtilFuncs object Transformer { def getTransformerProps(xFerNode : Node, defaults : scala.collection.mutable.Map[String, String]) : pub.ayada.scala.sparkUtils.etl.transform.TransformerProps = { val Id = (xFerNode \ "@id").text.trim val SrcDF = (xFerNode \ "@srcDF").text.trim.split(",") val Typ = (xFerNode \ "@type").text.trim val RegisterTempTable = ("true" == (xFerNode \ "@registerTempTable").text.trim.toLowerCase) val Repartition = (xFerNode \ "@repartition").text.trim val Persist = (xFerNode \ "@persist").text.trim.toUpperCase val LoadCount = ("true" == (xFerNode \ "@loadCount").text.trim.toLowerCase) val PrintSchema = ("true" == (xFerNode \ "@printSchema").text.trim.toLowerCase) val ConditionExpr = xFerNode.text.trim new pub.ayada.scala.sparkUtils.etl.transform.TransformerProps( id = Id, srcDF = SrcDF, typ = Typ, registerTempTable = RegisterTempTable, persist = StorageLevel.fromString(if ("" != Persist) Persist else defaults.get("defaultStorageLevel").get), repartition = { if ("" == Repartition) 0 else Repartition.toInt }, loadCount = LoadCount, printSchema = PrintSchema, conditionExpr = ConditionExpr) } def runTransforms(jobId : String, hiveContext : HiveContext, props : List[pub.ayada.scala.sparkUtils.etl.transform.TransformerProps], defaults : scala.collection.mutable.Map[String, String], dfs : scala.collection.mutable.Map[String, pub.ayada.scala.sparkUtils.etl.transform.TransformerDFs]) : scala.collection.mutable.ListBuffer[pub.ayada.scala.sparkUtils.etl.transform.TransformerProps] = { val parkedTransformations : scala.collection.mutable.ListBuffer[pub.ayada.scala.sparkUtils.etl.transform.TransformerProps] = scala.collection.mutable.ListBuffer() props.foreach(prop => { prop.srcDF.filter(_ != "").foreach(s => { var df : pub.ayada.scala.sparkUtils.etl.transform.TransformerDFs = dfs.getOrElse(s, null) if (null != df) df.useCount += 1 }) }) props.foreach(prop => { val taskID = s"Transformer-${jobId}-${prop.id}" try { println(DateTimeUtils.getFmtDtm(taskID) + "Prepping Transformarmation: " + prop.toString) var cont = true prop.srcDF.filter(_ != "").foreach({ srcDF => val paentDF = dfs.getOrElse(srcDF, null) if (cont && !dfs.contains(srcDF)) { cont = false println(DateTimeUtils.getFmtDtm(taskID) + "Wrn: Source DataFrame: '" + srcDF + "' not found. Parking current transformation") parkedTransformations += prop } }) if (cont) { var df2 : DataFrame = null prop.typ match { case "filter" => { val df = dfs.getOrElse(prop.srcDF(0), null) if (df == null) { println(DateTimeUtils.getFmtDtm(taskID) + " Failed to retrieve source DF to run the filter : " + prop.srcDF(0)) } df2 = df.df.filter(prop.conditionExpr).alias(prop.id) } case "sql" => { df2 = hiveContext.sql(prop.conditionExpr).alias(prop.id) } case _ => throw new Exception("Unknown transformation type received (valid:filter|sql) : " + prop.typ) } if (df2 == null) { println(DateTimeUtils.getFmtDtm(taskID) + s" DdataFrame is null : ${prop.id}") } println(DateTimeUtils.getFmtDtm(taskID) + s" Registering DF as temp table: ${prop.id}") if (prop.printSchema) { println(DateTimeUtils.getFmtDtm(taskID) + s"DF schema of : ${prop.id} ${df2.schema.treeString}") } var useCnt = 0; props.foreach(p => { p.srcDF.filter(_ != "").foreach(s => { if (s == prop.id) useCnt += 1 }) }) if (useCnt > 1 || (prop.persist != null && prop.persist != StorageLevel.NONE)) { val min = { if (prop.repartition > 0) prop.repartition else defaults.get("defaultNoOfDFPartitions").get.toInt } val res = UtilFuncs.calcOptimalPartitionCount(df2, min) println(pub.ayada.scala.utils.DateTimeUtils.getFmtDtm(taskID) + s"For DF : ${prop.id} Derived new Partition counts as newPartitions = ( cur_partitions/ cur_partition_capacity * 64MB ) or $min ==> ${res._3} . Calculation = ( ${res._1} / ${res._2 / 1024 / 1024}MB * 64MB)" ) val df3 = UtilFuncs.rePartitionAndPersist(df2, res._3, prop.persist) df3.registerTempTable(prop.id) dfs.put(prop.id, new pub.ayada.scala.sparkUtils.etl.transform.TransformerDFs(df3, useCnt, prop.loadCount, StorageLevel.NONE)) } else { df2.registerTempTable(prop.id) dfs.put(prop.id, new pub.ayada.scala.sparkUtils.etl.transform.TransformerDFs(df2, useCnt, prop.loadCount, prop.persist)) } } } catch { case t : Exception => { println(DateTimeUtils.getFmtDtm(taskID) + " Failed to complete the task for transformation ID: " + prop.id) t.printStackTrace() throw new Exception(t) } } }) parkedTransformations } }
k-ayada/SparkETL
pub/ayada/scala/sparkUtils/etl/transform/Transformer.scala
Scala
apache-2.0
6,459
<div class="container"> <div class="row"> <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2"> <form (ngSubmit)="onFormSubmit()" #frm="ngForm"> <div class="form-group"> <label for="email">Email</label> <input type="email" id="email" name="email" class="form-control" email ngModel required #email="ngModel"/> <span class="help-block" *ngIf="!email.valid && email.touched"> Invalid Email!! </span> </div> <div class="form-group"> <label for="subs">Subscription</label> <select id="subs" class="form-control" [ngModel]="defaultSubscription" name="subs" required #sub="ngModel"> <option *ngFor="let sub of subscriptions" value="sub">{{ sub }}</option> </select> </div> <span class="help-block" *ngIf="!sub.valid && sub.touched"> <p>Subscription is required!!</p> </span> <div class="form-group"> <label for="pass">Password</label> <input type="password" id="pass" name="pass" class="form-control" ngModel required #pass="ngModel"> </div> <span class="help-block" *ngIf="!pass.valid && pass.touched"> <p>Password is required!!</p> </span> <div class="form-group"> <button type="submit" id="submit" class="btn btn-primary" [disabled]="!frm.valid">Submit</button> </div> </form> </div> </div> <div class="row" *ngIf="submitted"> <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2"> <h3>Data entered</h3> <p>Email: {{ data.email}}</p> <p>Subscription: {{ data.subs}}</p> <p>Password: {{ data.pass}}</p> </div> </div> </div>
davidokun/Angular-js
forms-td-assignment/src/app/app.component.html
HTML
apache-2.0
1,866
<html> <head> <title>Title</title> </head> <body> <div> <h2>Code example</h2> <p>Here is some code sample <code>foo()</code></p> <code><pre> foo match { case "fish" => <*-> case "pig" => ^ ^ / * * \ | (..) | \--------/ } & & here() and.here.too() </pre></code> <p>See?</p> </div> </body> </html>
eigengo/sbt-mdrw
src/test/resources/code-activator.html
HTML
apache-2.0
382
from webfs import WebDirParser testDoc = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <title>Index of /ubuntu</title> </head> <body> <h1>Index of /ubuntu</h1> <pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a> <a href="?C=M;O=A">Last modified</a> <a href="?C=S;O=A">Size</a> <a href="?C=D;O=A">Description</a><hr><img src="/icons/back.gif" alt="[DIR]"> <a href="/">Parent Directory</a> - <img src="/icons/folder.gif" alt="[DIR]"> <a href="dists/">dists/</a> 18-Jun-2014 12:46 - <img src="/icons/folder.gif" alt="[DIR]"> <a href="indices/">indices/</a> 28-Apr-2008 17:47 - <img src="/icons/compressed.gif" alt="[ ]"> <a href="ls-lR.gz">ls-lR.gz</a> 28-Apr-2008 16:05 4.5M <img src="/icons/folder.gif" alt="[DIR]"> <a href="pool/">pool/</a> 14-Jan-2008 22:05 - <img src="/icons/folder.gif" alt="[DIR]"> <a href="project/">project/</a> 28-Jun-2013 11:52 - <hr></pre> <address>Apache/2.2.22 (Ubuntu) Server at old-releases.ubuntu.com Port 80</address> </body></html> """ def Test_ParsingTest(): wp = WebDirParser() wp.feed(testDoc) assert len(wp.entries) == 5 assert wp.entries.keys().sort() == ['dist', 'indices', 'ls-lR.gz', 'pool', 'project'].sort(),\ wp.entries.keys()
harun-emektar/webfs
tests/Test_WebDirParser.py
Python
apache-2.0
1,416
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: storedserverpaymentchannel.proto package com.google.leafcoin.protocols.channels; public final class ServerState { private ServerState() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface StoredServerPaymentChannelsOrBuilder extends com.google.protobuf.MessageOrBuilder { // repeated .paymentchannels.StoredServerPaymentChannel channels = 1; /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ java.util.List<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel> getChannelsList(); /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel getChannels(int index); /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ int getChannelsCount(); /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ java.util.List<? extends com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder> getChannelsOrBuilderList(); /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder getChannelsOrBuilder( int index); } /** * Protobuf type {@code paymentchannels.StoredServerPaymentChannels} * * <pre> * A set of StoredPaymentChannel's * </pre> */ public static final class StoredServerPaymentChannels extends com.google.protobuf.GeneratedMessage implements StoredServerPaymentChannelsOrBuilder { // Use StoredServerPaymentChannels.newBuilder() to construct. private StoredServerPaymentChannels(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private StoredServerPaymentChannels(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final StoredServerPaymentChannels defaultInstance; public static StoredServerPaymentChannels getDefaultInstance() { return defaultInstance; } public StoredServerPaymentChannels getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private StoredServerPaymentChannels( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { channels_ = new java.util.ArrayList<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel>(); mutable_bitField0_ |= 0x00000001; } channels_.add(input.readMessage(com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { channels_ = java.util.Collections.unmodifiableList(channels_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannels_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannels_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels.class, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels.Builder.class); } public static com.google.protobuf.Parser<StoredServerPaymentChannels> PARSER = new com.google.protobuf.AbstractParser<StoredServerPaymentChannels>() { public StoredServerPaymentChannels parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new StoredServerPaymentChannels(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<StoredServerPaymentChannels> getParserForType() { return PARSER; } // repeated .paymentchannels.StoredServerPaymentChannel channels = 1; public static final int CHANNELS_FIELD_NUMBER = 1; private java.util.List<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel> channels_; /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public java.util.List<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel> getChannelsList() { return channels_; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public java.util.List<? extends com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder> getChannelsOrBuilderList() { return channels_; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public int getChannelsCount() { return channels_.size(); } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel getChannels(int index) { return channels_.get(index); } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder getChannelsOrBuilder( int index) { return channels_.get(index); } private void initFields() { channels_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; for (int i = 0; i < getChannelsCount(); i++) { if (!getChannels(i).isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (int i = 0; i < channels_.size(); i++) { output.writeMessage(1, channels_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (int i = 0; i < channels_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, channels_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code paymentchannels.StoredServerPaymentChannels} * * <pre> * A set of StoredPaymentChannel's * </pre> */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannels_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannels_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels.class, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels.Builder.class); } // Construct using com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getChannelsFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (channelsBuilder_ == null) { channels_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { channelsBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannels_descriptor; } public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels getDefaultInstanceForType() { return com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels.getDefaultInstance(); } public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels build() { com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels buildPartial() { com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels result = new com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels(this); int from_bitField0_ = bitField0_; if (channelsBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { channels_ = java.util.Collections.unmodifiableList(channels_); bitField0_ = (bitField0_ & ~0x00000001); } result.channels_ = channels_; } else { result.channels_ = channelsBuilder_.build(); } onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels) { return mergeFrom((com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels other) { if (other == com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels.getDefaultInstance()) return this; if (channelsBuilder_ == null) { if (!other.channels_.isEmpty()) { if (channels_.isEmpty()) { channels_ = other.channels_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureChannelsIsMutable(); channels_.addAll(other.channels_); } onChanged(); } } else { if (!other.channels_.isEmpty()) { if (channelsBuilder_.isEmpty()) { channelsBuilder_.dispose(); channelsBuilder_ = null; channels_ = other.channels_; bitField0_ = (bitField0_ & ~0x00000001); channelsBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getChannelsFieldBuilder() : null; } else { channelsBuilder_.addAllMessages(other.channels_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { for (int i = 0; i < getChannelsCount(); i++) { if (!getChannels(i).isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannels) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // repeated .paymentchannels.StoredServerPaymentChannel channels = 1; private java.util.List<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel> channels_ = java.util.Collections.emptyList(); private void ensureChannelsIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { channels_ = new java.util.ArrayList<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel>(channels_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilder< com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder> channelsBuilder_; /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public java.util.List<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel> getChannelsList() { if (channelsBuilder_ == null) { return java.util.Collections.unmodifiableList(channels_); } else { return channelsBuilder_.getMessageList(); } } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public int getChannelsCount() { if (channelsBuilder_ == null) { return channels_.size(); } else { return channelsBuilder_.getCount(); } } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel getChannels(int index) { if (channelsBuilder_ == null) { return channels_.get(index); } else { return channelsBuilder_.getMessage(index); } } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder setChannels( int index, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel value) { if (channelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureChannelsIsMutable(); channels_.set(index, value); onChanged(); } else { channelsBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder setChannels( int index, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder builderForValue) { if (channelsBuilder_ == null) { ensureChannelsIsMutable(); channels_.set(index, builderForValue.build()); onChanged(); } else { channelsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder addChannels(com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel value) { if (channelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureChannelsIsMutable(); channels_.add(value); onChanged(); } else { channelsBuilder_.addMessage(value); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder addChannels( int index, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel value) { if (channelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureChannelsIsMutable(); channels_.add(index, value); onChanged(); } else { channelsBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder addChannels( com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder builderForValue) { if (channelsBuilder_ == null) { ensureChannelsIsMutable(); channels_.add(builderForValue.build()); onChanged(); } else { channelsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder addChannels( int index, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder builderForValue) { if (channelsBuilder_ == null) { ensureChannelsIsMutable(); channels_.add(index, builderForValue.build()); onChanged(); } else { channelsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder addAllChannels( java.lang.Iterable<? extends com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel> values) { if (channelsBuilder_ == null) { ensureChannelsIsMutable(); super.addAll(values, channels_); onChanged(); } else { channelsBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder clearChannels() { if (channelsBuilder_ == null) { channels_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { channelsBuilder_.clear(); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public Builder removeChannels(int index) { if (channelsBuilder_ == null) { ensureChannelsIsMutable(); channels_.remove(index); onChanged(); } else { channelsBuilder_.remove(index); } return this; } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder getChannelsBuilder( int index) { return getChannelsFieldBuilder().getBuilder(index); } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder getChannelsOrBuilder( int index) { if (channelsBuilder_ == null) { return channels_.get(index); } else { return channelsBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public java.util.List<? extends com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder> getChannelsOrBuilderList() { if (channelsBuilder_ != null) { return channelsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(channels_); } } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder addChannelsBuilder() { return getChannelsFieldBuilder().addBuilder( com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.getDefaultInstance()); } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder addChannelsBuilder( int index) { return getChannelsFieldBuilder().addBuilder( index, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.getDefaultInstance()); } /** * <code>repeated .paymentchannels.StoredServerPaymentChannel channels = 1;</code> */ public java.util.List<com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder> getChannelsBuilderList() { return getChannelsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder> getChannelsFieldBuilder() { if (channelsBuilder_ == null) { channelsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder>( channels_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); channels_ = null; } return channelsBuilder_; } // @@protoc_insertion_point(builder_scope:paymentchannels.StoredServerPaymentChannels) } static { defaultInstance = new StoredServerPaymentChannels(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:paymentchannels.StoredServerPaymentChannels) } public interface StoredServerPaymentChannelOrBuilder extends com.google.protobuf.MessageOrBuilder { // required uint64 bestValueToMe = 1; /** * <code>required uint64 bestValueToMe = 1;</code> */ boolean hasBestValueToMe(); /** * <code>required uint64 bestValueToMe = 1;</code> */ long getBestValueToMe(); // optional bytes bestValueSignature = 2; /** * <code>optional bytes bestValueSignature = 2;</code> */ boolean hasBestValueSignature(); /** * <code>optional bytes bestValueSignature = 2;</code> */ com.google.protobuf.ByteString getBestValueSignature(); // required uint64 refundTransactionUnlockTimeSecs = 3; /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ boolean hasRefundTransactionUnlockTimeSecs(); /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ long getRefundTransactionUnlockTimeSecs(); // required bytes contractTransaction = 4; /** * <code>required bytes contractTransaction = 4;</code> */ boolean hasContractTransaction(); /** * <code>required bytes contractTransaction = 4;</code> */ com.google.protobuf.ByteString getContractTransaction(); // required bytes clientOutput = 5; /** * <code>required bytes clientOutput = 5;</code> */ boolean hasClientOutput(); /** * <code>required bytes clientOutput = 5;</code> */ com.google.protobuf.ByteString getClientOutput(); // required bytes myKey = 6; /** * <code>required bytes myKey = 6;</code> */ boolean hasMyKey(); /** * <code>required bytes myKey = 6;</code> */ com.google.protobuf.ByteString getMyKey(); } /** * Protobuf type {@code paymentchannels.StoredServerPaymentChannel} * * <pre> * A server-side payment channel in serialized form, which can be reloaded later if the server restarts * </pre> */ public static final class StoredServerPaymentChannel extends com.google.protobuf.GeneratedMessage implements StoredServerPaymentChannelOrBuilder { // Use StoredServerPaymentChannel.newBuilder() to construct. private StoredServerPaymentChannel(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private StoredServerPaymentChannel(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final StoredServerPaymentChannel defaultInstance; public static StoredServerPaymentChannel getDefaultInstance() { return defaultInstance; } public StoredServerPaymentChannel getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private StoredServerPaymentChannel( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; bestValueToMe_ = input.readUInt64(); break; } case 18: { bitField0_ |= 0x00000002; bestValueSignature_ = input.readBytes(); break; } case 24: { bitField0_ |= 0x00000004; refundTransactionUnlockTimeSecs_ = input.readUInt64(); break; } case 34: { bitField0_ |= 0x00000008; contractTransaction_ = input.readBytes(); break; } case 42: { bitField0_ |= 0x00000010; clientOutput_ = input.readBytes(); break; } case 50: { bitField0_ |= 0x00000020; myKey_ = input.readBytes(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannel_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannel_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.class, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder.class); } public static com.google.protobuf.Parser<StoredServerPaymentChannel> PARSER = new com.google.protobuf.AbstractParser<StoredServerPaymentChannel>() { public StoredServerPaymentChannel parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new StoredServerPaymentChannel(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<StoredServerPaymentChannel> getParserForType() { return PARSER; } private int bitField0_; // required uint64 bestValueToMe = 1; public static final int BESTVALUETOME_FIELD_NUMBER = 1; private long bestValueToMe_; /** * <code>required uint64 bestValueToMe = 1;</code> */ public boolean hasBestValueToMe() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required uint64 bestValueToMe = 1;</code> */ public long getBestValueToMe() { return bestValueToMe_; } // optional bytes bestValueSignature = 2; public static final int BESTVALUESIGNATURE_FIELD_NUMBER = 2; private com.google.protobuf.ByteString bestValueSignature_; /** * <code>optional bytes bestValueSignature = 2;</code> */ public boolean hasBestValueSignature() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional bytes bestValueSignature = 2;</code> */ public com.google.protobuf.ByteString getBestValueSignature() { return bestValueSignature_; } // required uint64 refundTransactionUnlockTimeSecs = 3; public static final int REFUNDTRANSACTIONUNLOCKTIMESECS_FIELD_NUMBER = 3; private long refundTransactionUnlockTimeSecs_; /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ public boolean hasRefundTransactionUnlockTimeSecs() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ public long getRefundTransactionUnlockTimeSecs() { return refundTransactionUnlockTimeSecs_; } // required bytes contractTransaction = 4; public static final int CONTRACTTRANSACTION_FIELD_NUMBER = 4; private com.google.protobuf.ByteString contractTransaction_; /** * <code>required bytes contractTransaction = 4;</code> */ public boolean hasContractTransaction() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>required bytes contractTransaction = 4;</code> */ public com.google.protobuf.ByteString getContractTransaction() { return contractTransaction_; } // required bytes clientOutput = 5; public static final int CLIENTOUTPUT_FIELD_NUMBER = 5; private com.google.protobuf.ByteString clientOutput_; /** * <code>required bytes clientOutput = 5;</code> */ public boolean hasClientOutput() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>required bytes clientOutput = 5;</code> */ public com.google.protobuf.ByteString getClientOutput() { return clientOutput_; } // required bytes myKey = 6; public static final int MYKEY_FIELD_NUMBER = 6; private com.google.protobuf.ByteString myKey_; /** * <code>required bytes myKey = 6;</code> */ public boolean hasMyKey() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>required bytes myKey = 6;</code> */ public com.google.protobuf.ByteString getMyKey() { return myKey_; } private void initFields() { bestValueToMe_ = 0L; bestValueSignature_ = com.google.protobuf.ByteString.EMPTY; refundTransactionUnlockTimeSecs_ = 0L; contractTransaction_ = com.google.protobuf.ByteString.EMPTY; clientOutput_ = com.google.protobuf.ByteString.EMPTY; myKey_ = com.google.protobuf.ByteString.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; if (!hasBestValueToMe()) { memoizedIsInitialized = 0; return false; } if (!hasRefundTransactionUnlockTimeSecs()) { memoizedIsInitialized = 0; return false; } if (!hasContractTransaction()) { memoizedIsInitialized = 0; return false; } if (!hasClientOutput()) { memoizedIsInitialized = 0; return false; } if (!hasMyKey()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeUInt64(1, bestValueToMe_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, bestValueSignature_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeUInt64(3, refundTransactionUnlockTimeSecs_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeBytes(4, contractTransaction_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeBytes(5, clientOutput_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeBytes(6, myKey_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, bestValueToMe_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, bestValueSignature_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(3, refundTransactionUnlockTimeSecs_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(4, contractTransaction_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(5, clientOutput_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(6, myKey_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code paymentchannels.StoredServerPaymentChannel} * * <pre> * A server-side payment channel in serialized form, which can be reloaded later if the server restarts * </pre> */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannelOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannel_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannel_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.class, com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.Builder.class); } // Construct using com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); bestValueToMe_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); bestValueSignature_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); refundTransactionUnlockTimeSecs_ = 0L; bitField0_ = (bitField0_ & ~0x00000004); contractTransaction_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000008); clientOutput_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000010); myKey_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000020); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.leafcoin.protocols.channels.ServerState.internal_static_paymentchannels_StoredServerPaymentChannel_descriptor; } public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel getDefaultInstanceForType() { return com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.getDefaultInstance(); } public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel build() { com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel buildPartial() { com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel result = new com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.bestValueToMe_ = bestValueToMe_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.bestValueSignature_ = bestValueSignature_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.refundTransactionUnlockTimeSecs_ = refundTransactionUnlockTimeSecs_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.contractTransaction_ = contractTransaction_; if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000010; } result.clientOutput_ = clientOutput_; if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000020; } result.myKey_ = myKey_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel) { return mergeFrom((com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel other) { if (other == com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel.getDefaultInstance()) return this; if (other.hasBestValueToMe()) { setBestValueToMe(other.getBestValueToMe()); } if (other.hasBestValueSignature()) { setBestValueSignature(other.getBestValueSignature()); } if (other.hasRefundTransactionUnlockTimeSecs()) { setRefundTransactionUnlockTimeSecs(other.getRefundTransactionUnlockTimeSecs()); } if (other.hasContractTransaction()) { setContractTransaction(other.getContractTransaction()); } if (other.hasClientOutput()) { setClientOutput(other.getClientOutput()); } if (other.hasMyKey()) { setMyKey(other.getMyKey()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasBestValueToMe()) { return false; } if (!hasRefundTransactionUnlockTimeSecs()) { return false; } if (!hasContractTransaction()) { return false; } if (!hasClientOutput()) { return false; } if (!hasMyKey()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.leafcoin.protocols.channels.ServerState.StoredServerPaymentChannel) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required uint64 bestValueToMe = 1; private long bestValueToMe_ ; /** * <code>required uint64 bestValueToMe = 1;</code> */ public boolean hasBestValueToMe() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required uint64 bestValueToMe = 1;</code> */ public long getBestValueToMe() { return bestValueToMe_; } /** * <code>required uint64 bestValueToMe = 1;</code> */ public Builder setBestValueToMe(long value) { bitField0_ |= 0x00000001; bestValueToMe_ = value; onChanged(); return this; } /** * <code>required uint64 bestValueToMe = 1;</code> */ public Builder clearBestValueToMe() { bitField0_ = (bitField0_ & ~0x00000001); bestValueToMe_ = 0L; onChanged(); return this; } // optional bytes bestValueSignature = 2; private com.google.protobuf.ByteString bestValueSignature_ = com.google.protobuf.ByteString.EMPTY; /** * <code>optional bytes bestValueSignature = 2;</code> */ public boolean hasBestValueSignature() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional bytes bestValueSignature = 2;</code> */ public com.google.protobuf.ByteString getBestValueSignature() { return bestValueSignature_; } /** * <code>optional bytes bestValueSignature = 2;</code> */ public Builder setBestValueSignature(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; bestValueSignature_ = value; onChanged(); return this; } /** * <code>optional bytes bestValueSignature = 2;</code> */ public Builder clearBestValueSignature() { bitField0_ = (bitField0_ & ~0x00000002); bestValueSignature_ = getDefaultInstance().getBestValueSignature(); onChanged(); return this; } // required uint64 refundTransactionUnlockTimeSecs = 3; private long refundTransactionUnlockTimeSecs_ ; /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ public boolean hasRefundTransactionUnlockTimeSecs() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ public long getRefundTransactionUnlockTimeSecs() { return refundTransactionUnlockTimeSecs_; } /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ public Builder setRefundTransactionUnlockTimeSecs(long value) { bitField0_ |= 0x00000004; refundTransactionUnlockTimeSecs_ = value; onChanged(); return this; } /** * <code>required uint64 refundTransactionUnlockTimeSecs = 3;</code> */ public Builder clearRefundTransactionUnlockTimeSecs() { bitField0_ = (bitField0_ & ~0x00000004); refundTransactionUnlockTimeSecs_ = 0L; onChanged(); return this; } // required bytes contractTransaction = 4; private com.google.protobuf.ByteString contractTransaction_ = com.google.protobuf.ByteString.EMPTY; /** * <code>required bytes contractTransaction = 4;</code> */ public boolean hasContractTransaction() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>required bytes contractTransaction = 4;</code> */ public com.google.protobuf.ByteString getContractTransaction() { return contractTransaction_; } /** * <code>required bytes contractTransaction = 4;</code> */ public Builder setContractTransaction(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; contractTransaction_ = value; onChanged(); return this; } /** * <code>required bytes contractTransaction = 4;</code> */ public Builder clearContractTransaction() { bitField0_ = (bitField0_ & ~0x00000008); contractTransaction_ = getDefaultInstance().getContractTransaction(); onChanged(); return this; } // required bytes clientOutput = 5; private com.google.protobuf.ByteString clientOutput_ = com.google.protobuf.ByteString.EMPTY; /** * <code>required bytes clientOutput = 5;</code> */ public boolean hasClientOutput() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * <code>required bytes clientOutput = 5;</code> */ public com.google.protobuf.ByteString getClientOutput() { return clientOutput_; } /** * <code>required bytes clientOutput = 5;</code> */ public Builder setClientOutput(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000010; clientOutput_ = value; onChanged(); return this; } /** * <code>required bytes clientOutput = 5;</code> */ public Builder clearClientOutput() { bitField0_ = (bitField0_ & ~0x00000010); clientOutput_ = getDefaultInstance().getClientOutput(); onChanged(); return this; } // required bytes myKey = 6; private com.google.protobuf.ByteString myKey_ = com.google.protobuf.ByteString.EMPTY; /** * <code>required bytes myKey = 6;</code> */ public boolean hasMyKey() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * <code>required bytes myKey = 6;</code> */ public com.google.protobuf.ByteString getMyKey() { return myKey_; } /** * <code>required bytes myKey = 6;</code> */ public Builder setMyKey(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000020; myKey_ = value; onChanged(); return this; } /** * <code>required bytes myKey = 6;</code> */ public Builder clearMyKey() { bitField0_ = (bitField0_ & ~0x00000020); myKey_ = getDefaultInstance().getMyKey(); onChanged(); return this; } // @@protoc_insertion_point(builder_scope:paymentchannels.StoredServerPaymentChannel) } static { defaultInstance = new StoredServerPaymentChannel(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:paymentchannels.StoredServerPaymentChannel) } private static com.google.protobuf.Descriptors.Descriptor internal_static_paymentchannels_StoredServerPaymentChannels_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_paymentchannels_StoredServerPaymentChannels_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_paymentchannels_StoredServerPaymentChannel_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_paymentchannels_StoredServerPaymentChannel_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n storedserverpaymentchannel.proto\022\017paym" + "entchannels\"\\\n\033StoredServerPaymentChanne" + "ls\022=\n\010channels\030\001 \003(\0132+.paymentchannels.S" + "toredServerPaymentChannel\"\272\001\n\032StoredServ" + "erPaymentChannel\022\025\n\rbestValueToMe\030\001 \002(\004\022" + "\032\n\022bestValueSignature\030\002 \001(\014\022\'\n\037refundTra" + "nsactionUnlockTimeSecs\030\003 \002(\004\022\033\n\023contract" + "Transaction\030\004 \002(\014\022\024\n\014clientOutput\030\005 \002(\014\022" + "\r\n\005myKey\030\006 \002(\014B4\n%com.google.leafcoin.pro" + "tocols.channelsB\013ServerState" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_paymentchannels_StoredServerPaymentChannels_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_paymentchannels_StoredServerPaymentChannels_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_paymentchannels_StoredServerPaymentChannels_descriptor, new java.lang.String[] { "Channels", }); internal_static_paymentchannels_StoredServerPaymentChannel_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_paymentchannels_StoredServerPaymentChannel_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_paymentchannels_StoredServerPaymentChannel_descriptor, new java.lang.String[] { "BestValueToMe", "BestValueSignature", "RefundTransactionUnlockTimeSecs", "ContractTransaction", "ClientOutput", "MyKey", }); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
leafcoin/leafcoinj
core/src/main/java/com/google/leafcoin/protocols/channels/ServerState.java
Java
apache-2.0
63,519
/* * The aspiredb project * * Copyright (c) 2012 University of British Columbia * * 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 ubc.pavlab.aspiredb.server.model; import org.directwebremoting.annotations.DataTransferObject; /** * TODO Document Me. This might need to be changed to VariantType and include CNVs, SNVs etc. * * @author ?? * @version $Id: CnvType.java,v 1.6 2013/06/11 22:55:58 anton Exp $ */ @DataTransferObject(type = "enum") public enum CnvType { LOSS, GAIN, GAINLOSS, UNKNOWN }
ppavlidis/aspiredb
aspiredb/src/main/java/ubc/pavlab/aspiredb/server/model/CnvType.java
Java
apache-2.0
1,022
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.datacatalog.v1.model; /** * Request message for UnstarEntry. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Cloud Data Catalog API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDatacatalogV1UnstarEntryRequest extends com.google.api.client.json.GenericJson { @Override public GoogleCloudDatacatalogV1UnstarEntryRequest set(String fieldName, Object value) { return (GoogleCloudDatacatalogV1UnstarEntryRequest) super.set(fieldName, value); } @Override public GoogleCloudDatacatalogV1UnstarEntryRequest clone() { return (GoogleCloudDatacatalogV1UnstarEntryRequest) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-datacatalog/v1/1.31.0/com/google/api/services/datacatalog/v1/model/GoogleCloudDatacatalogV1UnstarEntryRequest.java
Java
apache-2.0
1,700
// Data Access is a Java library to store data // Copyright (C) 2018-2019 Adrián Romero Corchado. // // This file is part of Data Access // // 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 com.adr.data.mongo; import com.adr.data.DataException; import com.adr.data.varrw.Results; import java.math.BigDecimal; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeParseException; import java.util.Base64; import org.bson.Document; /** * * @author adrian */ public class DocumentResults implements Results { private final Document document; private final String realname; public DocumentResults(Document document, String columnName) { this.document = document; this.realname = columnName.endsWith(".KEY") ? columnName.substring(0, columnName.length() - 4) : columnName; } @Override public String getString() throws DataException { return document.getString(realname); } @Override public Integer getInt() throws DataException { return document.getInteger(realname); } @Override public Long getLong() throws DataException { return document.getLong(realname); } @Override public Float getFloat() throws DataException { Double d = document.getDouble(realname); return d == null ? null : d.floatValue(); } @Override public Double getDouble() throws DataException { return document.getDouble(realname); } @Override public BigDecimal getBigDecimal() throws DataException { String value = document.getString(realname); return value == null ? null : new BigDecimal(value); } @Override public Boolean getBoolean() throws DataException { return document.getBoolean(realname); } @Override public Instant getInstant() throws DataException { Long value = document.getLong(realname); return value == null ? null : Instant.ofEpochMilli(value); } @Override public LocalDateTime getLocalDateTime() throws DataException { try { String value = document.getString(realname); return value == null || value.equals("") ? null : LocalDateTime.parse(value); } catch (DateTimeParseException e) { throw new DataException(e); } } @Override public LocalDate getLocalDate() throws DataException { try { String value = document.getString(realname); return value == null || value.equals("") ? null : LocalDate.parse(value); } catch (DateTimeParseException e) { throw new DataException(e); } } @Override public LocalTime getLocalTime() throws DataException { try { String value = document.getString(realname); return value == null || value.equals("") ? null : LocalTime.parse(value); } catch (DateTimeParseException e) { throw new DataException(e); } } @Override public byte[] getBytes() throws DataException { try { String value = document.getString(realname); return value == null ? null : Base64.getDecoder().decode(value); } catch(IllegalArgumentException e) { throw new DataException(e); } } }
adrianromero/data
src/main/java/com/adr/data/mongo/DocumentResults.java
Java
apache-2.0
4,030
package configdefault import ( openshiftcontrolplanev1 "github.com/openshift/api/openshiftcontrolplane/v1" "github.com/openshift/library-go/pkg/config/configdefaults" leaderelectionconverter "github.com/openshift/library-go/pkg/config/leaderelection" ) func SetRecommendedOpenShiftControllerConfigDefaults(config *openshiftcontrolplanev1.OpenShiftControllerManagerConfig) { configdefaults.SetRecommendedHTTPServingInfoDefaults(config.ServingInfo) configdefaults.SetRecommendedKubeClientConfigDefaults(&config.KubeClientConfig) config.LeaderElection = leaderelectionconverter.LeaderElectionDefaulting(config.LeaderElection, "kube-system", "openshift-master-controllers") configdefaults.DefaultStringSlice(&config.Controllers, []string{"*"}) configdefaults.DefaultString(&config.Network.ServiceNetworkCIDR, "10.0.0.0/24") if config.ImageImport.MaxScheduledImageImportsPerMinute == 0 { config.ImageImport.MaxScheduledImageImportsPerMinute = 60 } if config.ImageImport.ScheduledImageImportMinimumIntervalSeconds == 0 { config.ImageImport.ScheduledImageImportMinimumIntervalSeconds = 15 * 60 } configdefaults.DefaultString(&config.SecurityAllocator.UIDAllocatorRange, "1000000000-1999999999/10000") configdefaults.DefaultString(&config.SecurityAllocator.MCSAllocatorRange, "s0:/2") if config.SecurityAllocator.MCSLabelsPerProject == 0 { config.SecurityAllocator.MCSLabelsPerProject = 5 } }
hferentschik/origin
pkg/cmd/openshift-controller-manager/configdefault/openshiftcontrolplane_default.go
GO
apache-2.0
1,413
/* * Copyright 2012 DigitasLBi Netherlands B.V. * * 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. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using LBi.LostDoc.Diagnostics; namespace LBi.LostDoc { public class XmlDocReader { private XDocument _doc; private Dictionary<string, XElement> _members; public void Load(XmlReader reader) { this._doc = XDocument.Load(reader, LoadOptions.SetLineInfo | LoadOptions.PreserveWhitespace); this._members = new Dictionary<string, XElement>(StringComparer.Ordinal); foreach (XElement member in _doc.Element("doc").Element("members").Elements("member")) { try { this._members.Add(member.Attribute("name").Value, member); } catch (ArgumentException) { TraceSources.GeneratorSource.TraceWarning("Duplicate member in xml documentation file: " + member.Attribute("name").Value); } } } public XElement GetDocComments(MethodInfo methodInfo) { string sig = Naming.GetAssetId(methodInfo); return this.GetMemberElement(sig); } public XElement GetDocComments(Type type) { return this.GetMemberElement(Naming.GetAssetId(type)); } public XElement GetDocComments(ConstructorInfo ctor) { string sig = Naming.GetAssetId(ctor); return this.GetMemberElement(sig); } internal XElement GetDocComments(ParameterInfo parameter) { string sig; if (parameter.Member is ConstructorInfo) sig = Naming.GetAssetId((ConstructorInfo)parameter.Member); else if (parameter.Member is PropertyInfo) sig = Naming.GetAssetId((PropertyInfo)parameter.Member); else sig = Naming.GetAssetId((MethodInfo)parameter.Member); XElement elem = this.GetMemberElement(sig); if (elem != null) return elem.XPathSelectElement(string.Format("param[@name='{0}']", parameter.Name)); return null; } internal XElement GetDocCommentsReturnParameter(ParameterInfo parameter) { string sig = Naming.GetAssetId((MethodInfo)parameter.Member); XElement elem = this.GetMemberElement(sig); if (elem != null) return elem.XPathSelectElement("returns"); return null; } internal XElement GetDocComments(FieldInfo fieldInfo) { string sig = Naming.GetAssetId(fieldInfo); return this.GetMemberElement(sig); } internal XElement GetTypeParameterSummary(Type type, Type typeParameter) { string sig = Naming.GetAssetId(type); XElement elem = this.GetMemberElement(sig); if (elem != null) return elem.XPathSelectElement(string.Format("typeparam[@name='{0}']", typeParameter.Name)); return null; } internal XElement GetTypeParameterSummary(MethodInfo methodInfo, Type typeParameter) { string sig = Naming.GetAssetId(methodInfo); XElement elem = this.GetMemberElement(sig); if (elem != null) return elem.XPathSelectElement(string.Format("typeparam[@name='{0}']", typeParameter.Name)); return null; } private XElement GetMemberElement(string signature) { XElement ret; if (!this._members.TryGetValue(signature, out ret)) ret = null; return ret; } public XElement GetDocComments(PropertyInfo propertyInfo) { string sig = Naming.GetAssetId(propertyInfo); return this.GetMemberElement(sig); } public XElement GetDocComments(EventInfo eventInfo) { string sig = Naming.GetAssetId(eventInfo); return this.GetMemberElement(sig); } } }
LBiNetherlands/LBi.LostDoc
LBi.LostDoc/XmlDocReader.cs
C#
apache-2.0
4,774
/* * Copyright 2000-2013 JetBrains s.r.o. * * 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.jetbrains.plugins.gradle.model.impl; import org.jetbrains.plugins.gradle.model.WarModel; import java.io.File; import java.util.Map; import java.util.Set; /** * @author Vladislav.Soroka * @since 11/5/13 */ public class WarModelImpl implements WarModel { private final String myWebAppDirName; private final File myWebAppDir; private File myWebXml; private Map<String, Set<String>> myWebRoots; public WarModelImpl(String webAppDirName, File webAppDir) { myWebAppDirName = webAppDirName; myWebAppDir = webAppDir; } @Override public String getWebAppDirName() { return myWebAppDirName; } @Override public File getWebAppDir() { return myWebAppDir; } public void setWebXml(File webXml) { myWebXml = webXml; } @Override public File getWebXml() { return myWebXml; } @Override public Map<String, Set<String>> getWebRoots() { return myWebRoots; } public void setWebRoots(Map<String, Set<String>> webRoots) { myWebRoots = webRoots; } }
IllusionRom-deprecated/android_platform_tools_idea
plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelImpl.java
Java
apache-2.0
1,625
--- layout: base title: 'Statistics of Polarity in UD_Portuguese-Bosque' udver: '2' --- ## Treebank Statistics: UD_Portuguese-Bosque: Features: `Polarity` This feature is universal. It occurs with 1 different values: `Neg`. 1367 tokens (1%) have a non-empty value of `Polarity`. 5 types (0%) occur at least once with a non-empty value of `Polarity`. 2 lemmas (0%) occur at least once with a non-empty value of `Polarity`. The feature is used with 1 part-of-speech tags: <tt><a href="pt_bosque-pos-ADV.html">ADV</a></tt> (1367; 1% instances). ### `ADV` 1367 <tt><a href="pt_bosque-pos-ADV.html">ADV</a></tt> tokens (16% of all `ADV` tokens) have a non-empty value of `Polarity`. `ADV` tokens may have the following values of `Polarity`: * `Neg` (1367; 100% of non-empty `Polarity`): <em>não, nada</em> * `EMPTY` (7017): <em>mais, já, também, ainda, ontem, só, depois, muito, como, agora</em>
UniversalDependencies/docs
treebanks/pt_bosque/pt_bosque-feat-Polarity.md
Markdown
apache-2.0
904
package com.mobplug.games.framework.entities; public class Vector2D { private Point2D position; private float speedX; private float speedY; public Vector2D() { position = new Point2D(0.0f, 0.0f); } public Vector2D(float posx, float posy) { position = new Point2D(posx, posy); } public Vector2D(float posx, float posy, float speedx, float speedy) { position = new Point2D(posx, posy); this.speedX = speedx; this.speedY = speedy; } public Vector2D(Point2D position) { this.position = position; } public Vector2D(Point2D position, float speedx, float speedy) { this.position = position; this.speedX = speedx; this.speedY = speedy; } public Point2D getPosition() { return position; } public float getPositionX() { return position.getX(); } public float getPositionY() { return position.getY(); } public float getSpeedX() { return this.speedX; } public float getSpeedY() { return this.speedY; } public void setPosition(Point2D position) { if (position == null) throw new IllegalArgumentException("Position cant be null"); this.position = position; } public void setPosition(float x, float y) { position.setX(x); position.setY(y); } public void setSpeed(float speedx, float speedy) { this.speedX = speedx; this.speedY = speedy; } public void setVelocity(float velocity) { //TODO implement throw new UnsupportedOperationException("Not Implemented yet"); } public double getVelocity() { return Math.sqrt(Math.pow(Math.abs(speedX), 2) + Math.pow(Math.abs(speedY), 2)); } /** * Changes the vector bearing * @param bearing in degrees */ public void setBearing(float bearing) { //TODO implement throw new UnsupportedOperationException("Not implemented yet"); } public float getBearing() { if (speedX == 0.0 && speedY == 0.0) return Float.NaN; if (speedX == 0.0) { if (speedY > 0) return 90f; else return 270f; } if (speedY == 0.0) { if (speedX > 0) return 0f; else return 180f; } if (speedX >= 0 && speedY >= 0) { return (float)Math.toDegrees(Math.atan(speedY/speedX)); } else if (speedX < 0 && speedY < 0) { return (float)(90 + Math.toDegrees(Math.atan(speedY/speedX))); } else if (speedX > 0) { return (float)(270 - Math.toDegrees(Math.atan(speedY/speedX))); } else { return (float)(90 - Math.toDegrees(Math.atan(speedY/speedX))); } } }
andreban/GamesFramework
src/com/mobplug/games/framework/entities/Vector2D.java
Java
apache-2.0
2,421
/** * Copyright 2016 StreamSets Inc. * * Licensed under 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 com.streamsets.pipeline.solr.impl; import com.streamsets.pipeline.api.StageException; import com.streamsets.pipeline.solr.api.Errors; import com.streamsets.pipeline.solr.api.SdcSolrTarget; import com.streamsets.pipeline.solr.api.SolrInstanceAPIType; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CloudSolrServer; import org.apache.solr.client.solrj.impl.HttpClientUtil; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.common.SolrInputDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class SolrTarget04 implements SdcSolrTarget { private final static Logger LOG = LoggerFactory.getLogger(SolrTarget04.class); private SolrServer solrClient; private String solrURI; private String zookeeperConnect; private String defaultCollection; private String instanceType; private boolean kerberosAuth; private static final String VERSION = "4.4.0"; public SolrTarget04( String instanceType, String solrURI, String zookeeperConnect, String defaultCollection, boolean kerberosAuth ) { this.instanceType = instanceType; this.solrURI = solrURI; this.zookeeperConnect = zookeeperConnect; this.defaultCollection = defaultCollection; this.kerberosAuth = kerberosAuth; } public void init() throws Exception { solrClient = getSolrClient(); solrClient.ping(); } private SolrServer getSolrClient() throws MalformedURLException { if(kerberosAuth) { // set kerberos before create SolrClient addSecurityProperties(); } if (SolrInstanceAPIType.SINGLE_NODE.toString().equals(this.instanceType)) { return new HttpSolrServer(this.solrURI); } else { CloudSolrServer cloudSolrClient = new CloudSolrServer(this.zookeeperConnect); cloudSolrClient.setDefaultCollection(this.defaultCollection); return cloudSolrClient; } } private void addSecurityProperties() { HttpClientUtil.setConfigurer(new SdcKrb5HttpClientConfigurer()); } public void destroy() throws IOException{ if(this.solrClient != null) { this.solrClient.shutdown(); } } public void add(Map<String, Object> fieldMap) throws StageException { SolrInputDocument document = createDocument(fieldMap); try { this.solrClient.add(document); } catch (SolrServerException | IOException ex) { throw new StageException(Errors.SOLR_04, ex.toString(), ex); } } @SuppressWarnings("unchecked") public void add(List<Map<String, Object>> fieldMaps) throws StageException { List<SolrInputDocument> documents = new ArrayList(); for(Map<String, Object> fieldMap : fieldMaps) { SolrInputDocument document = createDocument(fieldMap); documents.add(document); } try { this.solrClient.add(documents); } catch (SolrServerException | IOException | HttpSolrServer.RemoteSolrException ex) { throw new StageException(Errors.SOLR_04, ex.toString(), ex); } } @SuppressWarnings("unchecked") private SolrInputDocument createDocument(Map<String, Object> fieldMap) { SolrInputDocument document = new SolrInputDocument(); for(String key : fieldMap.keySet()) { document.addField(key, fieldMap.get(key)); } return document; } public void commit() throws StageException { try { this.solrClient.commit(); } catch (SolrServerException | IOException ex) { throw new StageException(Errors.SOLR_05, ex.toString(), ex); } } public void rollback() throws StageException { try { this.solrClient.rollback(); } catch (SolrServerException | IOException ex) { throw new StageException(Errors.SOLR_05, ex.toString(), ex); } } public String getVersion() { return this.VERSION; } }
WgStreamsets/datacollector
sdc-solr_cdh_4/src/main/java/com/streamsets/pipeline/solr/impl/SolrTarget04.java
Java
apache-2.0
4,867
/* * 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.harmony.test.func.api.javax.management.monitor.countermonitor; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.management.monitor.CounterMonitor; import org.apache.harmony.test.func.api.javax.management.monitor.gaugemonitor.sensors.Impulse; import org.apache.harmony.test.func.api.javax.management.monitor.share.NotifListener; import org.apache.harmony.test.func.api.javax.management.monitor.share.Timer; import org.apache.harmony.share.Test; /** * <b>GranularityTest</b><br> * This test verifies setGranularityPeriod method.<br> * Step by step: * <ul> * <li>1. Create the monitor and observed MBean objects. The Monitor and * Observed MBean has the same granularity period(GP), but the shifted to GP/2 * value * <li>2. After waiting for a reasonable time(~5*GP), change monitors * granularity period to GP/10 and receive the corresponding notification * </ul> */ public class GranularityTest extends Test { private static final Object sync = new Object(); private static NotifListener nListener = new NotifListener(sync); /** * @param args */ public static void main(String[] args) { System.exit(new GranularityTest().test(args)); } public int test() { /* Initialization */ MBeanServer server = MBeanServerFactory.createMBeanServer(); CounterMonitor monitor = new CounterMonitor(); Impulse counter = new Impulse(1000, 50, new Integer(3), new Integer(103)); counter.setPause(true); ObjectName counterName; try { server.registerMBean(monitor, new ObjectName( "org.apache.harmony.test.func.api.javax.management.monitor." + "countermonitor:type=CounterMonitor,id=1")); counterName = new ObjectName(Impulse.SENSOR_NAME_TEMPLATE + "1"); server.registerMBean(counter, counterName); } catch (Throwable t) { t.printStackTrace(); return error(t.toString()); } monitor.addNotificationListener(nListener, null, "handback"); nListener.setParameters("Value", counterName, "jmx.monitor.counter.threshold"); /* setup monitor */ monitor.addObservedObject(counterName); monitor.setObservedAttribute("Value"); monitor.setGranularityPeriod(1000); monitor.setInitThreshold(new Integer(100)); monitor.setModulus(new Integer(103)); monitor.setNotify(true); Thread sensorThread = new Thread(counter); sensorThread.setDaemon(true); sensorThread.start(); monitor.start(); counter.setPause(false); /* Wait 10 seconds (~10 periods) */ log.add("Test: Observed MBean counter and granularity periods " + "can't overlap: wait 5 seconds to verify"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } log.add("Test:Now check if granularity period has been changed," + " notification sends"); monitor.setGranularityPeriod(50); Timer timer = new Timer(2000, sync); timer.setDaemon(true); timer.start(); synchronized (sync) { try { sync.wait(); } catch (InterruptedException e) { e.printStackTrace(); return error(e.toString()); } } if (!(nListener.getRes() && timer.getRes())) { return fail("Either notification has been sent " + "when periods doesn't overlap " + "or hasn't been sent when periods should overlap"); } return pass(); } }
freeVM/freeVM
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/javax/management/monitor/countermonitor/GranularityTest.java
Java
apache-2.0
4,659
/* * Copyright 2008-2011 Wolfgang Keller * * 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. */ #include "gui/Texture.h" // for GL_CLAMP_TO_EDGE #include "GL/glext.h" size_t colorModePixelBytesCount(ColorMode colorMode) { switch (colorMode) { case ColorModeRGB: return 3; case ColorModeRGBA: return 4; case ColorModeInvalid: default: return 0; } } size_t textureLineBytesCount(const Texture* in_pTexture) { return (in_pTexture->width * colorModePixelBytesCount(in_pTexture->colorMode)*4+3)/4; } size_t textureBytesCount(const Texture* in_pTexture) { return in_pTexture->height * textureLineBytesCount(in_pTexture); } void allocateTextureMemory(Texture* in_pTexture) { in_pTexture->data = (unsigned char*) malloc(textureBytesCount(in_pTexture)); } void freeTextureMemory(Texture* in_pTexture) { free(in_pTexture->data); in_pTexture->data = NULL; } GLenum colorModeTextureFormat(ColorMode colorMode) { switch (colorMode) { case ColorModeRGB: return GL_RGB; case ColorModeRGBA: return GL_RGBA; case ColorModeInvalid: default: return 0; } } GLenum colorModeInternalFormat(ColorMode colorMode) { switch (colorMode) { case ColorModeRGB: return GL_RGB8; case ColorModeRGBA: return GL_RGBA8; case ColorModeInvalid: default: return 0; } } void createOpenGLTexture(Texture* in_pTexture) { glGenTextures(1, &in_pTexture->textureID); glBindTexture(GL_TEXTURE_2D, in_pTexture->textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // Linear Filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Linear Filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, // type of texture 0, // the texture level /* * Q: Why do we use GL_RGB8/GL_RGBA8 (this is what colorModeInternalFormat * returns) instead of 3 or 4? * * A: This is highly recommended on * http://www.opengl.org/wiki/Common_Mistakes#Image_precision */ colorModeInternalFormat(in_pTexture->colorMode), in_pTexture->width, // width in_pTexture->height, // height 0, // border size colorModeTextureFormat(in_pTexture->colorMode), // the format of the colors // GL_RGB, GL_RGBA etc. GL_UNSIGNED_BYTE, // the type of each component in_pTexture->data); }
dreamsxin/101_browser
src/gui/Texture.cpp
C++
apache-2.0
3,141
# Pertusaria secedens SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Lecanoromycetes/Pertusariales/Pertusariaceae/Pertusaria/Pertusaria secedens/README.md
Markdown
apache-2.0
152
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup() { ofEnableSmoothing(); //ofBackground(0); setGUI1(); setGUI2(); setGUI3(); setGUI4(); gui1->setDrawBack(false); gui2->setDrawBack(false); gui3->setDrawBack(false); gui4->setDrawBack(false); gui5->setDrawBack(false); ofBackground(50); gui1->toggleVisible(); gui2->toggleVisible(); gui3->toggleVisible(); // gui1->setDrawBack(true); // gui2->setDrawBack(true); // gui3->setDrawBack(true); // gui4->setDrawBack(true); // gui1->setDrawPadding(false); // gui2->setDrawPadding(false); // gui3->setDrawPadding(false); // ofBackground(red, green, blue); } //-------------------------------------------------------------- void testApp::update() { mg->addPoint(ofGetFrameRate()); } //-------------------------------------------------------------- void testApp::draw() { //ofBackground(red, green, blue, 255); ofBackground(50); ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_ALPHA); if(bdrawGrid) { ofSetColor(255, 255, 255, 25); drawGrid(8,8); } ofPopStyle(); ofSetRectMode(OF_RECTMODE_CENTER); } //-------------------------------------------------------------- void testApp::guiEvent(ofxUIEventArgs &e) { std::cout<<"(w,h)"<<ofGetWidth()<<","<<ofGetHeight()<<std::endl; string name = e.widget->getName(); int kind = e.widget->getKind(); cout << "got event from: " << name << endl; if(name == "RED") { ofxUISlider *slider = (ofxUISlider *) e.widget; cout << "RED " << slider->getScaledValue() << endl; red = slider->getScaledValue(); } else if(name == "GREEN") { ofxUISlider *slider = (ofxUISlider *) e.widget; cout << "GREEN " << slider->getScaledValue() << endl; green = slider->getScaledValue(); } else if(name == "BLUE") { ofxUISlider *slider = (ofxUISlider *) e.widget; cout << "BLUE " << slider->getScaledValue() << endl; blue = slider->getScaledValue(); } else if(name == "DRAW GRID") { ofxUIButton *button = (ofxUIButton *) e.widget; bdrawGrid = button->getValue(); } else if(name == "D_GRID") { ofxUIToggle *toggle = (ofxUIToggle *) e.widget; bdrawGrid = toggle->getValue(); } else if(name == "TEXT INPUT") { ofxUITextInput *textinput = (ofxUITextInput *) e.widget; if(textinput->getTriggerType() == OFX_UI_TEXTINPUT_ON_ENTER) { cout << "ON ENTER: "; // ofUnregisterKeyEvents((testApp*)this); } else if(textinput->getTriggerType() == OFX_UI_TEXTINPUT_ON_FOCUS) { cout << "ON FOCUS: "; } else if(textinput->getTriggerType() == OFX_UI_TEXTINPUT_ON_UNFOCUS) { cout << "ON BLUR: "; // ofRegisterKeyEvents(this); } string output = textinput->getTextString(); cout << output << endl; } } //-------------------------------------------------------------- void testApp::exit() { delete gui1; delete gui2; delete gui3; delete gui4; delete gui5; delete[] buffer; delete img; } //-------------------------------------------------------------- void testApp::keyPressed(int key) { if(gui2->hasKeyboardFocus()) { return; } switch (key) { case '`': { string hr; ofImage img; img.grabScreen(0,0,ofGetWidth(), ofGetHeight()); if(ofGetHours() < 12) { hr = " AM"; } else { hr = " PM"; } img.saveImage("snapshots/OFXUI "+ofToString(ofGetYear())+"-"+ofToString(ofGetMonth())+"-"+ofToString(ofGetDay())+" at "+ofToString(ofGetHours(),2)+"."+ofToString(ofGetMinutes(),2)+"."+ofToString(ofGetSeconds(),2) +hr +".png"); } break; case 'f': ofToggleFullscreen(); break; case 'h': gui1->toggleVisible(); gui2->toggleVisible(); gui3->toggleVisible(); gui4->toggleVisible(); break; case 'p': bdrawPadding = !bdrawPadding; gui1->setDrawWidgetPaddingOutline(bdrawPadding); gui2->setDrawWidgetPaddingOutline(bdrawPadding); gui3->setDrawWidgetPaddingOutline(bdrawPadding); gui4->setDrawWidgetPaddingOutline(bdrawPadding); break; case '[': gui1->setDrawWidgetPadding(false); gui2->setDrawWidgetPadding(false); gui3->setDrawWidgetPadding(false); gui4->setDrawWidgetPadding(false); break; case ']': gui1->setDrawWidgetPadding(true); gui2->setDrawWidgetPadding(true); gui3->setDrawWidgetPadding(true); gui4->setDrawWidgetPadding(true); break; case '1': gui1->toggleVisible(); break; case '2': gui2->toggleVisible(); break; case '3': gui3->toggleVisible(); break; case '4': gui4->toggleVisible(); break; case '5': //gui4->mouseDragged(555,521,0); gui4->onHitExternally(400, 500, true, 0); //gui4->onHitExternally(360, 500, 0); //gui4->onHitExternally(300, 500, 0); break; case '6': //gui4->mouseDragged(555,521,0); gui4->onHitExternally(400, 500, false, 0); //gui4->onHitExternally(360, 500, 0); //gui4->onHitExternally(300, 500, 0); break; default: break; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ) { } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void testApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } void testApp::drawGrid(float x, float y) { float w = ofGetWidth(); float h = ofGetHeight(); for(int i = 0; i < h; i+=y) { ofLine(0,i,w,i); } for(int j = 0; j < w; j+=x) { ofLine(j,0,j,h); } } void testApp::setGUI1() { red = 233; blue = 52; green = 27; float dim = 16; float xInit = OFX_UI_GLOBAL_WIDGET_SPACING; float length = 255-xInit; hideGUI = false; vector<string> names; names.push_back("RAD1"); names.push_back("RAD2"); names.push_back("RAD3"); gui1 = new ofxUICanvas(0, 0, length+xInit, ofGetHeight()); gui1->addWidgetDown(new ofxUILabel("PANEL 1: BASICS", OFX_UI_FONT_LARGE)); gui1->addWidgetDown(new ofxUILabel("Press 'h' to Hide GUIs", OFX_UI_FONT_LARGE)); gui1->addSpacer(length-xInit, 2); gui1->addWidgetDown(new ofxUILabel("H SLIDERS", OFX_UI_FONT_MEDIUM)); gui1->addSlider("RED", 0.0, 255.0, red, length-xInit, dim); gui1->addSlider("GREEN", 0.0, 255.0, green, length-xInit,dim); gui1->addSlider("BLUE", 0.0, 255.0, blue, length-xInit,dim); gui1->addSpacer(length-xInit, 2); gui1->addWidgetDown(new ofxUILabel("V SLIDERS", OFX_UI_FONT_MEDIUM)); gui1->addSlider("0", 0.0, 255.0, 150, dim, 160); gui1->setWidgetPosition(OFX_UI_WIDGET_POSITION_RIGHT); gui1->addSlider("1", 0.0, 255.0, 150, dim, 160); gui1->addSlider("2", 0.0, 255.0, 150, dim, 160); gui1->addSlider("3", 0.0, 255.0, 150, dim, 160); gui1->addSlider("4", 0.0, 255.0, 150, dim, 160); gui1->addSlider("5", 0.0, 255.0, 150, dim, 160); gui1->addSlider("6", 0.0, 255.0, 150, dim, 160); gui1->addSlider("7", 0.0, 255.0, 150, dim, 160); gui1->addSlider("8", 0.0, 255.0, 150, dim, 160); gui1->setWidgetPosition(OFX_UI_WIDGET_POSITION_DOWN); gui1->addSpacer(length-xInit, 2); gui1->addRadio("RADIO HORIZONTAL", names, OFX_UI_ORIENTATION_HORIZONTAL, dim, dim); gui1->addRadio("RADIO VERTICAL", names, OFX_UI_ORIENTATION_VERTICAL, dim, dim); gui1->addSpacer(length-xInit, 2); gui1->addWidgetDown(new ofxUILabel("BUTTONS", OFX_UI_FONT_MEDIUM)); gui1->addButton("DRAW GRID", false, dim, dim); gui1->addWidgetDown(new ofxUILabel("TOGGLES", OFX_UI_FONT_MEDIUM)); gui1->addToggle( "D_GRID", false, dim, dim); gui1->addSpacer(length-xInit, 2); gui1->addWidgetDown(new ofxUILabel("RANGE SLIDER", OFX_UI_FONT_MEDIUM)); gui1->addRangeSlider("RSLIDER", 0.0, 255.0, 50.0, 100.0, length-xInit,dim); gui1->addSpacer(length-xInit, 2); gui1->addWidgetDown(new ofxUILabel("2D PAD", OFX_UI_FONT_MEDIUM)); gui1->add2DPad("PAD", ofPoint(0,length-xInit), ofPoint(0,120), ofPoint((length-xInit)*.5,120*.5), length-xInit,120); bdrawGrid = false; bdrawPadding = false; ofAddListener(gui1->newGUIEvent,this,&testApp::guiEvent); } void testApp::setGUI2() { float dim = 16; float xInit = OFX_UI_GLOBAL_WIDGET_SPACING; float length = 255-xInit; img = new ofImage(); img->loadImage("nerd_me.png"); buffer = new float[256]; for(int i = 0; i < 256; i++) { buffer[i] = ofNoise(i/100.0); } gui2 = new ofxUICanvas(length+xInit+2, 0, length+xInit, ofGetHeight()); gui2->addWidgetDown(new ofxUILabel("PANEL 2: ADVANCED", OFX_UI_FONT_LARGE)); gui2->addSpacer(length-xInit, 2); gui2->addWidgetDown(new ofxUILabel("TEXT INPUT", OFX_UI_FONT_MEDIUM)); gui2->setWidgetFontSize(OFX_UI_FONT_LARGE); gui2->addTextInput("TEXT INPUT", "Input Text", length-xInit); gui2->addWidgetDown(new ofxUILabel("AUTO CLEAR DISABLED", OFX_UI_FONT_MEDIUM)); gui2->addTextInput("TEXT INPUT2", "Input Text", length-xInit)->setAutoClear(false); gui2->setWidgetFontSize(OFX_UI_FONT_MEDIUM); gui2->addSpacer(length-xInit, 2); gui2->addWidgetDown(new ofxUILabel("WAVEFORM DISPLAY", OFX_UI_FONT_MEDIUM)); gui2->addWidgetDown(new ofxUIWaveform(length-xInit, 64, buffer, 256, 0.0, 1.0, "WAVEFORM")); gui2->addWidgetDown(new ofxUILabel("SPECTRUM DISPLAY", OFX_UI_FONT_MEDIUM)); gui2->addWidgetDown(new ofxUISpectrum(length-xInit, 64, buffer, 256, 0.0, 1.0, "SPECTRUM")); gui2->addSpacer(length-xInit, 2); gui2->addWidgetDown(new ofxUILabel("IMAGE DISPLAY", OFX_UI_FONT_MEDIUM)); gui2->addWidgetDown(new ofxUIImage(img->width*.5, img->height*.5, img, "IMAGE CAPTION")); gui2->addSpacer(length-xInit, 2); gui2->addWidgetDown(new ofxUILabel("FPS LABEL", OFX_UI_FONT_MEDIUM)); gui2->addWidgetDown(new ofxUIFPS(OFX_UI_FONT_MEDIUM)); gui2->addSpacer(length-xInit, 2); gui2->addWidgetDown(new ofxUILabel("NUMBER DIALER", OFX_UI_FONT_MEDIUM)); gui2->addWidgetDown(new ofxUINumberDialer(-10000, 10000, 5000, 1, "NUMBER DIALER", OFX_UI_FONT_MEDIUM)); gui2->addSpacer(length-xInit, 2); gui2->addWidgetDown(new ofxUILabel("LABEL BUTTON", OFX_UI_FONT_MEDIUM)); gui2->addLabelButton("LABEL BUTTON", false, length-xInit); gui2->addLabelButton("AUTOSIZE BUTTON", false); gui2->addLabelButton("MEDIUM BUTTON", false); gui2->addSpacer(length-xInit, 2); gui2->addWidgetDown(new ofxUILabel("LABEL TOGGLES", OFX_UI_FONT_MEDIUM)); gui2->addLabelToggle("LABEL TOGGLE", false, length-xInit); gui2->addLabelToggle("AUTOSIZE TOGGLE", false); gui2->addLabelToggle("MEDIUM TOGGLE", false); ofAddListener(gui2->newGUIEvent,this,&testApp::guiEvent); } void testApp::setGUI3() { float dim = 16; float xInit = OFX_UI_GLOBAL_WIDGET_SPACING; float length = 255-xInit; gui3 = new ofxUICanvas(length*2+xInit*2+4, 0, length+xInit, ofGetHeight()); gui3->addWidgetDown(new ofxUILabel("PANEL 3: ADVANCED", OFX_UI_FONT_LARGE)); gui3->addSpacer(length-xInit, 2); gui3->addWidgetDown(new ofxUILabel("MATRIX", OFX_UI_FONT_MEDIUM)); gui3->addWidgetDown(new ofxUIToggleMatrix(dim, dim, 4, 4, "MATRIX1")); gui3->addWidgetDown(new ofxUIToggleMatrix(dim*2.0, dim*2.0, 3, 6, "MATRIX2")); gui3->addWidgetDown(new ofxUIToggleMatrix(dim*3.0, dim*3.0, 1, 4, "MATRIX3")); //gui3->addSpacer(length-xInit, 2); //gui3->addWidgetDown(new ofxUILabel("IMAGE BUTTON", OFX_UI_FONT_MEDIUM)); //gui3->addWidgetDown(new ofxUIImageButton(dim*4.0, dim*4.0, false, "GUI/images/App.png","IMAGEBTN")); //gui3->addWidgetDown(new ofxUILabel("IMAGE TOGGLE", OFX_UI_FONT_MEDIUM)); //gui3->addWidgetDown(new ofxUIImageToggle(dim*4.0, dim*4.0, false, "GUI/images/Preview.png","IMAGETGL")); gui3->addSpacer(length-xInit, 2); gui3->addWidgetDown(new ofxUILabel("ROTARY SLIDER", OFX_UI_FONT_MEDIUM)); gui3->addWidgetDown(new ofxUIRotarySlider(dim*4, 0, 100, 50, "R2SLIDER")); gui3->addSpacer(length-xInit, 2); gui3->addWidgetDown(new ofxUILabel("DROP DOWN", OFX_UI_FONT_MEDIUM)); vector<string> items; items.push_back("FIRST ITEM"); items.push_back("SECOND ITEM"); items.push_back("THIRD ITEM WHATS UP DOG"); items.push_back("FOURTH ITEM"); items.push_back("FIFTH ITEM"); items.push_back("SIXTH ITEM"); gui3->addDropDownList("DROP DOWN LIST", items, 200); ofAddListener(gui3->newGUIEvent,this,&testApp::guiEvent); } void testApp::setGUI4() { float dim = 16; float xInit = OFX_UI_GLOBAL_WIDGET_SPACING; float length = 255-xInit; //gui4 = new ofxUIScrollableCanvas(length*3+xInit*3+6, 0, length+xInit, ofGetHeight()); gui4 = new ofxUIScrollableCanvas(-length, ofGetHeight()/4, length+xInit, ofGetHeight()/3); gui4->setSnapping(false); gui4->addWidgetDown(new ofxUILabel("PANEL 4: SCROLLABLE", OFX_UI_FONT_LARGE)); gui4->setScrollableDirections(true, false); gui4->set_hitExternallyActivated(true); gui5 = new ofxUIScrollableCanvas(length, ofGetHeight()/5, dim*4.0, dim*4.0); gui5->setScrollableDirections(true, false); //gui4->setScrollAreaToScreenWidth(); // set draw padding does not work gui4->setDrawPadding(false); gui4->setDrawWidgetPadding(false); gui4->addSpacer(length-xInit, 2); //Working - good for debugging only gui4->setDrawOutline(true); gui4->setColorOutline(ofColor(255, 0, 0, 100)); vector<float> buffer; for(int i = 0; i < 256; i++) { buffer.push_back(0.0); } gui4->addWidgetDown(new ofxUILabel("IMAGE TOGGLE", OFX_UI_FONT_MEDIUM)); gui4->addWidgetDown(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/Preview.png","IMAGETGL")); gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/App.png","IMAGETGL")); gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/Preview.png","IMAGETGL")); gui4->addWidgetDown(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/Preview.png","IMAGETGL")); gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/App.png","IMAGETGL")); gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/Preview.png","IMAGETGL")); gui4->addWidget(new ofxUIImageToggle(length, ofGetHeight()/5, dim*4.0, dim*4.0, true, "GUI/play.png","IMAGETGL")); gui4->addWidgetDown(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/Preview.png","IMAGETGL")); gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/App.png","IMAGETGL")); gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/images/Preview.png","IMAGETGL")); //gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/play.png","IMAGETGL")); //gui4->addWidgetRight(new ofxUIImageToggle(dim*4.0, dim*4.0, true, "GUI/toggledown.png","IMAGETGL")); gui4->addWidgetDown(new ofxUILabel("MOVING GRAPH", OFX_UI_FONT_MEDIUM)); mg = (ofxUIMovingGraph *) gui4->addWidgetDown(new ofxUIMovingGraph(length-xInit, 120, buffer, 256, 0, 400, "MOVING GRAPH")); ofAddListener(gui4->newGUIEvent,this,&testApp::guiEvent); }
decebel/dataAtom_alpha
examples/example_menu_UI/testApp.cpp
C++
apache-2.0
16,228
package io.gatekeeper.node.service; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.gatekeeper.configuration.Configuration; import io.gatekeeper.configuration.data.ReplicationConfiguration; import io.gatekeeper.logging.Loggers; import io.gatekeeper.node.service.replication.common.Node; import io.gatekeeper.node.service.replication.common.ReplicationInformation; import java.io.IOException; import java.util.List; import java.util.concurrent.*; import java.util.logging.Logger; public abstract class ReplicationService<ReplicationConfigurationType extends ReplicationConfiguration> implements Service { protected final ReplicationConfigurationType replicationConfiguration; protected final Configuration configuration; protected final Logger logger; protected final ThreadPoolExecutor executor; public ReplicationService(Configuration configuration) { assert null != configuration; this.configuration = configuration; this.replicationConfiguration = (ReplicationConfigurationType) configuration.replication; this.logger = Loggers.getReplicationLogger(); this.executor = (ThreadPoolExecutor) Executors.newCachedThreadPool( (new ThreadFactoryBuilder()) .setNameFormat("Replication Service %d") .build() ); this.executor.prestartCoreThread(); this.executor.prestartAllCoreThreads(); } public abstract CompletableFuture<Void> start(); public abstract CompletableFuture<Integer> countNodes(); public abstract CompletableFuture<List<Node>> fetchNodes(); public void lock() throws InterruptedException { this.lock(".global"); } public abstract void lock(String name) throws InterruptedException; public abstract void unlock(String name) throws InterruptedException; public void unlock() throws InterruptedException { this.unlock(".global"); } public abstract CompletableFuture<ReplicationInformation> getInformation(); @Override public void close() throws IOException { this.logger.info(String.format("Shutting down %d replication threads", this.executor.getActiveCount())); this.executor.shutdown(); try { this.executor.awaitTermination(10, TimeUnit.SECONDS); } catch (InterruptedException e) { this.logger.warning(String.format( "Killing %d replication threads that did not shut down in time", this.executor.getActiveCount() )); } this.logger.info("Replication threads halted"); } }
JackPrice/gatekeeper
src/main/java/io/gatekeeper/node/service/ReplicationService.java
Java
apache-2.0
2,642
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ // -*- C++ -*- /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1.1.1 $ | | Description: | This file defines the SoGLCoordinateElement class. | | Author(s) : Paul S. Strauss | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #ifndef _SO_GL_COORDINATE_ELEMENT #define _SO_GL_COORDINATE_ELEMENT #include <Inventor/elements/SoCoordinateElement.h> ////////////////////////////////////////////////////////////////////////////// // // Class: SoGLCoordinateElement // // Element that stores the current coordinates. Adds methods to // send the surface coordinate to GL on demand. The coordinates are // sent in the appropriate form, depending on whether they are stored // as 3-D or 4-D values. // // Note that this class relies on SoCoordinateElement to store the // coordinates in the instance. // ////////////////////////////////////////////////////////////////////////////// SoEXTENDER class INVENTOR_API SoGLCoordinateElement : public SoCoordinateElement { SO_ELEMENT_HEADER(SoGLCoordinateElement); public: // Sends indexed coordinate to GL void send(int index) const; SoINTERNAL public: // Initializes the SoGLCoordinateElement class static void initClass(); protected: virtual ~SoGLCoordinateElement(); }; #endif /* _SO_GL_COORDINATE_ELEMENT */
OpenXIP/xip-libraries
src/extern/inventor/lib/database/include/Inventor/elements/SoGLCoordinateElement.h
C
apache-2.0
3,091
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.index.mapper.internal; import com.google.common.base.Objects; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.StoredField; import org.apache.lucene.index.FieldInfo.IndexOptions; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.compress.CompressedStreamInput; import org.elasticsearch.common.compress.Compressor; import org.elasticsearch.common.compress.CompressorFactory; import org.elasticsearch.common.io.stream.CachedStreamOutput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.document.BaseFieldVisitor; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.mapper.*; import org.elasticsearch.index.mapper.core.AbstractFieldMapper; import java.io.IOException; import java.util.List; import java.util.Map; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringValue; import static org.elasticsearch.index.mapper.MapperBuilders.source; /** * */ public class SourceFieldMapper extends AbstractFieldMapper<byte[]> implements InternalMapper, RootMapper { public static final String NAME = "_source"; public static final String CONTENT_TYPE = "_source"; public static class Defaults extends AbstractFieldMapper.Defaults { public static final String NAME = SourceFieldMapper.NAME; public static final boolean ENABLED = true; public static final long COMPRESS_THRESHOLD = -1; public static final String FORMAT = null; // default format is to use the one provided public static final FieldType SOURCE_FIELD_TYPE = new FieldType(AbstractFieldMapper.Defaults.FIELD_TYPE); static { SOURCE_FIELD_TYPE.setIndexed(false); SOURCE_FIELD_TYPE.setStored(true); SOURCE_FIELD_TYPE.setOmitNorms(true); SOURCE_FIELD_TYPE.setIndexOptions(IndexOptions.DOCS_ONLY); SOURCE_FIELD_TYPE.freeze(); } public static final String[] INCLUDES = Strings.EMPTY_ARRAY; public static final String[] EXCLUDES = Strings.EMPTY_ARRAY; } public static class Builder extends Mapper.Builder<Builder, SourceFieldMapper> { private boolean enabled = Defaults.ENABLED; private long compressThreshold = Defaults.COMPRESS_THRESHOLD; private Boolean compress = null; private String format = Defaults.FORMAT; private String[] includes = Defaults.INCLUDES; private String[] excludes = Defaults.EXCLUDES; public Builder() { super(Defaults.NAME); } public Builder enabled(boolean enabled) { this.enabled = enabled; return this; } public Builder compress(boolean compress) { this.compress = compress; return this; } public Builder compressThreshold(long compressThreshold) { this.compressThreshold = compressThreshold; return this; } public Builder format(String format) { this.format = format; return this; } public Builder includes(String[] includes) { this.includes = includes; return this; } public Builder excludes(String[] excludes) { this.excludes = excludes; return this; } @Override public SourceFieldMapper build(BuilderContext context) { return new SourceFieldMapper(name, enabled, format, compress, compressThreshold, includes, excludes); } } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { SourceFieldMapper.Builder builder = source(); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { builder.enabled(nodeBooleanValue(fieldNode)); } else if (fieldName.equals("compress") && fieldNode != null) { builder.compress(nodeBooleanValue(fieldNode)); } else if (fieldName.equals("compress_threshold") && fieldNode != null) { if (fieldNode instanceof Number) { builder.compressThreshold(((Number) fieldNode).longValue()); builder.compress(true); } else { builder.compressThreshold(ByteSizeValue.parseBytesSizeValue(fieldNode.toString()).bytes()); builder.compress(true); } } else if ("format".equals(fieldName)) { builder.format(nodeStringValue(fieldNode, null)); } else if (fieldName.equals("includes")) { List<Object> values = (List<Object>) fieldNode; String[] includes = new String[values.size()]; for (int i = 0; i < includes.length; i++) { includes[i] = values.get(i).toString(); } builder.includes(includes); } else if (fieldName.equals("excludes")) { List<Object> values = (List<Object>) fieldNode; String[] excludes = new String[values.size()]; for (int i = 0; i < excludes.length; i++) { excludes[i] = values.get(i).toString(); } builder.excludes(excludes); } } return builder; } } private final boolean enabled; private Boolean compress; private long compressThreshold; private String[] includes; private String[] excludes; private String format; private XContentType formatContentType; public SourceFieldMapper() { this(Defaults.NAME, Defaults.ENABLED, Defaults.FORMAT, null, -1, Defaults.INCLUDES, Defaults.EXCLUDES); } protected SourceFieldMapper(String name, boolean enabled, String format, Boolean compress, long compressThreshold, String[] includes, String[] excludes) { super(new Names(name, name, name, name), Defaults.BOOST, new FieldType(Defaults.SOURCE_FIELD_TYPE), Lucene.KEYWORD_ANALYZER, Lucene.KEYWORD_ANALYZER); this.enabled = enabled; this.compress = compress; this.compressThreshold = compressThreshold; this.includes = includes; this.excludes = excludes; this.format = format; this.formatContentType = format == null ? null : XContentType.fromRestContentType(format); } public boolean enabled() { return this.enabled; } public BaseFieldVisitor fieldSelector() { return new SourceFieldVisitor(); } @Override public void preParse(ParseContext context) throws IOException { super.parse(context); } @Override public void postParse(ParseContext context) throws IOException { } @Override public void parse(ParseContext context) throws IOException { // nothing to do here, we will call it in pre parse } @Override public void validate(ParseContext context) throws MapperParsingException { } @Override public boolean includeInObject() { return false; } @Override protected Field parseCreateField(ParseContext context) throws IOException { if (!enabled) { return null; } if (!stored()) { return null; } if (context.flyweight()) { return null; } BytesReference source = context.source(); boolean filtered = includes.length > 0 || excludes.length > 0; if (filtered) { // we don't update the context source if we filter, we want to keep it as is... Tuple<XContentType, Map<String, Object>> mapTuple = XContentHelper.convertToMap(source, true); Map<String, Object> filteredSource = XContentMapValues.filter(mapTuple.v2(), includes, excludes); CachedStreamOutput.Entry cachedEntry = CachedStreamOutput.popEntry(); StreamOutput streamOutput; if (compress != null && compress && (compressThreshold == -1 || source.length() > compressThreshold)) { streamOutput = cachedEntry.bytes(CompressorFactory.defaultCompressor()); } else { streamOutput = cachedEntry.bytes(); } XContentType contentType = formatContentType; if (contentType == null) { contentType = mapTuple.v1(); } XContentBuilder builder = XContentFactory.contentBuilder(contentType, streamOutput).map(filteredSource); builder.close(); source = cachedEntry.bytes().bytes().copyBytesArray(); CachedStreamOutput.pushEntry(cachedEntry); } else if (compress != null && compress && !CompressorFactory.isCompressed(source)) { if (compressThreshold == -1 || source.length() > compressThreshold) { CachedStreamOutput.Entry cachedEntry = CachedStreamOutput.popEntry(); try { XContentType contentType = XContentFactory.xContentType(source); if (formatContentType != null && formatContentType != contentType) { XContentBuilder builder = XContentFactory.contentBuilder(formatContentType, cachedEntry.bytes(CompressorFactory.defaultCompressor())); builder.copyCurrentStructure(XContentFactory.xContent(contentType).createParser(source)); builder.close(); } else { StreamOutput streamOutput = cachedEntry.bytes(CompressorFactory.defaultCompressor()); source.writeTo(streamOutput); streamOutput.close(); } // we copy over the byte array, since we need to push back the cached entry // TODO, we we had a handle into when we are done with parsing, then we push back then and not copy over bytes source = cachedEntry.bytes().bytes().copyBytesArray(); // update the data in the context, so it can be compressed and stored compressed outside... context.source(source); } finally { CachedStreamOutput.pushEntry(cachedEntry); } } } else if (formatContentType != null) { // see if we need to convert the content type Compressor compressor = CompressorFactory.compressor(source); if (compressor != null) { CompressedStreamInput compressedStreamInput = compressor.streamInput(source.streamInput()); XContentType contentType = XContentFactory.xContentType(compressedStreamInput); compressedStreamInput.resetToBufferStart(); if (contentType != formatContentType) { // we need to reread and store back, compressed.... CachedStreamOutput.Entry cachedEntry = CachedStreamOutput.popEntry(); try { StreamOutput streamOutput = cachedEntry.bytes(CompressorFactory.defaultCompressor()); XContentBuilder builder = XContentFactory.contentBuilder(formatContentType, streamOutput); builder.copyCurrentStructure(XContentFactory.xContent(contentType).createParser(compressedStreamInput)); builder.close(); source = cachedEntry.bytes().bytes().copyBytesArray(); // update the data in the context, so we store it in the translog in this format context.source(source); } finally { CachedStreamOutput.pushEntry(cachedEntry); } } else { compressedStreamInput.close(); } } else { XContentType contentType = XContentFactory.xContentType(source); if (contentType != formatContentType) { // we need to reread and store back // we need to reread and store back, compressed.... CachedStreamOutput.Entry cachedEntry = CachedStreamOutput.popEntry(); try { XContentBuilder builder = XContentFactory.contentBuilder(formatContentType, cachedEntry.bytes()); builder.copyCurrentStructure(XContentFactory.xContent(contentType).createParser(source)); builder.close(); source = cachedEntry.bytes().bytes().copyBytesArray(); // update the data in the context, so we store it in the translog in this format context.source(source); } finally { CachedStreamOutput.pushEntry(cachedEntry); } } } } assert source.hasArray(); return new StoredField(names().indexName(), source.array(), source.arrayOffset(), source.length()); } public byte[] value(Document document) { Field field = (Field) document.getField(names.indexName()); return field == null ? null : value(field); } public byte[] nativeValue(Field field) { return field.binaryValue().bytes; } @Override public byte[] value(Field field) { byte[] value = field.binaryValue().bytes; if (value == null) { return value; } try { return CompressorFactory.uncompressIfNeeded(new BytesArray(value)).toBytes(); } catch (IOException e) { throw new ElasticSearchParseException("failed to decompress source", e); } } @Override public byte[] valueFromString(String value) { return null; } @Override public String valueAsString(Field field) { throw new UnsupportedOperationException(); } @Override public String indexedValue(String value) { return value; } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { // all are defaults, no need to write it at all if (enabled == Defaults.ENABLED && compress == null && compressThreshold == -1 && includes.length == 0 && excludes.length == 0) { return builder; } builder.startObject(contentType()); if (enabled != Defaults.ENABLED) { builder.field("enabled", enabled); } if (!Objects.equal(format, Defaults.FORMAT)) { builder.field("format", format); } if (compress != null) { builder.field("compress", compress); } if (compressThreshold != -1) { builder.field("compress_threshold", new ByteSizeValue(compressThreshold).toString()); } if (includes.length > 0) { builder.field("includes", includes); } if (excludes.length > 0) { builder.field("excludes", excludes); } builder.endObject(); return builder; } @Override public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException { SourceFieldMapper sourceMergeWith = (SourceFieldMapper) mergeWith; if (!mergeContext.mergeFlags().simulate()) { if (sourceMergeWith.compress != null) { this.compress = sourceMergeWith.compress; } if (sourceMergeWith.compressThreshold != -1) { this.compressThreshold = sourceMergeWith.compressThreshold; } } } }
speedplane/elasticsearch
src/main/java/org/elasticsearch/index/mapper/internal/SourceFieldMapper.java
Java
apache-2.0
17,772
/* * Copyright 2014 Space Dynamics Laboratory - Utah State University Research 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. */ 'use strict'; app.directive('filterquery',['business', '$q', function (Business, $q) { var returnFilterQuerySource = function(element, attrs){ if (attrs.type === 'user') { return 'views/services/user.html'; } else if (attrs.type === 'component') { return 'views/services/component.html'; } else if (attrs.type === 'article') { return 'views/services/article.html'; } else { return 'views/services/default.html'; } } return { templateUrl: returnFilterQuerySource, restrict: 'E', scope:{ url: '@', max: '@', sortBy: '@', sortOrder: '@', showExport: '@', allowAllOption: '@', data: '=', setFeatures: '=', control: '=', all: '@', callback: '=?' /*This callback is actually an array that contains the pointer function, and then the array of arguments expecting the query object to be the last parameter*/ }, link: function postLink(scope, element, attrs) { scope.defaultMax = 50; scope.setFeatures = scope.setFeatures || {'dates': true, 'max': true, 'activeState': true, 'approvalState': false, 'componentType': false, 'clear': true, 'pages': true}; scope.internalControl = scope.control || {}; scope.defaultMax = scope.max? parseInt(scope.max): 50; scope.today = new Date(); scope.query = {}; scope.query.filterObj = angular.copy(utils.queryFilter); if (scope.callback && scope.callback[1]) { scope.callback[1].push(scope.query.filterObj); } scope.query.url = scope.url || ''; scope.query.filterObj.offset = 0; scope.query.filterObj.max = scope.defaultMax; scope.pagination = {}; scope.pagination.currentPage = 1; scope.pagination.itemsPerPage = scope.defaultMax; scope.pagination.maxSize = 5; scope.showPagination = true; scope.maxResults; scope.maxPerPage; scope.query.filterObj.sortField = scope.sortBy || 'eventDts'; scope.query.filterObj.sortOrder = scope.sortOrder || 'DESC'; scope.oldField = scope.sortBy || 'eventDts'; scope.popover = { "title": "Additional filters" }; attrs.$observe('url', function(value){ if (value) { scope.url = value; scope.query.url = scope.url || ''; } }); Business.lookupservice.getLookupCodes('TrackEventCode').then(function(result){ scope.eventCodes = result? result: []; }, function(){ scope.eventCodes = []; }) Business.lookupservice.getLookupCodes('UserTypeCode').then(function(result){ scope.userCodes = result? result: []; }, function(){ scope.userCodes = []; }) scope.sendRequest = function(){ var deferred = $q.defer(); var query = angular.copy(scope.query); query.filterObj.approvalState = scope.internalControl.approvalState; if (query.filterObj.approvalState === 'ALL') { query.filterObj.approvalState = null; } query.filterObj.componentType = scope.internalControl.componentType; if (query.filterObj.componentType === 'ALL') { query.filterObj.componentType = null; } if (query.filterObj.end) { var d = new Date(query.filterObj.end); d.setHours(d.getHours()+24); query.filterObj.end = d.toISOString(); } if (query.filterObj.start) { query.filterObj.start = new Date(query.filterObj.start).toISOString(); } if (attrs.type === 'user' || attrs.type === 'component' || attrs.type === 'article') { // for tracking types var func = (scope.callback && scope.callback.length)? scope.callback[0].apply(null, scope.callback[1]) : Business.trackingservice.get(query); func.then(function(result){ scope.backupResult = result; scope.data = result? result.result: []; scope.pagination.totalItems = result.count; deferred.resolve(result); }, function(){ deferred.resolve(); scope.data = []; }); }else { var func = (scope.callback && scope.callback.length)? scope.callback[0].apply(null, scope.callback[1]) : Business.get(query); func.then(function(result){ scope.backupResult = result; scope.data = result? result: []; scope.pagination.totalItems = result.totalNumber; deferred.resolve(result); }, function(){ scope.data = []; deferred.resolve(); }); } if (scope.internalControl && scope.internalControl.onRefresh){ scope.internalControl.onRefresh(); } return deferred.promise; } scope.sendRequest(); scope.pageChanged = function(){ scope.query.filterObj.offset = (scope.pagination.currentPage - 1) * scope.pagination.itemsPerPage; scope.sendRequest(); }; scope.switchOrder = function(sortOrder) { if (sortOrder === 'DESC') { return 'ASC'; } else { return 'DESC'; } }; scope.updateFilter = function() { if (scope.pagination.applyChanges){ scope.pagination.applyChanges = false; scope.pagination.applyChangesText='Filter Options'; scope.sendRequest(); } else { scope.pagination.applyChangesText='Apply'; scope.pagination.applyChanges=true; } }; scope.clearSort = function() { if (scope.internalControl.setPredicate) { scope.query.filterObj.sortField = scope.sortBy || 'eventDts'; scope.internalControl.setPredicate(scope.query.filterObj.sortField); } else { scope.query.filterObj.sortField = scope.sortBy || 'eventDts'; } scope.query.filterObj.sortOrder = scope.sortOrder || 'ASC'; scope.sendRequest(); } scope.checkMax = function(){ if (scope.maxResults) { scope.query.filterObj.offset = 0; scope.query.filterObj.max = scope.maxResults; scope.showPagination = false; } else { scope.showPagination = true; } } scope.generateDownloadLink = function(){ var url = 'api/v1/resource/'; if (attrs.type === 'user'){ url += 'usertracking/export?'; } else if (attrs.type === 'component'){ url += 'componenttracking/export?'; } else if (attrs.type === 'article'){ url += 'articletracking/export?'; } var query = angular.copy(scope.query.filterObj); if (scope.maxResults) { query.offset = 0; query.max = scope.maxResults; } else { query.offset = 0; query.max = 0; } url += query.toQuery(); return url; } scope.toTop = function(){ jQuery('html,body').animate({scrollTop:0},0); } scope.setPageMax = function(maxPerPage){ if (maxPerPage){ scope.query.filterObj.max = maxPerPage; scope.pagination.itemsPerPage = maxPerPage; } else { scope.query.filterObj.max = 20; scope.pagination.itemsPerPage = 20; } } scope.changeSortOrder = function(field){ if (scope.oldField && scope.oldField === field) { scope.query.filterObj.sortField = field; scope.query.filterObj.sortOrder = scope.switchOrder(scope.query.filterObj.sortOrder); } else { scope.query.filterObj.sortField = field; scope.query.filterObj.sortOrder = scope.sortOrder || 'ASC'; } scope.oldField = field; scope.sendRequest(); } scope.getEventType = function(code){ if (scope.eventCodes && scope.eventCodes.length){ var found = _.find(scope.eventCodes, {'code': code}); if (found) { return found.description; } else { return code; } } return code; } scope.getUserType = function(code){ if (scope.userCodes && scope.userCodes.length){ var found = _.find(scope.userCodes, {'code': code}); if (found) { return found.description; } else { return code; } } return code; } scope.getDate = function(d) { return utils.getDate(d); } scope.internalControl.refresh = function(){ return scope.sendRequest(); } scope.internalControl.changeSortOrder = function(field){ scope.changeSortOrder(field); } scope.control = scope.internalControl; } }; }]);
Jedwondle/openstorefront
client/openstorefront/app/scripts/directives/services/filterquery.js
JavaScript
apache-2.0
9,465