repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
antonmedv/year
|
packages/1994/04/06/index.js
|
<gh_stars>1-10
module.exports = new Date(1994, 3, 6)
|
whble/trunk
|
target/linux/adm5120/files/drivers/usb/host/adm5120-pm.c
|
/*
* ADM5120 HCD (Host Controller Driver) for USB
*
* Copyright (C) 2007-2008 <NAME> <<EMAIL>>
*
* This file was derived from fragments of the OHCI driver.
* (C) Copyright 1999 <NAME> <<EMAIL>>
* (C) Copyright 2000-2004 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
*/
#define OHCI_SCHED_ENABLES \
(OHCI_CTRL_CLE|OHCI_CTRL_BLE|OHCI_CTRL_PLE|OHCI_CTRL_IE)
#ifdef CONFIG_PM
static int admhc_restart(struct admhcd *ahcd);
static int admhc_rh_suspend(struct admhcd *ahcd, int autostop)
__releases(ahcd->lock)
__acquires(ahcd->lock)
{
int status = 0;
ahcd->hc_control = admhc_readl(ahcd, &ahcd->regs->control);
switch (ahcd->hc_control & OHCI_CTRL_HCFS) {
case OHCI_USB_RESUME:
admhc_dbg(ahcd, "resume/suspend?\n");
ahcd->hc_control &= ~OHCI_CTRL_HCFS;
ahcd->hc_control |= OHCI_USB_RESET;
admhc_writel(ahcd, ahcd->hc_control, &ahcd->ahcd->regs->control);
(void) admhc_readl(ahcd, &ahcd->regs->control);
/* FALL THROUGH */
case OHCI_USB_RESET:
status = -EBUSY;
admhc_dbg(ahcd, "needs reinit!\n");
goto done;
case OHCI_USB_SUSPEND:
if (!ahcd->autostop) {
admhc_dbg(ahcd, "already suspended\n");
goto done;
}
}
admhc_dbg(ahcd, "%s root hub\n",
autostop ? "auto-stop" : "suspend");
/* First stop any processing */
if (!autostop && (ahcd->hc_control & OHCI_SCHED_ENABLES)) {
ahcd->hc_control &= ~OHCI_SCHED_ENABLES;
admhc_writel(ahcd, ahcd->hc_control, &ahcd->ahcd->regs->control);
ahcd->hc_control = admhc_readl(ahcd, &ahcd->regs->control);
admhc_writel(ahcd, OHCI_INTR_SF, &ahcd->regs->intrstatus);
/* sched disables take effect on the next frame,
* then the last WDH could take 6+ msec
*/
admhc_dbg(ahcd, "stopping schedules ...\n");
ahcd->autostop = 0;
spin_unlock_irq (&ahcd->lock);
msleep (8);
spin_lock_irq(&ahcd->lock);
}
dl_done_list (ahcd);
finish_unlinks (ahcd, admhc_frame_no(ahcd));
/* maybe resume can wake root hub */
if (device_may_wakeup(&admhcd_to_hcd(ahcd)->self.root_hub->dev) ||
autostop)
ahcd->hc_control |= OHCI_CTRL_RWE;
else {
admhc_writel(ahcd, OHCI_INTR_RHSC, &ahcd->regs->intrdisable);
ahcd->hc_control &= ~OHCI_CTRL_RWE;
}
/* Suspend hub ... this is the "global (to this bus) suspend" mode,
* which doesn't imply ports will first be individually suspended.
*/
ahcd->hc_control &= ~OHCI_CTRL_HCFS;
ahcd->hc_control |= OHCI_USB_SUSPEND;
admhc_writel(ahcd, ahcd->hc_control, &ahcd->ahcd->regs->control);
(void) admhc_readl(ahcd, &ahcd->regs->control);
/* no resumes until devices finish suspending */
if (!autostop) {
ahcd->next_statechange = jiffies + msecs_to_jiffies (5);
ahcd->autostop = 0;
}
done:
return status;
}
static inline struct ed *find_head(struct ed *ed)
{
/* for bulk and control lists */
while (ed->ed_prev)
ed = ed->ed_prev;
return ed;
}
/* caller has locked the root hub */
static int admhc_rh_resume(struct admhcd *ahcd)
__releases(ahcd->lock)
__acquires(ahcd->lock)
{
struct usb_hcd *hcd = admhcd_to_hcd (ahcd);
u32 temp, enables;
int status = -EINPROGRESS;
int autostopped = ahcd->autostop;
ahcd->autostop = 0;
ahcd->hc_control = admhc_readl(ahcd, &ahcd->regs->control);
if (ahcd->hc_control & (OHCI_CTRL_IR | OHCI_SCHED_ENABLES)) {
/* this can happen after resuming a swsusp snapshot */
if (hcd->state == HC_STATE_RESUMING) {
admhc_dbg(ahcd, "BIOS/SMM active, control %03x\n",
ahcd->hc_control);
status = -EBUSY;
/* this happens when pmcore resumes HC then root */
} else {
admhc_dbg(ahcd, "duplicate resume\n");
status = 0;
}
} else switch (ahcd->hc_control & OHCI_CTRL_HCFS) {
case OHCI_USB_SUSPEND:
ahcd->hc_control &= ~(OHCI_CTRL_HCFS|OHCI_SCHED_ENABLES);
ahcd->hc_control |= OHCI_USB_RESUME;
admhc_writel(ahcd, ahcd->hc_control, &ahcd->ahcd->regs->control);
(void) admhc_readl(ahcd, &ahcd->regs->control);
admhc_dbg(ahcd, "%s root hub\n",
autostopped ? "auto-start" : "resume");
break;
case OHCI_USB_RESUME:
/* HCFS changes sometime after INTR_RD */
admhc_dbg(ahcd, "%swakeup root hub\n",
autostopped ? "auto-" : "");
break;
case OHCI_USB_OPER:
/* this can happen after resuming a swsusp snapshot */
admhc_dbg(ahcd, "snapshot resume? reinit\n");
status = -EBUSY;
break;
default: /* RESET, we lost power */
admhc_dbg(ahcd, "lost power\n");
status = -EBUSY;
}
if (status == -EBUSY) {
if (!autostopped) {
spin_unlock_irq (&ahcd->lock);
(void) ahcd_init (ahcd);
status = admhc_restart (ahcd);
spin_lock_irq(&ahcd->lock);
}
return status;
}
if (status != -EINPROGRESS)
return status;
if (autostopped)
goto skip_resume;
spin_unlock_irq (&ahcd->lock);
/* Some controllers (lucent erratum) need extra-long delays */
msleep (20 /* usb 172.16.58.3 */ + 12 /* 32 msec counter */ + 1);
temp = admhc_readl(ahcd, &ahcd->regs->control);
temp &= OHCI_CTRL_HCFS;
if (temp != OHCI_USB_RESUME) {
admhc_err (ahcd, "controller won't resume\n");
spin_lock_irq(&ahcd->lock);
return -EBUSY;
}
/* disable old schedule state, reinit from scratch */
admhc_writel(ahcd, 0, &ahcd->regs->ed_controlhead);
admhc_writel(ahcd, 0, &ahcd->regs->ed_controlcurrent);
admhc_writel(ahcd, 0, &ahcd->regs->ed_bulkhead);
admhc_writel(ahcd, 0, &ahcd->regs->ed_bulkcurrent);
admhc_writel(ahcd, 0, &ahcd->regs->ed_periodcurrent);
admhc_writel(ahcd, (u32) ahcd->hcca_dma, &ahcd->ahcd->regs->hcca);
/* Sometimes PCI D3 suspend trashes frame timings ... */
periodic_reinit(ahcd);
/* the following code is executed with ahcd->lock held and
* irqs disabled if and only if autostopped is true
*/
skip_resume:
/* interrupts might have been disabled */
admhc_writel(ahcd, OHCI_INTR_INIT, &ahcd->regs->int_enable);
if (ahcd->ed_rm_list)
admhc_writel(ahcd, OHCI_INTR_SF, &ahcd->regs->int_enable);
/* Then re-enable operations */
admhc_writel(ahcd, OHCI_USB_OPER, &ahcd->regs->control);
(void) admhc_readl(ahcd, &ahcd->regs->control);
if (!autostopped)
msleep (3);
temp = ahcd->hc_control;
temp &= OHCI_CTRL_RWC;
temp |= OHCI_CONTROL_INIT | OHCI_USB_OPER;
ahcd->hc_control = temp;
admhc_writel(ahcd, temp, &ahcd->regs->control);
(void) admhc_readl(ahcd, &ahcd->regs->control);
/* TRSMRCY */
if (!autostopped) {
msleep (10);
spin_lock_irq(&ahcd->lock);
}
/* now ahcd->lock is always held and irqs are always disabled */
/* keep it alive for more than ~5x suspend + resume costs */
ahcd->next_statechange = jiffies + STATECHANGE_DELAY;
/* maybe turn schedules back on */
enables = 0;
temp = 0;
if (!ahcd->ed_rm_list) {
if (ahcd->ed_controltail) {
admhc_writel(ahcd,
find_head (ahcd->ed_controltail)->dma,
&ahcd->regs->ed_controlhead);
enables |= OHCI_CTRL_CLE;
temp |= OHCI_CLF;
}
if (ahcd->ed_bulktail) {
admhc_writel(ahcd, find_head (ahcd->ed_bulktail)->dma,
&ahcd->regs->ed_bulkhead);
enables |= OHCI_CTRL_BLE;
temp |= OHCI_BLF;
}
}
if (hcd->self.bandwidth_isoc_reqs || hcd->self.bandwidth_int_reqs)
enables |= OHCI_CTRL_PLE|OHCI_CTRL_IE;
if (enables) {
admhc_dbg(ahcd, "restarting schedules ... %08x\n", enables);
ahcd->hc_control |= enables;
admhc_writel(ahcd, ahcd->hc_control, &ahcd->ahcd->regs->control);
if (temp)
admhc_writel(ahcd, temp, &ahcd->regs->cmdstatus);
(void) admhc_readl(ahcd, &ahcd->regs->control);
}
return 0;
}
static int admhc_bus_suspend(struct usb_hcd *hcd)
{
struct admhcd *ahcd = hcd_to_admhcd(hcd);
int rc;
spin_lock_irq(&ahcd->lock);
if (unlikely(!HCD_HW_ACCESSIBLE(hcd)))
rc = -ESHUTDOWN;
else
rc = admhc_rh_suspend(ahcd, 0);
spin_unlock_irq(&ahcd->lock);
return rc;
}
static int admhc_bus_resume(struct usb_hcd *hcd)
{
struct admhcd *ahcd = hcd_to_admhcd(hcd);
int rc;
if (time_before(jiffies, ahcd->next_statechange))
msleep(5);
spin_lock_irq(&ahcd->lock);
if (unlikely(!HCD_HW_ACCESSIBLE(hcd)))
rc = -ESHUTDOWN;
else
rc = admhc_rh_resume(ahcd);
spin_unlock_irq(&ahcd->lock);
/* poll until we know a device is connected or we autostop */
if (rc == 0)
usb_hcd_poll_rh_status(hcd);
return rc;
}
/* Carry out polling-, autostop-, and autoresume-related state changes */
static int admhc_root_hub_state_changes(struct admhcd *ahcd, int changed,
int any_connected)
{
int poll_rh = 1;
switch (ahcd->hc_control & OHCI_CTRL_HCFS) {
case OHCI_USB_OPER:
/* keep on polling until we know a device is connected
* and RHSC is enabled */
if (!ahcd->autostop) {
if (any_connected ||
!device_may_wakeup(&admhcd_to_hcd(ahcd)
->self.root_hub->dev)) {
if (admhc_readl(ahcd, &ahcd->regs->int_enable) &
OHCI_INTR_RHSC)
poll_rh = 0;
} else {
ahcd->autostop = 1;
ahcd->next_statechange = jiffies + HZ;
}
/* if no devices have been attached for one second, autostop */
} else {
if (changed || any_connected) {
ahcd->autostop = 0;
ahcd->next_statechange = jiffies +
STATECHANGE_DELAY;
} else if (time_after_eq(jiffies,
ahcd->next_statechange)
&& !ahcd->ed_rm_list
&& !(ahcd->hc_control &
OHCI_SCHED_ENABLES)) {
ahcd_rh_suspend(ahcd, 1);
}
}
break;
/* if there is a port change, autostart or ask to be resumed */
case OHCI_USB_SUSPEND:
case OHCI_USB_RESUME:
if (changed) {
if (ahcd->autostop)
admhc_rh_resume(ahcd);
else
usb_hcd_resume_root_hub(admhcd_to_hcd(ahcd));
} else {
/* everything is idle, no need for polling */
poll_rh = 0;
}
break;
}
return poll_rh;
}
/*-------------------------------------------------------------------------*/
/* must not be called from interrupt context */
static int admhc_restart(struct admhcd *ahcd)
{
int temp;
int i;
struct urb_priv *priv;
/* mark any devices gone, so they do nothing till khubd disconnects.
* recycle any "live" eds/tds (and urbs) right away.
* later, khubd disconnect processing will recycle the other state,
* (either as disconnect/reconnect, or maybe someday as a reset).
*/
spin_lock_irq(&ahcd->lock);
admhc_disable(ahcd);
usb_root_hub_lost_power(admhcd_to_hcd(ahcd)->self.root_hub);
if (!list_empty(&ahcd->pending))
admhc_dbg(ahcd, "abort schedule...\n");
list_for_each_entry(priv, &ahcd->pending, pending) {
struct urb *urb = priv->td[0]->urb;
struct ed *ed = priv->ed;
switch (ed->state) {
case ED_OPER:
ed->state = ED_UNLINK;
ed->hwINFO |= cpu_to_hc32(ahcd, ED_DEQUEUE);
ed_deschedule (ahcd, ed);
ed->ed_next = ahcd->ed_rm_list;
ed->ed_prev = NULL;
ahcd->ed_rm_list = ed;
/* FALLTHROUGH */
case ED_UNLINK:
break;
default:
admhc_dbg(ahcd, "bogus ed %p state %d\n",
ed, ed->state);
}
if (!urb->unlinked)
urb->unlinked = -ESHUTDOWN;
}
finish_unlinks(ahcd, 0);
spin_unlock_irq(&ahcd->lock);
/* paranoia, in case that didn't work: */
/* empty the interrupt branches */
for (i = 0; i < NUM_INTS; i++) ahcd->load[i] = 0;
for (i = 0; i < NUM_INTS; i++) ahcd->hcca->int_table[i] = 0;
/* no EDs to remove */
ahcd->ed_rm_list = NULL;
/* empty control and bulk lists */
ahcd->ed_controltail = NULL;
ahcd->ed_bulktail = NULL;
if ((temp = admhc_run(ahcd)) < 0) {
admhc_err(ahcd, "can't restart, %d\n", temp);
return temp;
} else {
/* here we "know" root ports should always stay powered,
* and that if we try to turn them back on the root hub
* will respond to CSC processing.
*/
i = ahcd->num_ports;
while (i--)
admhc_writel(ahcd, RH_PS_PSS,
&ahcd->regs->portstatus[i]);
admhc_dbg(ahcd, "restart complete\n");
}
return 0;
}
#else /* CONFIG_PM */
static inline int admhc_rh_resume(struct admhcd *ahcd)
{
return 0;
}
/* Carry out polling-related state changes.
* autostop isn't used when CONFIG_PM is turned off.
*/
static int admhc_root_hub_state_changes(struct admhcd *ahcd, int changed,
int any_connected)
{
/* If INSM is enabled, don't poll */
if (admhc_readl(ahcd, &ahcd->regs->int_enable) & ADMHC_INTR_INSM)
return 0;
/* If no status changes are pending, enable status-change interrupts */
if (!changed) {
admhc_intr_enable(ahcd, ADMHC_INTR_INSM);
return 0;
}
return 1;
}
#endif /* CONFIG_PM */
|
mmattamala/gtsam.org
|
doxygen/4.0.0/search/files_4.js
|
<filename>doxygen/4.0.0/search/files_4.js
var searchData=
[
['eliminateablefactorgraph_2eh',['EliminateableFactorGraph.h',['../a00413.html',1,'']]],
['eliminationtree_2eh',['EliminationTree.h',['../a00419.html',1,'']]],
['equalityfactorgraph_2eh',['EqualityFactorGraph.h',['../a01151.html',1,'']]],
['equivinertialnavfactor_5fglobalvel_2eh',['EquivInertialNavFactor_GlobalVel.h',['../a01283.html',1,'']]],
['equivinertialnavfactor_5fglobalvel_5fnobias_2eh',['EquivInertialNavFactor_GlobalVel_NoBias.h',['../a01286.html',1,'']]],
['errors_2ecpp',['Errors.cpp',['../a00512.html',1,'']]],
['errors_2eh',['Errors.h',['../a00515.html',1,'']]],
['essentialmatrixconstraint_2ecpp',['EssentialMatrixConstraint.cpp',['../a00947.html',1,'']]],
['essentialmatrixconstraint_2eh',['EssentialMatrixConstraint.h',['../a00950.html',1,'']]],
['expression_2dinl_2eh',['Expression-inl.h',['../a00782.html',1,'']]],
['expression_2eh',['Expression.h',['../a00785.html',1,'']]],
['expressionfactorgraph_2eh',['ExpressionFactorGraph.h',['../a00791.html',1,'']]],
['expressiontesting_2eh',['expressionTesting.h',['../a00797.html',1,'']]],
['extendedkalmanfilter_2dinl_2eh',['ExtendedKalmanFilter-inl.h',['../a00800.html',1,'']]],
['extendedkalmanfilter_2eh',['ExtendedKalmanFilter.h',['../a00803.html',1,'']]]
];
|
jessejohns-1/underdog-devs-fe-a
|
src/components/pages/Profile/ProfileContainer.js
|
import React from 'react';
import RenderProfile from './RenderProfileContainer';
function ProfileContainer({ LoadingComponent }) {
return (
<>
<RenderProfile />
</>
);
}
export default ProfileContainer;
|
DFE-Digital/fb-runner-node
|
lib/module/savereturn/controller/page/instance/return.setup.mobile.validate/return.setup.mobile.validate.controller.js
|
<reponame>DFE-Digital/fb-runner-node
const {deepClone} = require('@ministryofjustice/fb-utils-node')
const {client, handleValidationError, resetUser, authenticate, sendEmail} = require('../../../savereturn')
const ReturnSetupMobileValidateController = {}
ReturnSetupMobileValidateController.preUpdateContents = async (pageInstance, userData) => {
const authenticated = userData.getUserDataProperty('authenticated')
if (!authenticated) {
pageInstance.redirect = 'page.start'
}
return pageInstance
}
ReturnSetupMobileValidateController.postValidation = async (instance, userData) => {
const code = userData.getUserDataProperty('code')
if (!code) {
return instance
}
const email = userData.getUserDataProperty('email')
const pageInstance = deepClone(instance)
try {
const details = await client.validateSetupMobileCode(code, email, userData.logger)
await resetUser(userData, details)
const {userId, userToken} = details
const mobile = userData.getUserDataProperty('mobile')
await client.createRecord(userId, userToken, email, mobile, userData.logger)
await sendEmail('email.return.setup.mobile.verified', userData)
authenticate(userData, 'setup-mobile')
pageInstance.redirect = 'return.setup.success'
} catch (e) {
if (e.message && e.message === 'code.invalid') {
return pageInstance
}
return handleValidationError(e, 'return.setup.mobile')
}
return pageInstance
}
module.exports = ReturnSetupMobileValidateController
|
jpr86/jevolve
|
src/main/java/com/ridderware/jevolve/DiscreteDoubleGAGene.java
|
/* %%
*
* JEvolve
*
* Copyright 2006 <NAME>
*
* 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.ridderware.jevolve;
import com.ridderware.jrandom.MersenneTwisterFast;
/**
* A discrete gene with double-valued alleles.
*
* @author <NAME>
*/
public class DiscreteDoubleGAGene extends DiscreteGAGene<Double>
{
/**
* Creates a new instance of DiscreteDoubleGAGene.
*/
public DiscreteDoubleGAGene()
{
}
/**
* Creates a new instance of DiscreteDoubleGAGene.
*
* @param lower_bound lower bound for the gene
* @param upper_bound upper bound
* @param num_alleles number of alleles (including the upper and lower bounds).
*/
public DiscreteDoubleGAGene(Double lower_bound, Double upper_bound,
int num_alleles)
{
super(lower_bound, upper_bound);
int num = Math.max(num_alleles, 2);
addAllele(lower_bound);
double delta = (upper_bound - lower_bound) / (double) (num - 1);
for (int i = 1; i < num - 1; i++)
{
addAllele(lower_bound + delta * i);
}
addAllele(upper_bound);
}
/**
* Returns a random allele using a uniform probability distribution.
*
* @return random allele value.
*/
public Double randomUniformValue()
{
Double value = getAllele((int) (MersenneTwisterFast.getInstance().
nextDouble() * getNumAlleles()));
return value;
}
/**
* Returns a random allele using a uniform probability distribution. The
* input parameters are ignored.
*
* @param value ignored.
* @param multiplier ignored.
* @return random allele value
*/
public Double randomUniformValue(Double value, double multiplier)
{
return randomUniformValue();
}
/**
* Returns a random allele using a uniform probability distribution. The
* "Gaussian" is ignored since it makes no sense for unordered discrete genes.
*
* @param value ignored.
* @return random allele value.
*/
public Double randomGaussianValue(Double value)
{
return randomUniformValue();
}
/**
* Returns a random allele using a uniform probability distribution. The
* input parameters are ignored.
*
* @param value ignored.
* @param multiplier ignored.
* @return random allele value
*/
public Double randomGaussianValue(Double value, double multiplier)
{
return randomUniformValue();
}
}
|
dmbeer/wicket-bootstrap
|
bootstrap-extensions/src/main/java/de/agilecoders/wicket/extensions/markup/html/bootstrap/form/validation/TooltipValidation.java
|
<gh_stars>100-1000
package de.agilecoders.wicket.extensions.markup.html.bootstrap.form.validation;
import de.agilecoders.wicket.core.Bootstrap;
import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.BootstrapResourcesBehavior;
import org.apache.wicket.Component;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
/**
* <h1>Validation behavior.</h1>
* <p>Display errors in tooltips.</p>
* This behavior may not work properly with widgets like bootstrap-select or select2.
* In this case try to wrap all inputs in div (that's done by default in bootstrap form layout)
* and set appendToParent of config to true.
* <br/>
* <br/>
* <b>DO NOT USE SimpleMessageValidation behavior and TooltipValidation behavior on one page.</b>
*
* @author <NAME>
* @author <NAME>
* @since 15.09.2014
*/
public class TooltipValidation extends ValidationBehavior<TooltipValidationConfig> {
private static final long serialVersionUID = 1L;
public TooltipValidation() {
this(new TooltipValidationConfig());
}
public TooltipValidation(TooltipValidationConfig config) {
super(config);
}
@Override
public void renderHead(Component component, IHeaderResponse response) {
BootstrapResourcesBehavior.instance().renderHead(Bootstrap.getSettings(), response);
response.render(JavaScriptHeaderItem.forReference(ValidationJS.tooltip()));
super.renderHead(component, response);
}
}
|
tvdeyen/friendly_shipping
|
spec/friendly_shipping/services/ups/serialize_rating_service_selection_request_spec.rb
|
<filename>spec/friendly_shipping/services/ups/serialize_rating_service_selection_request_spec.rb<gh_stars>0
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe FriendlyShipping::Services::Ups::SerializeRatingServiceSelectionRequest do
let(:origin) { FactoryBot.build(:physical_location) }
let(:destination) { FactoryBot.build(:physical_location ) }
let(:dimensions) do
[
Measured::Length.new(10, :centimeters),
Measured::Length.new(10, :centimeters),
Measured::Length.new(10, :centimeters),
]
end
let(:package) do
Physical::Package.new(
container: Physical::Box.new(
weight: Measured::Weight.new(5, :pounds),
dimensions: dimensions
)
)
end
let(:shipment) do
Physical::Shipment.new(
origin: origin,
destination: destination,
packages: [package],
options: options
)
end
let(:options) { { origin_account: "12345" } }
subject do
Nokogiri::XML(
described_class.call(shipment: shipment)
)
end
it 'contains the right data' do
aggregate_failures do
expect(subject.at_xpath('//RatingServiceSelectionRequest')).to be_present
expect(subject.at_xpath('//RatingServiceSelectionRequest/Request')).to be_present
expect(subject.at_xpath('//RatingServiceSelectionRequest/Request/RequestAction').text).to eq('Rate')
expect(subject.at_xpath('//RatingServiceSelectionRequest/Request/RequestOption').text).to eq('Shop')
expect(subject.at_xpath('//RatingServiceSelectionRequest/Request/SubVersion').text).to eq('1707')
expect(subject.at_xpath('//RatingServiceSelectionRequest/PickupType/Code').text).to eq('01')
expect(subject.at_xpath('//RatingServiceSelectionRequest/CustomerClassification/Code').text).to eq('01')
expect(
subject.at_xpath('//RatingServiceSelectionRequest/Shipment/Shipper/Address/AddressLine1').text
).to eq('11 Lovely Street')
expect(subject.at_xpath('//RatingServiceSelectionRequest/Shipment/Shipper/ShipperNumber').text).to be_present
expect(
subject.at_xpath('//RatingServiceSelectionRequest/Shipment/ShipTo/ShipperAssignedIdentificationNumber')
).not_to be_present
expect(subject.at_xpath('//RatingServiceSelectionRequest/Shipment/ShipFrom')).not_to be_present
expect(subject.at_xpath('//RatingServiceSelectionRequest/Shipment/Package')).to be_present
expect(subject.at_xpath('//RatingServiceSelectionRequest/Shipment/Package/PackagingType/Code').text).to eq('02')
expect(
subject.at_xpath('//RatingServiceSelectionRequest/Shipment/Package/PackageWeight/UnitOfMeasurement/Code').text
).to eq('LBS')
expect(subject.at_xpath('//RatingServiceSelectionRequest/Shipment/Package/PackageWeight/Weight').text).to eq('5')
end
end
context 'with a different shipper' do
let(:options) { { shipper: FactoryBot.build(:physical_location, address1: "Another Street") } }
it 'contains an extra ShipFrom element' do
aggregate_failures do
expect(subject.at_xpath('//RatingServiceSelectionRequest/Shipment/ShipFrom')).to be_present
expect(
subject.at_xpath('//RatingServiceSelectionRequest/Shipment/Shipper/Address/AddressLine1').text
).to eq('Another Street')
expect(
subject.at_xpath('//RatingServiceSelectionRequest/Shipment/ShipFrom/Address/AddressLine1').text
).to eq('11 Lovely Street')
end
end
end
end
|
ruoranluomu/AliOS-Things
|
board/developerkit/bootloader/Src/hal_boot_uart.c
|
#include "main.h"
#include "stm32l4xx_hal.h"
#define LPUARTx LPUART1
#define LPUARTx_CLK_ENABLE() __HAL_RCC_LPUART1_CLK_ENABLE();
#define LPUARTx_RX_GPIO_CLK_ENABLE() __HAL_RCC_GPIOB_CLK_ENABLE()
#define LPUARTx_TX_GPIO_CLK_ENABLE() __HAL_RCC_GPIOB_CLK_ENABLE()
#define LPUARTx_FORCE_RESET() __HAL_RCC_LPUART1_FORCE_RESET()
#define LPUARTx_RELEASE_RESET() __HAL_RCC_LPUART1_RELEASE_RESET()
/* Definition for LPUART Pins */
#define LPUARTx_TX_PIN GPIO_PIN_11
#define LPUARTx_TX_GPIO_PORT GPIOB
#define LPUARTx_TX_AF GPIO_AF8_LPUART1
#define LPUARTx_RX_PIN GPIO_PIN_10
#define LPUARTx_RX_GPIO_PORT GPIOB
#define LPUARTx_RX_AF GPIO_AF8_LPUART1
/* Definition for LPUART's NVIC */
#define LPUARTx_IRQn LPUART1_IRQn
#define LPUARTx_IRQHandler LPUART1_IRQHandler
/* Size of Trasmission buffer */
#define TXBUFFERSIZE (COUNTOF(aTxBuffer) - 1)
/* Size of Reception buffer */
#define RXBUFFERSIZE TXBUFFERSIZE
/* Exported macro ------------------------------------------------------------*/
#define COUNTOF(__BUFFER__) (sizeof(__BUFFER__) / sizeof(*(__BUFFER__)))
#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \
USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8 ))
#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE | USART_CR3_ONEBIT))
#define LPUART_BRR_MIN 0x00000300U
#define LPUART_BRR_MAX 0x000FFFFFU
#define UART_BRR_MIN 0x10U
#define UART_BRR_MAX 0x0000FFFFU
static void UART_TxISR_8BIT(UART_HandleTypeDef *huart)
{
if (huart->gState == HAL_UART_STATE_BUSY_TX) {
if (huart->TxXferCount == 0) {
CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE);
SET_BIT(huart->Instance->CR1, USART_CR1_TCIE);
}
else {
huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0xFF);
huart->TxXferCount--;
}
}
}
void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init);
static void UART_TxISR_16BIT(UART_HandleTypeDef *huart)
{
uint16_t *tmp;
if (huart->gState == HAL_UART_STATE_BUSY_TX) {
if (huart->TxXferCount == 0) {
CLEAR_BIT(huart->Instance->CR1, USART_CR1_TXEIE);
SET_BIT(huart->Instance->CR1, USART_CR1_TCIE);
}
else {
tmp = (uint16_t *) huart->pTxBuffPtr;
huart->Instance->TDR = (*tmp & (uint16_t)0x01FF);
huart->pTxBuffPtr += 2;
huart->TxXferCount--;
}
}
}
HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
if (huart->gState == HAL_UART_STATE_READY) {
if ((pData == NULL) || (Size == 0U)) {
return HAL_ERROR;
}
__HAL_LOCK(huart);
huart->pTxBuffPtr = pData;
huart->TxXferSize = Size;
huart->TxXferCount = Size;
huart->TxISR = NULL;
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_BUSY_TX;
if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) {
huart->TxISR = UART_TxISR_16BIT;
}
else {
huart->TxISR = UART_TxISR_8BIT;
}
__HAL_UNLOCK(huart);
SET_BIT(huart->Instance->CR1, USART_CR1_TXEIE);
return HAL_OK;
}
else {
return HAL_BUSY;
}
}
void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
GPIO_InitTypeDef GPIO_InitStruct;
LPUARTx_TX_GPIO_CLK_ENABLE();
LPUARTx_RX_GPIO_CLK_ENABLE();
LPUARTx_CLK_ENABLE();
GPIO_InitStruct.Pin = LPUARTx_TX_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = LPUARTx_TX_AF;
HAL_GPIO_Init(LPUARTx_TX_GPIO_PORT, &GPIO_InitStruct);
GPIO_InitStruct.Pin = LPUARTx_RX_PIN;
GPIO_InitStruct.Alternate = LPUARTx_RX_AF;
HAL_GPIO_Init(LPUARTx_RX_GPIO_PORT, &GPIO_InitStruct);
HAL_NVIC_SetPriority(LPUARTx_IRQn, 0, 1);
HAL_NVIC_EnableIRQ(LPUARTx_IRQn);
}
HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart)
{
uint32_t tmpreg = 0x00000000U;
UART_ClockSourceTypeDef clocksource = UART_CLOCKSOURCE_UNDEFINED;
uint16_t brrtemp = 0x0000U;
uint32_t usartdiv = 0x00000000U;
HAL_StatusTypeDef ret = HAL_OK;
uint32_t lpuart_ker_ck_pres = 0x00000000U;
assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate));
assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength));
if (UART_INSTANCE_LOWPOWER(huart)) {
assert_param(IS_LPUART_STOPBITS(huart->Init.StopBits));
}
else {
assert_param(IS_UART_STOPBITS(huart->Init.StopBits));
assert_param(IS_UART_ONE_BIT_SAMPLE(huart->Init.OneBitSampling));
}
tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling ;
MODIFY_REG(huart->Instance->CR1, USART_CR1_FIELDS, tmpreg);
MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits);
tmpreg = (uint32_t)huart->Init.HwFlowCtl;
if (!(UART_INSTANCE_LOWPOWER(huart))) {
tmpreg |= huart->Init.OneBitSampling;
}
MODIFY_REG(huart->Instance->CR3, USART_CR3_FIELDS, tmpreg);
UART_GETCLOCKSOURCE(huart, clocksource);
if (UART_INSTANCE_LOWPOWER(huart)) {
lpuart_ker_ck_pres = HAL_RCC_GetPCLK1Freq();
if (lpuart_ker_ck_pres != 0U) {
if ((lpuart_ker_ck_pres < (3 * huart->Init.BaudRate)) ||
(lpuart_ker_ck_pres > (4096 * huart->Init.BaudRate))) {
ret = HAL_ERROR;
}
else {
usartdiv = (uint32_t)(UART_DIV_LPUART(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate));
if ((usartdiv >= LPUART_BRR_MIN) && (usartdiv <= LPUART_BRR_MAX)) {
huart->Instance->BRR = usartdiv;
}
else {
ret = HAL_ERROR;
}
}
}
}
else if (huart->Init.OverSampling == UART_OVERSAMPLING_8) {
usartdiv = (uint16_t)(UART_DIV_SAMPLING8(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate));
if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) {
brrtemp = usartdiv & 0xFFF0U;
brrtemp |= (uint16_t)((usartdiv & (uint16_t)0x000FU) >> 1U);
huart->Instance->BRR = brrtemp;
}
else {
ret = HAL_ERROR;
}
}
else {
usartdiv = (uint16_t)(UART_DIV_SAMPLING16(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate));
if ((usartdiv >= UART_BRR_MIN) && (usartdiv <= UART_BRR_MAX)) {
huart->Instance->BRR = usartdiv;
}
else {
ret = HAL_ERROR;
}
}
huart->RxISR = NULL;
huart->TxISR = NULL;
return ret;
}
void UART_AdvFeatureConfig(UART_HandleTypeDef *huart)
{
assert_param(IS_UART_ADVFEATURE_INIT(huart->AdvancedInit.AdvFeatureInit));
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_TXINVERT_INIT)) {
assert_param(IS_UART_ADVFEATURE_TXINV(huart->AdvancedInit.TxPinLevelInvert));
MODIFY_REG(huart->Instance->CR2, USART_CR2_TXINV, huart->AdvancedInit.TxPinLevelInvert);
}
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXINVERT_INIT)) {
assert_param(IS_UART_ADVFEATURE_RXINV(huart->AdvancedInit.RxPinLevelInvert));
MODIFY_REG(huart->Instance->CR2, USART_CR2_RXINV, huart->AdvancedInit.RxPinLevelInvert);
}
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DATAINVERT_INIT)) {
assert_param(IS_UART_ADVFEATURE_DATAINV(huart->AdvancedInit.DataInvert));
MODIFY_REG(huart->Instance->CR2, USART_CR2_DATAINV, huart->AdvancedInit.DataInvert);
}
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_SWAP_INIT)) {
assert_param(IS_UART_ADVFEATURE_SWAP(huart->AdvancedInit.Swap));
MODIFY_REG(huart->Instance->CR2, USART_CR2_SWAP, huart->AdvancedInit.Swap);
}
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXOVERRUNDISABLE_INIT)) {
assert_param(IS_UART_OVERRUN(huart->AdvancedInit.OverrunDisable));
MODIFY_REG(huart->Instance->CR3, USART_CR3_OVRDIS, huart->AdvancedInit.OverrunDisable);
}
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DMADISABLEONERROR_INIT)) {
assert_param(IS_UART_ADVFEATURE_DMAONRXERROR(huart->AdvancedInit.DMADisableonRxError));
MODIFY_REG(huart->Instance->CR3, USART_CR3_DDRE, huart->AdvancedInit.DMADisableonRxError);
}
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_AUTOBAUDRATE_INIT)) {
assert_param(IS_USART_AUTOBAUDRATE_DETECTION_INSTANCE(huart->Instance));
assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATE(huart->AdvancedInit.AutoBaudRateEnable));
MODIFY_REG(huart->Instance->CR2, USART_CR2_ABREN, huart->AdvancedInit.AutoBaudRateEnable);
if (huart->AdvancedInit.AutoBaudRateEnable == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE) {
assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(huart->AdvancedInit.AutoBaudRateMode));
MODIFY_REG(huart->Instance->CR2, USART_CR2_ABRMODE, huart->AdvancedInit.AutoBaudRateMode);
}
}
if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_MSBFIRST_INIT)) {
assert_param(IS_UART_ADVFEATURE_MSBFIRST(huart->AdvancedInit.MSBFirst));
MODIFY_REG(huart->Instance->CR2, USART_CR2_MSBFIRST, huart->AdvancedInit.MSBFirst);
}
}
HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart)
{
if (huart == NULL) {
return HAL_ERROR;
}
if (huart->Init.HwFlowCtl != UART_HWCONTROL_NONE) {
assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance));
}
else {
assert_param((IS_UART_INSTANCE(huart->Instance)) || (IS_LPUART_INSTANCE(huart->Instance)));
}
if (huart->gState == HAL_UART_STATE_RESET) {
huart->Lock = HAL_UNLOCKED;
HAL_UART_MspInit(huart);
}
huart->gState = HAL_UART_STATE_BUSY;
__HAL_UART_DISABLE(huart);
if (UART_SetConfig(huart) == HAL_ERROR) {
return HAL_ERROR;
}
if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) {
UART_AdvFeatureConfig(huart);
}
CLEAR_BIT(huart->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN));
CLEAR_BIT(huart->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN));
__HAL_UART_ENABLE(huart);
return (UART_CheckIdleState(huart));
}
HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout)
{
while ((__HAL_UART_GET_FLAG(huart, Flag) ? SET : RESET) == Status) {
if (Timeout != HAL_MAX_DELAY) {
if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) {
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
__HAL_UNLOCK(huart);
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart)
{
uint32_t tickstart = 0U;
huart->ErrorCode = HAL_UART_ERROR_NONE;
tickstart = HAL_GetTick();
if ((huart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) {
if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_TEACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) {
return HAL_TIMEOUT;
}
}
if ((huart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) {
if (UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, tickstart, HAL_UART_TIMEOUT_VALUE) != HAL_OK) {
return HAL_TIMEOUT;
}
}
huart->gState = HAL_UART_STATE_READY;
huart->RxState = HAL_UART_STATE_READY;
__HAL_UNLOCK(huart);
return HAL_OK;
}
static void UART_RxISR_8BIT(UART_HandleTypeDef *huart)
{
uint16_t uhMask = huart->Mask;
uint16_t uhdata;
if (huart->RxState == HAL_UART_STATE_BUSY_RX) {
uhdata = (uint16_t) READ_REG(huart->Instance->RDR);
*huart->pRxBuffPtr++ = (uint8_t)(uhdata & (uint8_t)uhMask);
if (--huart->RxXferCount == 0) {
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
huart->RxState = HAL_UART_STATE_READY;
huart->RxISR = NULL;
HAL_UART_RxCpltCallback(huart);
}
}
else {
__HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST);
}
}
static void UART_RxISR_16BIT(UART_HandleTypeDef *huart)
{
uint16_t *tmp;
uint16_t uhMask = huart->Mask;
uint16_t uhdata;
if (huart->RxState == HAL_UART_STATE_BUSY_RX) {
uhdata = (uint16_t) READ_REG(huart->Instance->RDR);
tmp = (uint16_t *) huart->pRxBuffPtr ;
*tmp = (uint16_t)(uhdata & uhMask);
huart->pRxBuffPtr += 2;
if (--huart->RxXferCount == 0) {
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
huart->RxState = HAL_UART_STATE_READY;
huart->RxISR = NULL;
HAL_UART_RxCpltCallback(huart);
}
}
else {
__HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST);
}
}
HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
if (huart->RxState == HAL_UART_STATE_READY) {
if ((pData == NULL) || (Size == 0U)) {
return HAL_ERROR;
}
__HAL_LOCK(huart);
huart->pRxBuffPtr = pData;
huart->RxXferSize = Size;
huart->RxXferCount = Size;
huart->RxISR = NULL;
UART_MASK_COMPUTATION(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->RxState = HAL_UART_STATE_BUSY_RX;
SET_BIT(huart->Instance->CR3, USART_CR3_EIE);
if ((huart->Init.WordLength == UART_WORDLENGTH_9B)
&& (huart->Init.Parity == UART_PARITY_NONE)) {
huart->RxISR = UART_RxISR_16BIT;
}
else {
huart->RxISR = UART_RxISR_8BIT;
}
__HAL_UNLOCK(huart);
SET_BIT(huart->Instance->CR1, USART_CR1_PEIE | USART_CR1_RXNEIE);
return HAL_OK;
}
else {
return HAL_BUSY;
}
}
__weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
UNUSED(huart);
}
static void UART_EndTransmit_IT(UART_HandleTypeDef *huart)
{
CLEAR_BIT(huart->Instance->CR1, USART_CR1_TCIE);
huart->gState = HAL_UART_STATE_READY;
huart->TxISR = NULL;
HAL_UART_TxCpltCallback(huart);
}
static void UART_EndRxTransfer(UART_HandleTypeDef *huart)
{
CLEAR_BIT(huart->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(huart->Instance->CR3, USART_CR3_EIE);
huart->RxState = HAL_UART_STATE_READY;
huart->RxISR = NULL;
}
__weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
UNUSED(huart);
}
__weak void HAL_UART_AbortCpltCallback(UART_HandleTypeDef *huart)
{
UNUSED(huart);
}
__weak void HAL_UARTEx_WakeupCallback(UART_HandleTypeDef *huart)
{
UNUSED(huart);
}
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
{
uint32_t isrflags = READ_REG(huart->Instance->ISR);
uint32_t cr1its = READ_REG(huart->Instance->CR1);
uint32_t cr3its = READ_REG(huart->Instance->CR3);
uint32_t errorflags;
errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE));
if (errorflags == RESET) {
if (((isrflags & USART_ISR_RXNE) != RESET)
&& ((cr1its & USART_CR1_RXNEIE) != RESET)) {
if (huart->RxISR != NULL) {
huart->RxISR(huart);
}
return;
}
}
if ((errorflags != RESET) && (((cr3its & USART_CR3_EIE) != RESET)
|| ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET))) {
if (((isrflags & USART_ISR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET)) {
__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_PEF);
huart->ErrorCode |= HAL_UART_ERROR_PE;
}
if (((isrflags & USART_ISR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) {
__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_FEF);
huart->ErrorCode |= HAL_UART_ERROR_FE;
}
if (((isrflags & USART_ISR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET)) {
__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF);
huart->ErrorCode |= HAL_UART_ERROR_NE;
}
if (((isrflags & USART_ISR_ORE) != RESET) && (((cr1its & USART_CR1_RXNEIE) != RESET) ||
((cr3its & USART_CR3_EIE) != RESET))) {
__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_OREF);
huart->ErrorCode |= HAL_UART_ERROR_ORE;
}
if (huart->ErrorCode != HAL_UART_ERROR_NONE) {
if (((isrflags & USART_ISR_RXNE) != RESET)
&& ((cr1its & USART_CR1_RXNEIE) != RESET)) {
if (huart->RxISR != NULL) {
huart->RxISR(huart);
}
}
if (((huart->ErrorCode & HAL_UART_ERROR_ORE) != RESET) ||
(HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR))) {
UART_EndRxTransfer(huart);
if (HAL_IS_BIT_SET(huart->Instance->CR3, USART_CR3_DMAR)) {
CLEAR_BIT(huart->Instance->CR3, USART_CR3_DMAR);
}
else {
HAL_UART_ErrorCallback(huart);
}
}
else {
HAL_UART_ErrorCallback(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
}
}
return;
}
if (((isrflags & USART_ISR_WUF) != RESET) && ((cr3its & USART_CR3_WUFIE) != RESET)) {
__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_WUF);
HAL_UARTEx_WakeupCallback(huart);
return;
}
if (((isrflags & USART_ISR_TXE) != RESET)
&& ((cr1its & USART_CR1_TXEIE) != RESET)) {
if (huart->TxISR != NULL) {
huart->TxISR(huart);
}
return;
}
if (((isrflags & USART_ISR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET)) {
UART_EndTransmit_IT(huart);
return;
}
}
HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t *tmp;
uint32_t tickstart = 0U;
if (huart->gState == HAL_UART_STATE_READY) {
if ((pData == NULL) || (Size == 0U)) {
return HAL_ERROR;
}
__HAL_LOCK(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->gState = HAL_UART_STATE_BUSY_TX;
tickstart = HAL_GetTick();
huart->TxXferSize = Size;
huart->TxXferCount = Size;
while (huart->TxXferCount > 0U) {
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK) {
return HAL_TIMEOUT;
}
if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) {
tmp = (uint16_t *) pData;
huart->Instance->TDR = (*tmp & (uint16_t)0x01FFU);
pData += 2U;
}
else {
huart->Instance->TDR = (*pData++ & (uint8_t)0xFFU);
}
huart->TxXferCount--;
}
if (UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK) {
return HAL_TIMEOUT;
}
huart->gState = HAL_UART_STATE_READY;
__HAL_UNLOCK(huart);
return HAL_OK;
}
else {
return HAL_BUSY;
}
}
#define UART_RECE_SIZE (64)
UART_HandleTypeDef hlpuart1;
uint8_t aRxByte = 0;
uint8_t aRxBuffer[UART_RECE_SIZE];
uint8_t aRx_ptr = 0;
uint8_t aRx_ctr = 0;
__IO ITStatus UartReady = RESET;
void hal_uart_Init(void)
{
hlpuart1.Instance = LPUART1;
hlpuart1.Init.BaudRate = 115200;
hlpuart1.Init.WordLength = UART_WORDLENGTH_8B;
hlpuart1.Init.StopBits = UART_STOPBITS_1;
hlpuart1.Init.Parity = UART_PARITY_NONE;
hlpuart1.Init.Mode = UART_MODE_TX_RX;
hlpuart1.Init.OverSampling = UART_OVERSAMPLING_16;
hlpuart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
hlpuart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
if (HAL_UART_Init(&hlpuart1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
if(HAL_UART_Receive_IT(&hlpuart1, (uint8_t *)&aRxByte, 1) != HAL_OK)
{
hal_uart_send_string("boot uart receive mode set failed\r\n");
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
{
/* Set transmission flag: trasfer complete*/
UartReady = SET;
if(HAL_UART_Receive_IT(UartHandle, (unsigned char *)&aRxByte, 1) != HAL_OK) {
;
}
aRxBuffer[aRx_ptr++] = aRxByte;
aRx_ptr = aRx_ptr % UART_RECE_SIZE;
}
unsigned char hal_get_uart_receive_data(unsigned char *c)
{
unsigned char rx_done = 0;
if(aRx_ctr != aRx_ptr) {
rx_done = 1;
*c = aRxBuffer[aRx_ctr++];
aRx_ctr = aRx_ctr % UART_RECE_SIZE;
}
return rx_done;
}
static void hal_uart_send(unsigned char *buff, int len)
{
while (len--)
HAL_UART_Transmit(&hlpuart1, buff++, 1, 1000);
}
void hal_uart_send_string( char *str)
{
while(*str)
HAL_UART_Transmit(&hlpuart1, str++, 1, 1000);
}
|
MineGame159/donat
|
donat/src/minegame159/donat/rendering/common/Mesh.java
|
package minegame159.donat.rendering.common;
import minegame159.donat.Disposable;
import minegame159.donat.collections.FloatArray;
import minegame159.donat.collections.IntArray;
import static org.lwjgl.opengl.GL33C.*;
public class Mesh implements Disposable {
private int vaoHandle, vboHandle, iboHandle;
public FloatArray vertices;
public IntArray indices;
public final VertexAttribute[] vertexAttributes;
private int indicesCount;
public Mesh(FloatArray vertices, IntArray indices, VertexAttribute... vertexAttributes) {
this.vertices = vertices;
this.indices = indices;
this.vertexAttributes = vertexAttributes;
vaoHandle = glGenVertexArrays();
glBindVertexArray(vaoHandle);
// Vertices
vboHandle = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vboHandle);
glBufferData(GL_ARRAY_BUFFER, vertices.getArray(), GL_STATIC_DRAW);
calculateVertexAttributes();
// Indices
iboHandle = glGenBuffers();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.getArray(), GL_STATIC_DRAW);
indicesCount = indices.size;
}
private void calculateVertexAttributes() {
int stride = 0;
for (int i = 0; i < vertexAttributes.length; i++) {
stride += vertexAttributes[i].getComponentSize() * 4;
}
int offset = 0;
for (int i = 0; i < vertexAttributes.length; i++) {
VertexAttribute vertexAttribute = vertexAttributes[i];
glEnableVertexAttribArray(i);
glVertexAttribPointer(i, vertexAttribute.getComponentSize(), GL_FLOAT, vertexAttribute.isNormalized(), stride, offset);
offset += vertexAttribute.getComponentSize() * 4;
}
}
public void render() {
glBindVertexArray(vaoHandle);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboHandle);
glDrawElements(GL_TRIANGLES, indicesCount, GL_UNSIGNED_INT, 0);
}
public void updateVertices() {
glBindBuffer(GL_ARRAY_BUFFER, vboHandle);
glBufferData(GL_ARRAY_BUFFER, vertices.getArray(), GL_STATIC_DRAW);
}
public void updateIndices() {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboHandle);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.getArray(), GL_STATIC_DRAW);
indicesCount = indices.size;
}
@Override
public void dispose() {
glDeleteVertexArrays(vaoHandle);
glDeleteBuffers(vboHandle);
glDeleteBuffers(iboHandle);
}
}
|
eiichiro/bootleg
|
src/main/java/org/eiichiro/bootleg/Forward.java
|
<filename>src/main/java/org/eiichiro/bootleg/Forward.java<gh_stars>0
/*
* Copyright (C) 2011-2013 <NAME>. 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 org.eiichiro.bootleg;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eiichiro.reverb.lang.UncheckedException;
/**
* {@code Forward} is a {@link Response} implementation to forward HTTP request
* to another resource.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public class Forward implements Response {
private final String path;
/**
* Constructs {@code Forward} instance to forward to the specified path.
*
* @param path The path to be forwarded. The specified path must be
* relative.
*/
public Forward(String path) {
this.path = path;
}
/** Unsupported operation. {@code UnsupportedOperationException} is thrown. */
public void status(int status) {
throw new UnsupportedOperationException(
"'public void status(int status)' is not supoprted in ["
+ getClass().getName() + "]");
}
/** Unsupported operation. {@code UnsupportedOperationException} is thrown. */
public void mediaType(String mediaType) {
throw new UnsupportedOperationException(
"'public void mediaType(String mediaType)' is not supoprted in ["
+ getClass().getName() + "]");
}
/** Unsupported operation. {@code UnsupportedOperationException} is thrown. */
public void entity(Object entity) {
throw new UnsupportedOperationException(
"'public void entity(Object entity)' is not supoprted in ["
+ getClass().getName() + "]");
}
/**
* Forwards HTTP request to the specified path.
*
* @param context HTTP request processing context.
*/
public void to(WebContext context) {
HttpServletRequest request = context.request();
HttpServletResponse response = context.response();
try {
request.getRequestDispatcher(path).forward(request, response);
} catch (ServletException e) {
throw new UncheckedException(e);
} catch (IOException e) {
throw new UncheckedException(e);
}
}
}
|
jellisgwn/DependencyCheck
|
utils/src/test/java/org/owasp/dependencycheck/utils/SettingsTest.java
|
<gh_stars>1000+
/*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 <NAME>. All Rights Reserved.
*/
package org.owasp.dependencycheck.utils;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
/**
*
* @author <NAME>
*/
public class SettingsTest extends BaseTest {
/**
* Test of getString method, of class Settings.
*/
@Test
public void testGetString() {
String key = Settings.KEYS.CVE_MODIFIED_VALID_FOR_DAYS;
String expResult = "7";
String result = getSettings().getString(key);
Assert.assertTrue(result.endsWith(expResult));
}
/**
* Test of getDataFile method, of class Settings.
*/
@Test
public void testGetDataFile() throws IOException {
String key = Settings.KEYS.DATA_DIRECTORY;
String expResult = "data";
File result = getSettings().getDataFile(key);
Assert.assertTrue(result.getAbsolutePath().endsWith(expResult));
}
/**
* Test of mergeProperties method, of class Settings.
*
* @throws java.io.IOException thrown when the test fails
* @throws java.net.URISyntaxException thrown when the test fails
*/
@Test
public void testMergeProperties_String() throws IOException, URISyntaxException {
String key = Settings.KEYS.PROXY_PORT;
String expResult = getSettings().getString(key);
File f = new File(this.getClass().getClassLoader().getResource("test.properties").toURI());
//InputStream in = this.getClass().getClassLoader().getResourceAsStream("test.properties");
getSettings().mergeProperties(f.getAbsolutePath());
String result = getSettings().getString(key);
Assert.assertTrue("setting didn't change?", (expResult == null && result != null) || !expResult.equals(result));
}
/**
* Test of setString method, of class Settings.
*/
@Test
public void testSetString() {
String key = "newProperty";
String value = "someValue";
getSettings().setString(key, value);
String expResults = getSettings().getString(key);
Assert.assertEquals(expResults, value);
}
/**
* Test of setStringIfNotNull method, of class Settings.
*/
@Test
public void testSetStringIfNotNull() {
String key = "nullableProperty";
String value = "someValue";
getSettings().setString(key, value);
getSettings().setStringIfNotNull(key, null); // NO-OP
String expResults = getSettings().getString(key);
Assert.assertEquals(expResults, value);
}
/**
* Test of setStringIfNotNull method, of class Settings.
*/
@Test
public void testSetStringIfNotEmpty() {
String key = "optionalProperty";
String value = "someValue";
getSettings().setString(key, value);
getSettings().setStringIfNotEmpty(key, ""); // NO-OP
String expResults = getSettings().getString(key);
Assert.assertEquals(expResults, value);
}
/**
* Test of getString method, of class Settings.
*/
@Test
public void testGetString_String_String() {
String key = "key That Doesn't Exist";
String defaultValue = "blue bunny";
String expResult = "blue bunny";
String result = getSettings().getString(key);
Assert.assertTrue(result == null);
result = getSettings().getString(key, defaultValue);
Assert.assertEquals(expResult, result);
}
/**
* Test of getString method, of class Settings.
*/
@Test
public void testGetString_String() {
String key = Settings.KEYS.CONNECTION_TIMEOUT;
String result = getSettings().getString(key);
Assert.assertTrue(result == null);
}
/**
* Test of getInt method, of class Settings.
*/
@Test
public void testGetInt() throws InvalidSettingException {
String key = "SomeNumber";
int expResult = 85;
getSettings().setString(key, "85");
int result = getSettings().getInt(key);
Assert.assertEquals(expResult, result);
}
/**
* Test of getInt method, of class Settings.
*/
@Test
public void testGetIntDefault() throws InvalidSettingException {
String key = "SomeKey";
int expResult = 85;
getSettings().setString(key, "blue");
int result = getSettings().getInt(key, expResult);
Assert.assertEquals(expResult, result);
}
/**
* Test of getLong method, of class Settings.
*/
@Test
public void testGetLong() throws InvalidSettingException {
String key = "SomeNumber";
long expResult = 300L;
getSettings().setString(key, "300");
long result = getSettings().getLong(key);
Assert.assertEquals(expResult, result);
}
/**
* Test of getBoolean method, of class Settings.
*/
@Test
public void testGetBoolean() throws InvalidSettingException {
String key = "SomeBoolean";
getSettings().setString(key, "false");
boolean expResult = false;
boolean result = getSettings().getBoolean(key);
Assert.assertEquals(expResult, result);
key = "something that does not exist";
expResult = true;
result = getSettings().getBoolean(key, true);
Assert.assertEquals(expResult, result);
}
/**
* Test of removeProperty method, of class Settings.
*/
@Test
public void testRemoveProperty() {
String key = "SomeKey";
String value = "value";
String dfault = "default";
getSettings().setString(key, value);
String ret = getSettings().getString(key);
Assert.assertEquals(value, ret);
getSettings().removeProperty(key);
ret = getSettings().getString(key, dfault);
Assert.assertEquals(dfault, ret);
}
/**
* Test of getConnectionString.
*/
@Test
public void testGetConnectionString() throws Exception {
String value = getSettings().getConnectionString(Settings.KEYS.DB_CONNECTION_STRING, Settings.KEYS.DB_FILE_NAME);
Assert.assertNotNull(value);
String msg = null;
try {
value = getSettings().getConnectionString("invalidKey", null);
} catch (InvalidSettingException e) {
msg = e.getMessage();
}
Assert.assertNotNull(msg);
}
/**
* Test of getTempDirectory.
*/
@Test
public void testGetTempDirectory() throws Exception {
File tmp = getSettings().getTempDirectory();
Assert.assertTrue(tmp.exists());
}
/**
* Assert {@link Settings#getArray(String)} from a delimited string returns
* multiple values in an array.
*/
@Test
public void testGetArrayFromADelimitedString() {
// GIVEN a delimited string
final String delimitedString = "value1,value2";
getSettings().setString("key", delimitedString);
// WHEN getting the array
final String[] array = getSettings().getArray("key");
// THEN the split array is returned
assertThat("Expected the array to be non-null", array, notNullValue());
assertThat("Expected the array to have two values", array.length, is(2));
assertThat("Expected the first array value to be value1", array[0], is("value1"));
assertThat("Expected the second array value to be value2", array[1], is("value2"));
}
/**
* Assert {@link Settings#getArray(String)} returns {@code null} if the
* property is not set.
*/
@Test
public void testGetArrayWhereThePropertyIsNotSet() {
// WHEN getting the array
final String[] array = getSettings().getArray("key");
// THEN null is returned
assertThat("Expected the array to be null", array, nullValue());
}
/**
* Assert {@link Settings#setArrayIfNotEmpty(String, String[])} with an
* empty array is ignored.
*/
@Test
public void testSetArrayNotEmptyIgnoresAnEmptyArray() {
// GIVEN an empty array
final String[] array = {};
// WHEN setting the array
getSettings().setArrayIfNotEmpty("key", array);
// THEN the property was not set
assertThat("Expected the property to not be set", getSettings().getString("key"), nullValue());
}
/**
* Assert {@link Settings#setArrayIfNotEmpty(String, String[])} with a null
* array is ignored.
*/
@Test
public void testSetArrayNotEmptyIgnoresAnNullArray() {
// GIVEN a null array
final String[] array = null;
// WHEN setting the array
getSettings().setArrayIfNotEmpty("key", array);
// THEN the property was not set
assertThat("Expected the property to not be set", getSettings().getString("key"), nullValue());
}
/**
* Assert {@link Settings#setArrayIfNotEmpty(String, List<String>)}
* correctly stores the list as an array.
*/
@Test
public void testSetArrayNotEmptyWithList() {
// GIVEN a null array
final List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
// WHEN setting the array
getSettings().setArrayIfNotEmpty("key", list);
// THEN the property was not set
assertThat("Expected the property to not be set", getSettings().getArray("key"),
equalTo(new String[]{"one", "two"}));
}
@Test
public void testMaskedKeys() {
getSettings().initMaskedKeys();
assertThat("password should be masked",
getSettings().getPrintableValue("odc.database.password", "<PASSWORD>!"),
equalTo("********"));
assertThat("tokens should be masked",
getSettings().getPrintableValue("odc.api.token", "<PASSWORD>"),
equalTo("********"));
assertThat("other keys should not be masked",
getSettings().getPrintableValue("odc.version", "5.0.0"),
equalTo("5.0.0"));
}
}
|
aluminous/caver-java
|
core/src/main/java/com/klaytn/caver/methods/request/KlayLogFilter.java
|
/*
* Copyright 2019 The caver-java Authors
*
* 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.klaytn.caver.methods.request;
import org.web3j.protocol.core.DefaultBlockParameter;
import java.util.Arrays;
import java.util.List;
public class KlayLogFilter extends KlayFilter {
/**
* (optional) A filter option that restricts the logs returned to the single block with the 32-byte hash blockHash.
* Using blockHash is equivalent to fromBlock = toBlock = the block number with hash blockHash. If blockHash is
* present in in the filter criteria, then neither fromBlock nor toBlock are allowed.
*/
private String blockHash;
public KlayLogFilter() {
super();
}
public KlayLogFilter(DefaultBlockParameter fromBlock, DefaultBlockParameter toBlock,
List<String> address, String blockHash) {
super(fromBlock, toBlock, address);
this.blockHash = blockHash;
}
public KlayLogFilter(DefaultBlockParameter fromBlock, DefaultBlockParameter toBlock,
String address, String blockHash) {
this(fromBlock, toBlock, Arrays.asList(address), blockHash);
}
public String getBlockHash() {
return blockHash;
}
@Override
KlayLogFilter getThis() {
return this;
}
}
|
tomcamp0228/ibeo_ros2
|
src/ibeo_8l_sdk/src/ibeosdk/MeasurementKey.cpp
|
//======================================================================
/*! \file MeasurementKey.cpp
*
* \copydoc Copyright
* \author <NAME> (jcd)
* \date May 3, 2016
*///-------------------------------------------------------------------
//======================================================================
#include <ibeosdk/misc/WinCompatibility.hpp>
#include <ibeosdk/MeasurementKey.hpp>
#include <ibeosdk/datablocks/snippets/Measurement.hpp>
//======================================================================
namespace ibeosdk {
//======================================================================
bool MeasurementKey::compare(const Measurement& m, const MeasurementKey key)
{
return key == m.getKey();
}
//======================================================================
} // namespace ibeosdk
//======================================================================
|
aras-p/dingus
|
dingus/dingus/utils/AssertHelper.h
|
// --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#ifndef __ASSERT_HELP_H
#define __ASSERT_HELP_H
#define ASSERT_MSG( condition, message ) assert( (condition) || !message )
#define ASSERT_FAIL_MSG( message ) assert( !message )
#define ASSERT_NOT_IMPL ASSERT_FAIL_MSG("not implemented")
#endif
|
wanderBee/launch-advertising-api
|
src/logger/index.js
|
const pino = require('pino');
const config = require('../config');
module.exports = pino({
level: config.get('logger.level'),
prettyPrint: config.get('env') !== 'production'
});
|
iryabov/n2o-framework
|
frontend/n2o-framework/src/reducers.js
|
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
import { reducer as formReducer } from 'redux-form';
import widgets from './reducers/widgets';
import models from './reducers/models';
import global from './reducers/global';
import pages from './reducers/pages';
import alerts from './reducers/alerts';
import overlays from './reducers/overlays';
import columns from './reducers/columns';
import toolbar from './reducers/toolbar';
import formPlugin from './reducers/formPlugin';
import user from './reducers/auth';
import regions from './reducers/regions';
const formHack = (state, action) => {
return action.meta && action.meta.form
? formReducer.plugin({
[action.meta.form]: (formState, formAction) => {
return Object.assign(
{},
formState,
formPlugin(formState, formAction)
);
},
})(state, action)
: formReducer(state, action);
};
export default (history, customReducers = {}) =>
combineReducers({
router: connectRouter(history),
form: formHack,
widgets,
models,
global,
pages,
alerts,
overlays,
columns,
toolbar,
user,
regions,
...customReducers,
});
|
Seanny123/backmap
|
manuscript/python_generators/local_imports/stride/chk_atom.c
|
<gh_stars>1-10
#include "stride.h"
int CheckAtom(char *At)
{
int AtomTypeCnt, AtomTypeNumber = 95;
static char *Atom[MAX_AtomType] = {
"AD1", "AD2", "AE1", "AE2", "C", "CA", "CB", "CD", "CD1", "CD2", "CE", "CE1", "CE2",
"CE3", "CG", "CG1", "CG2", "CH2", "CH3", "CZ", "CZ2", "CZ3", "HG", "HG1", "HH", "HH2",
"HZ", "HZ2", "HZ3", "N", "ND1", "ND2", "NE", "NE1", "NE2", "NH1", "NH2", "NZ", "O",
"OD1", "OD2", "OE", "OE1", "OE2", "OG", "OG1", "OH", "OXT", "SD", "SG", "H", "HA", "HB",
"HD1", "HD2", "HE", "HE1", "HE2", "HE3", "1H", "1HA", "1HB", "1HD", "1HD1", "1HD2",
"1HE", "1HE2", "1HG", "1HG1", "1HG2", "1HH1", "1HH2", "1HZ", "2H", "2HA", "2HB", "2HD",
"2HD1", "2HD2", "2HE", "2HE2", "2HG", "2HG1", "2HG2", "2HH1", "2HH2", "2HZ", "3H", "3HB",
"3HD1", "3HD2", "3HE", "3HG1", "3HG2", "3HZ"
};
for( AtomTypeCnt=0; AtomTypeCnt<AtomTypeNumber; AtomTypeCnt++ )
if( !strcmp(At,Atom[AtomTypeCnt]) )
return(SUCCESS);
return(FAILURE);
}
|
felipeek/bullet3
|
examples/pybullet/gym/pybullet_envs/minitaur/robots/minitaur_motor_model_v2.py
|
# Lint as: python3
"""This file implements an accurate motor model."""
from typing import Tuple
import gin
import numpy as np
from pybullet_envs.minitaur.robots import hybrid_motor_model
from pybullet_envs.minitaur.robots import robot_config
VOLTAGE_CLIPPING = 50
# TODO(b/73728631): Clamp the pwm signal instead of the OBSERVED_TORQUE_LIMIT.
OBSERVED_TORQUE_LIMIT = 5.7
MOTOR_VOLTAGE = 16.0
MOTOR_RESISTANCE = 0.186
MOTOR_TORQUE_CONSTANT = 0.0954
MOTOR_VISCOUS_DAMPING = 0
MOTOR_POS_LB = 0.5
MOTOR_POS_UB = 2.5
@gin.configurable
class MinitaurMotorModel(hybrid_motor_model.HybridMotorModel):
"""The accurate motor model, which is based on the physics of DC motors.
The motor model support two types of control: position control and torque
control. In position control mode, a desired motor angle is specified, and a
torque is computed based on the internal motor model. When the torque control
is specified, a pwm signal in the range of [-1.0, 1.0] is converted to the
torque.
The internal motor model takes the following factors into consideration:
pd gains, viscous friction, back-EMF voltage and current-torque profile.
"""
def __init__(self,
num_motors: int,
voltage_clipping: float = VOLTAGE_CLIPPING,
observed_torque_limit: float = OBSERVED_TORQUE_LIMIT,
motor_voltage: float = MOTOR_VOLTAGE,
motor_resistance: float = MOTOR_RESISTANCE,
motor_torque_constant: float = MOTOR_TORQUE_CONSTANT,
motor_viscous_damping: float = MOTOR_VISCOUS_DAMPING,
motor_pos_lb: float = MOTOR_POS_LB,
motor_pos_ub: float = MOTOR_POS_UB,
**kwargs):
super(MinitaurMotorModel, self).__init__(num_motors, **kwargs)
self._voltage_clipping = voltage_clipping
self._observed_torque_limit = observed_torque_limit
self._voltage = motor_voltage
self._resistance = motor_resistance
self._torque_constant = motor_torque_constant
self._viscous_damping = motor_viscous_damping
self._motor_pos_lb = motor_pos_lb
self._motor_pos_ub = motor_pos_ub
self._current_table = [0, 10, 20, 30, 40, 50, 60]
self._torque_table = [0, 1, 1.9, 2.45, 3.0, 3.25, 3.5]
def set_voltage(self, voltage):
self._voltage = voltage
def get_voltage(self):
return self._voltage
def set_viscous_damping(self, viscous_damping):
self._viscous_damping = viscous_damping
def get_viscous_dampling(self):
return self._viscous_damping
def get_motor_torques(
self,
motor_commands: np.ndarray,
motor_control_mode=None) -> Tuple[np.ndarray, np.ndarray]:
"""Convert the commands (position control or pwm control) to torque.
Args:
motor_commands: The desired motor angle if the motor is in position
control mode. The pwm signal if the motor is in torque control mode.
motor_control_mode: A MotorControlMode enum.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor.
"""
if not motor_control_mode:
motor_control_mode = self._motor_control_mode
if (motor_control_mode is robot_config.MotorControlMode.TORQUE) or (
motor_control_mode is robot_config.MotorControlMode.HYBRID):
raise ValueError(
"{} is not a supported motor control mode".format(motor_control_mode))
motor_angle, motor_velocity = self.get_motor_states()
_, true_motor_velocity = self.get_motor_states(latency=0)
kp = self._kp
kd = self._kd
pwm = -1 * kp * (motor_angle - motor_commands) - kd * motor_velocity
pwm = np.clip(pwm, -1.0, 1.0)
return self._convert_to_torque_from_pwm(pwm, true_motor_velocity)
def _convert_to_torque_from_pwm(self, pwm: np.ndarray,
true_motor_velocity: np.ndarray):
"""Convert the pwm signal to torque.
Args:
pwm: The pulse width modulation.
true_motor_velocity: The true motor velocity at the current moment. It is
used to compute the back EMF voltage and the viscous damping.
Returns:
actual_torque: The torque that needs to be applied to the motor.
observed_torque: The torque observed by the sensor.
"""
observed_torque = np.clip(
self._torque_constant *
(np.asarray(pwm) * self._voltage / self._resistance),
-self._observed_torque_limit, self._observed_torque_limit)
if (self._torque_lower_limits is not None or
self._torque_upper_limits is not None):
observed_torque = np.clip(observed_torque, self._torque_lower_limits,
self._torque_upper_limits)
# Net voltage is clipped at 50V by diodes on the motor controller.
voltage_net = np.clip(
np.asarray(pwm) * self._voltage -
(self._torque_constant + self._viscous_damping) *
np.asarray(true_motor_velocity), -self._voltage_clipping,
self._voltage_clipping)
current = voltage_net / self._resistance
current_sign = np.sign(current)
current_magnitude = np.absolute(current)
# Saturate torque based on empirical current relation.
actual_torque = np.interp(current_magnitude, self._current_table,
self._torque_table)
actual_torque = np.multiply(current_sign, actual_torque)
actual_torque = np.multiply(self._strength_ratios, actual_torque)
if (self._torque_lower_limits is not None or
self._torque_upper_limits is not None):
actual_torque = np.clip(actual_torque, self._torque_lower_limits,
self._torque_upper_limits)
return observed_torque, actual_torque
|
qianyuqiao/dragonflow
|
dragonflow/neutron/common/dhcp_opt_map.py
|
# 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 dragonflow.common.constants as const
from dragonflow.common import dhcp
dnsmasq_opts = {
"netmask": 1,
"router": 3,
"dns-server": 6,
"log-server": 7,
"lpr-server": 9,
"hostname": 12,
"domain-name": 15,
"swap-server": 16,
"root-path": 17,
"extension-path": 18,
"policy-filter": 21,
"broadcast": 28,
"router-solicitation": 32,
"static-route": 33,
"nis-domain": 40,
"nis-server": 41,
"ntp-server": 42,
"vendor-encap": 43,
"netbios-ns": 44,
"netbios-dd": 45,
"x-windows-fs": 48,
"x-windows-dm": 49,
"requested-address": 50,
"lease-time": 51,
"option-overload": 52,
"message-type": 53,
"server-identifier": 54,
"parameter-request": 55,
"message": 56,
"max-message-size": 57,
"T1": 58,
"T2": 59,
"client-id": 61,
"nis+-domain": 64,
"nis+-server": 65,
"tftp-server": 66,
"bootfile-name": 67,
"mobile-ip-home": 68,
"smtp-server": 69,
"pop3-server": 70,
"nntp-server": 71,
"irc-server": 74,
"FQDN": 81,
"agent-id": 82,
"subnet-select": 118,
"domain-search": 119,
"server-ip-address": "siaddr"
}
dhcpd_ops = {
"subnet-mask": 1,
"time-offset": 2,
"routers": 3,
"time-servers": 4,
"ien116-name-servers": 5,
"domain-name-servers": 6,
"log-servers": 7,
"cookie-servers": 8,
"lpr-servers": 9,
"impress-servers": 10,
"resource-location-servers": 11,
"host-name": 12,
"boot-size": 13,
"merit-dump": 14,
"domain-name": 15,
"swap-server": 16,
"root-path": 17,
"extensions-path": 18,
"ip-forwarding": 19,
"non-local-source-routing": 20,
"policy-filter": 21,
"max-dgram-reassembly": 22,
"default-ip-ttl": 23,
"path-mtu-aging-timeout": 24,
"path-mtu-plateau-table": 25,
"interface-mtu": 26,
"all-subnets-local": 27,
"broadcast-address": 28,
"perform-mask-discovery": 29,
"mask-supplier": 30,
"router-discovery": 31,
"router-solicitation-address": 32,
"static-routes": 33,
"trailer-encapsulation": 34,
"arp-cache-timeout": 35,
"ieee802-3-encapsulation": 36,
"default-tcp-ttl": 37,
"tcp-keepalive-interval": 38,
"tcp-keepalive-garbage": 39,
"nis-domain": 40,
"nis-servers": 41,
"ntp-servers": 42,
"vendor-encapsulated-options": 43,
"netbios-name-servers": 44,
"netbios-dd-server": 45,
"netbios-node-type": 46,
"netbios-scope": 47,
"font-servers": 48,
"x-display-manager": 49,
"dhcp-requested-address": 50,
"dhcp-lease-time": 51,
"dhcp-option-overload": 52,
"dhcp-message-type": 53,
"dhcp-server-identifier": 54,
"dhcp-parameter-request-list": 55,
"dhcp-message": 56,
"dhcp-max-message-size": 57,
"dhcp-renewal-time": 58,
"dhcp-rebinding-time": 59,
"vendor-class-identifier": 60,
"dhcp-client-identifier": 61,
"nwip-domain": 62,
"nwip-suboptions": 63,
"nisplus-domain": 64,
"nisplus-servers": 65,
"tftp-server-name": 66,
"bootfile-name": 67,
"mobile-ip-home-agent": 68,
"smtp-server": 69,
"pop-server": 70,
"nntp-server": 71,
"www-server": 72,
"finger-server": 73,
"irc-server": 74,
"streettalk-server": 75,
"user-class": 77,
"slp-directory-agent": 78,
"slp-service-scope": 79,
"fqdn": 81,
"relay-agent-information": 82,
"nds-servers": 85,
"nds-tree-name": 86,
"nds-context": 87,
"bcms-controller-names": 88,
"bcms-controller-address": 89,
"client-last-transaction-time": 91,
"associated-ip": 92,
"pxe-system-type": 93,
"pxe-interface-id": 94,
"pxe-client-id": 97,
"uap-servers": 98,
"geoconf-civic": 99,
"pcode": 100,
"tcode": 101,
"netinfo-server-address": 112,
"netinfo-server-tag": 113,
"default-url": 114,
"auto-config": 116,
"name-service-search": 117,
"subnet-selection": 118,
"domain-search": 119,
"vivco": 124,
"vivso": 125,
"pxe-undefined-1": 128,
"pxe-undefined-2": 129,
"pxe-undefined-3": 130,
"pxe-undefined-4": 131,
"pxe-undefined-5": 132,
"pxe-undefined-6": 133,
"pxe-undefined-7": 134,
"pxe-undefined-8": 135,
"pana-agent": 136,
"v4-lost": 137,
"capwap-ac-v4": 138,
"sip-ua-cs-domains": 141,
"ipv4-address-andsf": 142,
"rdnss-selection": 146,
"tftp-server-address": 150,
"v4-portparams": 159,
"v4-captive-portal": 160,
"pxelinux-magic": 208,
"loader-configfile": 209,
"loader-pathprefix": 210,
"loader-reboottime": 211,
"option-6rd": 212,
"v4-access-domain": 213
}
opt_mapping = {}
opt_mapping.update(dnsmasq_opts)
opt_mapping.update(dhcpd_ops)
def dhcp_app_tag_by_user_tag(usr_tag):
try:
user_tag_int = int(usr_tag)
if dhcp.is_tag_valid(user_tag_int):
return user_tag_int
except ValueError:
pass
if usr_tag == const.DHCP_SIADDR:
return usr_tag
return opt_mapping.get(usr_tag)
|
myoukaku/bksge
|
libs/core/math/include/bksge/core/math/color4.hpp
|
<gh_stars>1-10
/**
* @file color4.hpp
*
* @brief Color4 の定義
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_MATH_COLOR4_HPP
#define BKSGE_CORE_MATH_COLOR4_HPP
#include <bksge/core/math/fwd/color4_fwd.hpp>
#include <bksge/core/math/color.hpp>
#include <bksge/core/math/color3.hpp>
#include <bksge/core/math/detail/vector_base.hpp>
#include <bksge/core/math/detail/swizzle_operator.hpp>
#include <bksge/fnd/type_traits/enable_if.hpp>
#include <bksge/fnd/type_traits/is_constructible.hpp>
#include <bksge/fnd/config.hpp>
namespace bksge
{
namespace math
{
template <typename T>
class Color<T, 4> : public detail::VectorBase<T, 4>
{
private:
using BaseType = detail::VectorBase<T, 4>;
public:
/**
* @brief デフォルトコンストラクタ
*/
BKSGE_CONSTEXPR
Color() BKSGE_NOEXCEPT
: BaseType{}
{}
/**
* @brief 値1つのコンストラクタ
*/
explicit BKSGE_CONSTEXPR
Color(T const& x) BKSGE_NOEXCEPT
: BaseType{x, x, x, x}
{}
/**
* @brief 値4つのコンストラクタ
*/
BKSGE_CONSTEXPR
Color(T const& v1, T const& v2, T const& v3, T const& v4) BKSGE_NOEXCEPT
: BaseType{v1, v2, v3, v4}
{}
/**
* @brief Color3と値1つのコンストラクタ
*/
BKSGE_CONSTEXPR
Color(Color<T, 3> const& v1, T const& v2) BKSGE_NOEXCEPT
: BaseType{v1[0], v1[1], v1[2], v2}
{}
/**
* @brief 変換コンストラクタ
*/
template <
typename U,
typename = bksge::enable_if_t<
bksge::is_constructible<T, U>::value
>
>
BKSGE_CONSTEXPR
Color(Color<U, 4> const& rhs) BKSGE_NOEXCEPT
: BaseType{
static_cast<T>(rhs[0] * detail::color_scale<T>::get() / detail::color_scale<U>::get()),
static_cast<T>(rhs[1] * detail::color_scale<T>::get() / detail::color_scale<U>::get()),
static_cast<T>(rhs[2] * detail::color_scale<T>::get() / detail::color_scale<U>::get()),
static_cast<T>(rhs[3] * detail::color_scale<T>::get() / detail::color_scale<U>::get()),
}
{}
/**
* @brief ゼロ初期化されたColorを作成します
*/
static BKSGE_CONSTEXPR Color
Zero() BKSGE_NOEXCEPT
{
return {};
}
BKSGE_CORE_MATH_NAMED_ACCESS(r, 0);
BKSGE_CORE_MATH_NAMED_ACCESS(g, 1);
BKSGE_CORE_MATH_NAMED_ACCESS(b, 2);
BKSGE_CORE_MATH_NAMED_ACCESS(a, 3);
BKSGE_CORE_MATH_DECLARE_SWIZZLE_OPERATOR((r)(g)(b)(a));
};
} // namespace math
} // namespace bksge
#endif // BKSGE_CORE_MATH_COLOR4_HPP
|
sohobase/xCryptos
|
src/screens/Coins/index.js
|
export default from './Coins';
|
lriki/Lumino
|
lumino/Graphics/src/RHI/Backend/OpenGL/GLUniformBuffer.cpp
|
#include "GLUniformBuffer.hpp"
namespace ln {
namespace detail {
//==============================================================================
// GLUniformBuffer
GLUniformBuffer::GLUniformBuffer()
: m_ubo(0)
, m_size(0)
, m_data(nullptr)
, m_mapped(false) {
}
Result GLUniformBuffer::init(size_t size) {
LN_TRY(RHIResource::initAsUniformBuffer(GraphicsResourceUsage::Dynamic, size));
m_size = size;
// 大きなバッファをずっと持つ可能性があるが、UBO は通常、毎フレームデータの書き込みが行われるため、
// map() のたびに大きなバッファを new するとオーバーヘッドが大きくなる。
m_data = LN_NEW uint8_t[m_size];
GL_CHECK(glGenBuffers(1, &m_ubo));
//GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, info.ubo));
//GL_CHECK(glBufferData(GL_UNIFORM_BUFFER, info.blockSize, nullptr, GL_DYNAMIC_DRAW));
//GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, 0));
map();
unmap();
return ok();
}
void GLUniformBuffer::dispose() {
if (m_ubo) {
GL_CHECK(glDeleteBuffers(1, &m_ubo));
m_ubo = 0;
}
LN_SAFE_DELETE_ARRAY(m_data);
RHIResource::dispose();
}
// モバイル環境で glMapBuffer が使えないことがあるため、glBufferData() で対応する。
void* GLUniformBuffer::map() {
if (LN_REQUIRE(!m_mapped)) return nullptr;
m_mapped = true;
return m_data;
}
void GLUniformBuffer::unmap() {
if (LN_REQUIRE(m_mapped)) return;
GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, m_ubo));
GL_CHECK(glBufferData(GL_UNIFORM_BUFFER, m_size, m_data, GL_STREAM_DRAW));
GL_CHECK(glBindBuffer(GL_UNIFORM_BUFFER, 0));
m_mapped = false;
}
void GLUniformBuffer::flush() {
if (m_mapped) {
unmap();
map();
}
}
} // namespace detail
} // namespace ln
|
ekmixon/concord
|
common/src/main/java/com/walmartlabs/concord/common/ObjectInputStreamWithClassLoader.java
|
package com.walmartlabs.concord.common;
/*-
* *****
* Concord
* -----
* Copyright (C) 2017 - 2020 Walmart 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 java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.lang.reflect.Proxy;
/**
* Almost a carbon copy of <a href="https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/ClassLoaderObjectInputStream.html">ClassLoaderObjectInputStream</a>
* from commons-io.
*/
public class ObjectInputStreamWithClassLoader extends ObjectInputStream {
private final ClassLoader classLoader;
public ObjectInputStreamWithClassLoader(InputStream in, ClassLoader classLoader) throws IOException {
super(in);
this.classLoader = classLoader;
}
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
try {
return Class.forName(desc.getName(), false, classLoader);
} catch (ClassNotFoundException e) {
// delegate to super class loader which can resolve primitives
return super.resolveClass(desc);
}
}
@Override
protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
Class<?>[] interfaceClasses = new Class[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
interfaceClasses[i] = Class.forName(interfaces[i], false, classLoader);
}
try {
return Proxy.getProxyClass(classLoader, interfaceClasses);
} catch (IllegalArgumentException e) {
return super.resolveProxyClass(interfaces);
}
}
}
|
Jacshon/spring-framework-i21
|
src/com/interface21/aop/framework/MethodPointcut.java
|
/*
* The Spring Framework is published under the terms
* of the Apache Software License.
*/
package com.interface21.aop.framework;
import org.aopalliance.intercept.MethodInterceptor;
/**
* Interface to be implemented by objects that can cause
* conditional invocation of an Interceptor depending on
* the method, arguments and attributes passed.
* @author <NAME>
* @since 03-Apr-2003
* @version $Id$
*/
public interface MethodPointcut {
/**
* Return the interceptor to run conditionally
* @return MethodInterceptor
*/
MethodInterceptor getInterceptor();
/**
* Arbitrary int value. Depends on other values.
* Higher values cause interceptors to be invoked earlier
* in the invocation chain.
* @return int
*/
//int getPrecedence();
}
|
clilystudio/NetBook
|
allsrc/android/support/v4/app/ActionBarDrawerToggle$ActionBarDrawerToggleImplJellybeanMR2.java
|
package android.support.v4.app;
import android.app.Activity;
import android.graphics.drawable.Drawable;
class ActionBarDrawerToggle$ActionBarDrawerToggleImplJellybeanMR2
implements ActionBarDrawerToggle.ActionBarDrawerToggleImpl
{
public Drawable getThemeUpIndicator(Activity paramActivity)
{
return ActionBarDrawerToggleJellybeanMR2.getThemeUpIndicator(paramActivity);
}
public Object setActionBarDescription(Object paramObject, Activity paramActivity, int paramInt)
{
return ActionBarDrawerToggleJellybeanMR2.setActionBarDescription(paramObject, paramActivity, paramInt);
}
public Object setActionBarUpIndicator(Object paramObject, Activity paramActivity, Drawable paramDrawable, int paramInt)
{
return ActionBarDrawerToggleJellybeanMR2.setActionBarUpIndicator(paramObject, paramActivity, paramDrawable, paramInt);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v4.app.ActionBarDrawerToggle.ActionBarDrawerToggleImplJellybeanMR2
* JD-Core Version: 0.6.0
*/
|
tudo-aqua/jStateExplorer
|
src/main/java/gov/nasa/jstateexplorer/util/ResultSaver.java
|
<reponame>tudo-aqua/jStateExplorer<filename>src/main/java/gov/nasa/jstateexplorer/util/ResultSaver.java
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 gov.nasa.jstateexplorer.util;
import gov.nasa.jstateexplorer.datastructures.searchImage.SearchIterationImage;
import gov.nasa.jstateexplorer.transitionSystem.TransitionSystem;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
/**
* Saves results to a file.
*/
public class ResultSaver {
public static void writeResultToFolder(SearchIterationImage result,
String folder, String prefix) {
String currentDate
= new SimpleDateFormat("yyyyMMddhhmm'.txt'").format(new Date());
String fileName = folder + prefix + "searchResult-" + currentDate;
try (PrintWriter writer = new PrintWriter(fileName);) {
if (result.getDepth() == Integer.MAX_VALUE) {
writer.println("!!!!The search hit a predefined max search level."
+ " It was interupted!!!!");
} else {
writer.println("!!!!The search terminated reaching a fix point!!!!");
}
result.print(writer);
} catch (IOException ex) {
Logger.getLogger("psyco").severe(ex.getStackTrace().toString());
}
}
public static void writeResultToFolder(SearchIterationImage result,
TransitionSystem transitionSystem, String folder, String prefix) {
String currentDate
= new SimpleDateFormat("yyyyMMddhhmm'.txt'").format(new Date());
String fileName = folder + prefix + "searchResult-" + currentDate;
try (PrintWriter writer = new PrintWriter(fileName);) {
if (result.getDepth() == Integer.MAX_VALUE) {
writer.println("!!!!The search hit a predefined max search level."
+ " It was interupted!!!!");
} else {
writer.println("!!!!The search terminated reaching a fix point!!!!");
}
result.print(writer);
writer.println("\n");
writer.println("The following statistic is provided"
+ "by the transition system:");
writer.println(transitionSystem.getExecutionStatistics());
} catch (IOException ex) {
Logger.getLogger("psyco").severe(ex.getStackTrace().toString());
}
}
}
|
1446554749/jdk_11_src_read
|
jdk11/java.desktop/sun/awt/X11/XAtom.java
|
<gh_stars>100-1000
/*
* Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.X11;
/**
* XAtom is a class that allows you to create and modify X Window properties.
* An X Atom is an identifier for a property that you can set on any X Window.
* Standard X Atom are defined by X11 and these atoms are defined in this class
* for convenience. Common X Atoms like {@code XA_WM_NAME} are used to communicate with the
* Window manager to let it know the Window name. The use and protocol for these
* atoms are defined in the Inter client communications converntions manual.
* User specified XAtoms are defined by specifying a name that gets Interned
* by the XServer and an {@code XAtom} object is returned. An {@code XAtom} can also be created
* by using a pre-exisiting atom like {@code XA_WM_CLASS}. A {@code display} has to be specified
* in order to create an {@code XAtom}. <p> <p>
*
* Once an {@code XAtom} instance is created, you can call get and set property methods to
* set the values for a particular window. <p> <p>
*
*
* Example usage : To set the window name for a top level: <p>
* <pre>{@code
* XAtom xa = new XAtom(display,XAtom.XA_WM_NAME);
* xa.setProperty(window,"Hello World");
* }</pre>
* <p>
* <p>
* To get the cut buffer:
* <pre>{@code
* XAtom xa = new XAtom(display,XAtom.XA_CUT_BUFFER0);
* String selection = xa.getProperty(root_window);
* }</pre>
*
* @author <NAME>
* @since 1.5
*/
import jdk.internal.misc.Unsafe;
import java.util.HashMap;
public final class XAtom {
// Order of lock: XAWTLock -> XAtom.class
/* Predefined Atoms - automatically extracted from XAtom.h */
private static Unsafe unsafe = XlibWrapper.unsafe;
private static XAtom[] emptyList = new XAtom[0];
public static final long XA_PRIMARY=1;
public static final long XA_SECONDARY=2;
public static final long XA_ARC=3;
public static final long XA_ATOM=4;
public static final long XA_BITMAP=5;
public static final long XA_CARDINAL=6;
public static final long XA_COLORMAP=7;
public static final long XA_CURSOR=8;
public static final long XA_CUT_BUFFER0=9;
public static final long XA_CUT_BUFFER1=10;
public static final long XA_CUT_BUFFER2=11;
public static final long XA_CUT_BUFFER3=12;
public static final long XA_CUT_BUFFER4=13;
public static final long XA_CUT_BUFFER5=14;
public static final long XA_CUT_BUFFER6=15;
public static final long XA_CUT_BUFFER7=16;
public static final long XA_DRAWABLE=17;
public static final long XA_FONT=18;
public static final long XA_INTEGER=19;
public static final long XA_PIXMAP=20;
public static final long XA_POINT=21;
public static final long XA_RECTANGLE=22;
public static final long XA_RESOURCE_MANAGER=23;
public static final long XA_RGB_COLOR_MAP=24;
public static final long XA_RGB_BEST_MAP=25;
public static final long XA_RGB_BLUE_MAP=26;
public static final long XA_RGB_DEFAULT_MAP=27;
public static final long XA_RGB_GRAY_MAP=28;
public static final long XA_RGB_GREEN_MAP=29;
public static final long XA_RGB_RED_MAP=30;
public static final long XA_STRING=31;
public static final long XA_VISUALID=32;
public static final long XA_WINDOW=33;
public static final long XA_WM_COMMAND=34;
public static final long XA_WM_HINTS=35;
public static final long XA_WM_CLIENT_MACHINE=36;
public static final long XA_WM_ICON_NAME=37;
public static final long XA_WM_ICON_SIZE=38;
public static final long XA_WM_NAME=39;
public static final long XA_WM_NORMAL_HINTS=40;
public static final long XA_WM_SIZE_HINTS=41;
public static final long XA_WM_ZOOM_HINTS=42;
public static final long XA_MIN_SPACE=43;
public static final long XA_NORM_SPACE=44;
public static final long XA_MAX_SPACE=45;
public static final long XA_END_SPACE=46;
public static final long XA_SUPERSCRIPT_X=47;
public static final long XA_SUPERSCRIPT_Y=48;
public static final long XA_SUBSCRIPT_X=49;
public static final long XA_SUBSCRIPT_Y=50;
public static final long XA_UNDERLINE_POSITION=51;
public static final long XA_UNDERLINE_THICKNESS=52 ;
public static final long XA_STRIKEOUT_ASCENT=53;
public static final long XA_STRIKEOUT_DESCENT=54;
public static final long XA_ITALIC_ANGLE=55;
public static final long XA_X_HEIGHT=56;
public static final long XA_QUAD_WIDTH=57;
public static final long XA_WEIGHT=58;
public static final long XA_POINT_SIZE=59;
public static final long XA_RESOLUTION=60;
public static final long XA_COPYRIGHT=61;
public static final long XA_NOTICE=62;
public static final long XA_FONT_NAME=63;
public static final long XA_FAMILY_NAME=64;
public static final long XA_FULL_NAME=65;
public static final long XA_CAP_HEIGHT=66;
public static final long XA_WM_CLASS=67;
public static final long XA_WM_TRANSIENT_FOR=68;
public static final long XA_LAST_PREDEFINED=68;
static HashMap<Long, XAtom> atomToAtom = new HashMap<Long, XAtom>();
static HashMap<String, XAtom> nameToAtom = new HashMap<String, XAtom>();
static void register(XAtom at) {
if (at == null) {
return;
}
synchronized (XAtom.class) {
if (at.atom != 0) {
atomToAtom.put(Long.valueOf(at.atom), at);
}
if (at.name != null) {
nameToAtom.put(at.name, at);
}
}
}
static XAtom lookup(long atom) {
synchronized (XAtom.class) {
return atomToAtom.get(Long.valueOf(atom));
}
}
static XAtom lookup(String name) {
synchronized (XAtom.class) {
return nameToAtom.get(name);
}
}
/*
* [das]Suggestion:
* 1.Make XAtom immutable.
* 2.Replace public ctors with factory methods (e.g. get() below).
*/
static XAtom get(long atom) {
XAtom xatom = lookup(atom);
if (xatom == null) {
xatom = new XAtom(XToolkit.getDisplay(), atom);
}
return xatom;
}
public static XAtom get(String name) {
XAtom xatom = lookup(name);
if (xatom == null) {
xatom = new XAtom(XToolkit.getDisplay(), name);
}
return xatom;
}
public String getName() {
if (name == null) {
XToolkit.awtLock();
try {
this.name = XlibWrapper.XGetAtomName(display, atom);
} finally {
XToolkit.awtUnlock();
}
register();
}
return name;
}
static String asString(long atom) {
XAtom at = lookup(atom);
if (at == null) {
return Long.toString(atom);
} else {
return at.toString();
}
}
void register() {
register(this);
}
public String toString() {
if (name != null) {
return name + ":" + atom;
} else {
return Long.toString(atom);
}
}
/* interned value of Atom */
long atom = 0;
/* name of atom */
String name;
/* display for X connection */
long display;
/** This constructor will create and intern a new XAtom that is specified
* by the supplied name.
*
* @param display X display to use
* @param name name of the XAtom to create.
* @since 1.5
*/
private XAtom(long display, String name) {
this(display, name, true);
}
public XAtom(String name, boolean autoIntern) {
this(XToolkit.getDisplay(), name, autoIntern);
}
/** This constructor will create an instance of XAtom that is specified
* by the predefined XAtom specified by u {@code latom}
*
* @param display X display to use.
* @param atom a predefined XAtom.
* @since 1.5
*/
public XAtom(long display, long atom) {
this.atom = atom;
this.display = display;
register();
}
/** This constructor will create the instance,
* and if {@code autoIntern} is true intern a new XAtom that is specified
* by the supplied name.
*
* @param display X display to use
* @param name name of the XAtom to create.
* @since 1.5
*/
private XAtom(long display, String name, boolean autoIntern) {
this.name = name;
this.display = display;
if (autoIntern) {
XToolkit.awtLock();
try {
atom = XlibWrapper.InternAtom(display,name,0);
} finally {
XToolkit.awtUnlock();
}
}
register();
}
/**
* Creates uninitialized instance of
*/
public XAtom() {
}
/** Sets the window property for the specified window
* @param window window id to use
* @param str value to set to.
* @since 1.5
*/
public void setProperty(long window, String str) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
XlibWrapper.SetProperty(display,window,atom,str);
} finally {
XToolkit.awtUnlock();
}
}
/**
* Sets UTF8_STRING type property. Explicitly converts str to UTF-8 byte sequence.
*/
public void setPropertyUTF8(long window, String str) {
XAtom XA_UTF8_STRING = XAtom.get("UTF8_STRING"); /* like STRING but encoding is UTF-8 */
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
byte[] bdata = null;
try {
bdata = str.getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException uee) {
uee.printStackTrace();
}
if (bdata != null) {
setAtomData(window, XA_UTF8_STRING.atom, bdata);
}
}
/**
* Sets STRING/8 type property. Explicitly converts str to Latin-1 byte sequence.
*/
public void setProperty8(long window, String str) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
byte[] bdata = null;
try {
bdata = str.getBytes("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
uee.printStackTrace();
}
if (bdata != null) {
setAtomData(window, XA_STRING, bdata);
}
}
/** Gets the window property for the specified window
* @param window window id to use
* @return string with the property.
* @since 1.5
*/
public String getProperty(long window) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
return XlibWrapper.GetProperty(display,window,atom);
} finally {
XToolkit.awtUnlock();
}
}
/*
* Auxiliary function that returns the value of 'property' of type
* 'property_type' on window 'window'. Format of the property must be 32.
*/
public long get32Property(long window, long property_type) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
WindowPropertyGetter getter =
new WindowPropertyGetter(window, this, 0, 1,
false, property_type);
try {
int status = getter.execute();
if (status != XConstants.Success || getter.getData() == 0) {
return 0;
}
if (getter.getActualType() != property_type || getter.getActualFormat() != 32) {
return 0;
}
return Native.getCard32(getter.getData());
} finally {
getter.dispose();
}
}
/**
* Returns value of property of type CARDINAL/32 of this window
*/
public long getCard32Property(XBaseWindow window) {
return get32Property(window.getWindow(), XA_CARDINAL);
}
/**
* Sets property of type CARDINAL on the window
*/
public void setCard32Property(long window, long value) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
Native.putCard32(XlibWrapper.larg1, value);
XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window,
atom, XA_CARDINAL, 32, XConstants.PropModeReplace,
XlibWrapper.larg1, 1);
} finally {
XToolkit.awtUnlock();
}
}
/**
* Sets property of type CARDINAL/32 on the window
*/
public void setCard32Property(XBaseWindow window, long value) {
setCard32Property(window.getWindow(), value);
}
/**
* Gets uninterpreted set of data from property and stores them in data_ptr.
* Property type is the same as current atom, property is current atom.
* Property format is 32. Property 'delete' is false.
* Returns boolean if requested type, format, length match returned values
* and returned data pointer is not null.
*/
public boolean getAtomData(long window, long data_ptr, int length) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
WindowPropertyGetter getter =
new WindowPropertyGetter(window, this, 0, (long)length,
false, this);
try {
int status = getter.execute();
if (status != XConstants.Success || getter.getData() == 0) {
return false;
}
if (getter.getActualType() != atom
|| getter.getActualFormat() != 32
|| getter.getNumberOfItems() != length
)
{
return false;
}
XlibWrapper.memcpy(data_ptr, getter.getData(), length*getAtomSize());
return true;
} finally {
getter.dispose();
}
}
/**
* Gets uninterpreted set of data from property and stores them in data_ptr.
* Property type is {@code type}, property is current atom.
* Property format is 32. Property 'delete' is false.
* Returns boolean if requested type, format, length match returned values
* and returned data pointer is not null.
*/
public boolean getAtomData(long window, long type, long data_ptr, int length) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
WindowPropertyGetter getter =
new WindowPropertyGetter(window, this, 0, (long)length,
false, type);
try {
int status = getter.execute();
if (status != XConstants.Success || getter.getData() == 0) {
return false;
}
if (getter.getActualType() != type
|| getter.getActualFormat() != 32
|| getter.getNumberOfItems() != length
)
{
return false;
}
XlibWrapper.memcpy(data_ptr, getter.getData(), length*getAtomSize());
return true;
} finally {
getter.dispose();
}
}
/**
* Sets uninterpreted set of data into property from data_ptr.
* Property type is the same as current atom, property is current atom.
* Property format is 32. Mode is PropModeReplace. length is a number
* of items pointer by data_ptr.
*/
public void setAtomData(long window, long data_ptr, int length) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window,
atom, atom, 32, XConstants.PropModeReplace,
data_ptr, length);
} finally {
XToolkit.awtUnlock();
}
}
/**
* Sets uninterpreted set of data into property from data_ptr.
* Property type is {@code type}, property is current atom.
* Property format is 32. Mode is PropModeReplace. length is a number
* of items pointer by data_ptr.
*/
public void setAtomData(long window, long type, long data_ptr, int length) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window,
atom, type, 32, XConstants.PropModeReplace,
data_ptr, length);
} finally {
XToolkit.awtUnlock();
}
}
/**
* Sets uninterpreted set of data into property from data_ptr.
* Property type is {@code type}, property is current atom.
* Property format is 8. Mode is PropModeReplace. length is a number
* of bytes pointer by data_ptr.
*/
public void setAtomData8(long window, long type, long data_ptr, int length) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window,
atom, type, 8, XConstants.PropModeReplace,
data_ptr, length);
} finally {
XToolkit.awtUnlock();
}
}
/**
* Deletes property specified by this item on the window.
*/
public void DeleteProperty(long window) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
XlibWrapper.XDeleteProperty(XToolkit.getDisplay(), window, atom);
} finally {
XToolkit.awtUnlock();
}
}
/**
* Deletes property specified by this item on the window.
*/
public void DeleteProperty(XBaseWindow window) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window.getWindow());
XToolkit.awtLock();
try {
XlibWrapper.XDeleteProperty(XToolkit.getDisplay(),
window.getWindow(), atom);
} finally {
XToolkit.awtUnlock();
}
}
public void setAtomData(long window, long property_type, byte[] data) {
long bdata = Native.toData(data);
try {
setAtomData8(window, property_type, bdata, data.length);
} finally {
unsafe.freeMemory(bdata);
}
}
/*
* Auxiliary function that returns the value of 'property' of type
* 'property_type' on window 'window'. Format of the property must be 8.
*/
public byte[] getByteArrayProperty(long window, long property_type) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
WindowPropertyGetter getter =
new WindowPropertyGetter(window, this, 0, 0xFFFF,
false, property_type);
try {
int status = getter.execute();
if (status != XConstants.Success || getter.getData() == 0) {
return null;
}
if (getter.getActualType() != property_type || getter.getActualFormat() != 8) {
return null;
}
byte[] res = XlibWrapper.getStringBytes(getter.getData());
return res;
} finally {
getter.dispose();
}
}
/**
* Interns the XAtom
*/
public void intern(boolean onlyIfExists) {
XToolkit.awtLock();
try {
atom = XlibWrapper.InternAtom(display,name, onlyIfExists?1:0);
} finally {
XToolkit.awtUnlock();
}
register();
}
public boolean isInterned() {
if (atom == 0) {
XToolkit.awtLock();
try {
atom = XlibWrapper.InternAtom(display, name, 1);
} finally {
XToolkit.awtUnlock();
}
if (atom == 0) {
return false;
} else {
register();
return true;
}
} else {
return true;
}
}
public void setValues(long display, String name, long atom) {
this.display = display;
this.atom = atom;
this.name = name;
register();
}
static int getAtomSize() {
return Native.getLongSize();
}
/*
* Returns the value of property ATOM[]/32 as array of XAtom objects
* @return array of atoms, array of length 0 if the atom list is empty
* or has different format
*/
XAtom[] getAtomListProperty(long window) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
WindowPropertyGetter getter =
new WindowPropertyGetter(window, this, 0, 0xFFFF,
false, XA_ATOM);
try {
int status = getter.execute();
if (status != XConstants.Success || getter.getData() == 0) {
return emptyList;
}
if (getter.getActualType() != XA_ATOM || getter.getActualFormat() != 32) {
return emptyList;
}
int count = getter.getNumberOfItems();
if (count == 0) {
return emptyList;
}
long list_atoms = getter.getData();
XAtom[] res = new XAtom[count];
for (int index = 0; index < count; index++) {
res[index] = XAtom.get(XAtom.getAtom(list_atoms+index*getAtomSize()));
}
return res;
} finally {
getter.dispose();
}
}
/*
* Returns the value of property of type ATOM[]/32 as XAtomList
* @return list of atoms, empty list if the atom list is empty
* or has different format
*/
XAtomList getAtomListPropertyList(long window) {
return new XAtomList(getAtomListProperty(window));
}
XAtomList getAtomListPropertyList(XBaseWindow window) {
return getAtomListPropertyList(window.getWindow());
}
XAtom[] getAtomListProperty(XBaseWindow window) {
return getAtomListProperty(window.getWindow());
}
/**
* Sets property value of type ATOM list to the list of atoms.
*/
void setAtomListProperty(long window, XAtom[] atoms) {
long data = toData(atoms);
setAtomData(window, XAtom.XA_ATOM, data, atoms.length);
unsafe.freeMemory(data);
}
/**
* Sets property value of type ATOM list to the list of atoms specified by XAtomList
*/
void setAtomListProperty(long window, XAtomList atoms) {
long data = atoms.getAtomsData();
setAtomData(window, XAtom.XA_ATOM, data, atoms.size());
unsafe.freeMemory(data);
}
/**
* Sets property value of type ATOM list to the list of atoms.
*/
public void setAtomListProperty(XBaseWindow window, XAtom[] atoms) {
setAtomListProperty(window.getWindow(), atoms);
}
/**
* Sets property value of type ATOM list to the list of atoms specified by XAtomList
*/
public void setAtomListProperty(XBaseWindow window, XAtomList atoms) {
setAtomListProperty(window.getWindow(), atoms);
}
long getAtom() {
return atom;
}
void putAtom(long ptr) {
Native.putLong(ptr, atom);
}
static long getAtom(long ptr) {
return Native.getLong(ptr);
}
/**
* Allocated memory to hold the list of native atom data and returns unsafe pointer to it
* Caller should free the memory by himself.
*/
static long toData(XAtom[] atoms) {
long data = unsafe.allocateMemory(getAtomSize() * atoms.length);
for (int i = 0; i < atoms.length; i++ ) {
if (atoms[i] != null) {
atoms[i].putAtom(data + i * getAtomSize());
}
}
return data;
}
void checkWindow(long window) {
if (window == 0) {
throw new IllegalArgumentException("Window must not be zero");
}
}
public boolean equals(Object o) {
if (!(o instanceof XAtom)) {
return false;
}
XAtom ot = (XAtom)o;
return (atom == ot.atom && display == ot.display);
}
public int hashCode() {
return (int)((atom ^ display)& 0xFFFFL);
}
/**
* Sets property on the {@code window} to the value {@code window_value}
* Property is assumed to be of type WINDOW/32
*/
public void setWindowProperty(long window, long window_value) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
XToolkit.awtLock();
try {
Native.putWindow(XlibWrapper.larg1, window_value);
XlibWrapper.XChangeProperty(XToolkit.getDisplay(), window,
atom, XA_WINDOW, 32, XConstants.PropModeReplace,
XlibWrapper.larg1, 1);
} finally {
XToolkit.awtUnlock();
}
}
public void setWindowProperty(XBaseWindow window, XBaseWindow window_value) {
setWindowProperty(window.getWindow(), window_value.getWindow());
}
/**
* Gets property on the {@code window}. Property is assumed to be
* of type WINDOW/32.
*/
public long getWindowProperty(long window) {
if (atom == 0) {
throw new IllegalStateException("Atom should be initialized");
}
checkWindow(window);
WindowPropertyGetter getter =
new WindowPropertyGetter(window, this, 0, 1,
false, XA_WINDOW);
try {
int status = getter.execute();
if (status != XConstants.Success || getter.getData() == 0) {
return 0;
}
if (getter.getActualType() != XA_WINDOW || getter.getActualFormat() != 32) {
return 0;
}
return Native.getWindow(getter.getData());
} finally {
getter.dispose();
}
}
}
|
HewlettPackard/SimpliVity-Citrix-VCenter-Plugin
|
HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/VmFaultToleranceConfigIssueReasonForIssue.java
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.06.12 at 09:16:35 AM EDT
//
package com.vmware.vim25;
/**
*
*/
public enum VmFaultToleranceConfigIssueReasonForIssue {
haNotEnabled,
moreThanOneSecondary,
recordReplayNotSupported,
replayNotSupported,
templateVm,
multipleVCPU,
hostInactive,
ftUnsupportedHardware,
ftUnsupportedProduct,
missingVMotionNic,
missingFTLoggingNic,
thinDisk,
verifySSLCertificateFlagNotSet,
hasSnapshots,
noConfig,
ftSecondaryVm,
hasLocalDisk,
esxAgentVm,
video3dEnabled,
hasUnsupportedDisk,
insufficientBandwidth,
hasNestedHVConfiguration,
hasVFlashConfiguration,
unsupportedProduct,
cpuHvUnsupported,
cpuHwmmuUnsupported,
cpuHvDisabled,
hasEFIFirmware,
tooManyVCPUs,
tooMuchMemory;
}
|
zoozooll/MyExercise
|
Market/src/com/mogoo/components/ad/AdOnClickListener.java
|
<filename>Market/src/com/mogoo/components/ad/AdOnClickListener.java
package com.mogoo.components.ad;
/**
* 监听点击展示位的事件接口
*
* @author Administrator
*
*/
public interface AdOnClickListener
{
/**
* 点击展示位时触发
*
* @param item
*/
void OnClick(AdvertiseItem item);
}
|
zlypher/advent-of-code
|
2020/day13/index.js
|
<filename>2020/day13/index.js
// Day 13: Shuttle Search
const fs = require("fs");
const prepareInput = () => fs.readFileSync("./input.txt")
.toString()
.split("\r\n");
function solvePartOne(input) {
const [fst, snd] = input;
const earliest = parseInt(fst, 10);
const timestamps = snd.split(",")
.filter(ts => ts !== "x")
.map(ts => parseInt(ts, 10));
const [id, time] = timestamps.reduce((prev, curr) => {
const [_, prevWait] = prev;
const timeToWait = curr - (earliest % curr);
if (timeToWait < prevWait) {
return [curr, timeToWait];
}
return prev;
}, [0, Number.MAX_VALUE]);
return id * time;
}
const input = prepareInput();
console.log(solvePartOne(input));
|
iOSDevLog/iOSDevLog
|
68. Pods/Pods/OBJMasterViewController.h
|
<filename>68. Pods/Pods/OBJMasterViewController.h
//
// OBJMasterViewController.h
// Pods
//
// Created by <NAME> on 02.03.14.
// Copyright (c) 2014 objc.io. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface OBJMasterViewController : UITableViewController <NSFetchedResultsControllerDelegate>
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@end
|
Apereo-Learning-Analytics-Initiative/Larissa
|
src/main/java/nl/uva/larissa/json/model/About.java
|
package nl.uva.larissa.json.model;
import java.util.List;
import java.util.Map;
import org.apache.abdera.i18n.iri.IRI;
public class About {
List<String> version;
private Map<IRI, Object> extensions;
public List<String> getVersion() {
return version;
}
public void setVersion(List<String> version) {
this.version = version;
}
public Map<IRI, Object> getExtensions() {
return extensions;
}
public void setExtensions(Map<IRI, Object> extensions) {
this.extensions = extensions;
}
}
|
atsushi-m-ito/nowtype
|
src/nt.dom_finder.js
|
<gh_stars>1-10
"use strict";
function FindNextEffectiveNode(focus_node, focus_offset, upper_limit_node) {
let target_node;
if (focus_node.nodeType === Node.TEXT_NODE) {
if (focus_offset < focus_node.length) {
return focus_node;
}
target_node = focus_node;
} else {
if (focus_offset < focus_node.childNodes.length) {
return focus_node.childNodes[focus_offset];
} else {
target_node = focus_node;
}
}
//target_node = target_node.parentNode;
while (target_node.nextSibling === null) {
target_node = target_node.parentNode;
if (target_node === upper_limit_node) {
return null; //no TEXT_NODE found//
}
}
target_node = target_node.nextSibling;
return target_node;//no TEXT_NODE found//
}
function FindNextTextNode(focus_node, focus_offset, upper_limit_node) {
/*
var target_node;
var is_end_of_children = false;
if (focus_node.nodeType === Node.TEXT_NODE) {
if (focus_offset < focus_node.length) {
return focus_node;
}
is_end_of_children = true;
target_node = focus_node;
} else {
if (focus_offset < focus_node.childNodes.length) {
target_node = focus_node.childNodes[focus_offset];
} else {
is_end_of_children = true;
target_node = focus_node;
}
}
if (is_end_of_children) {
if (target_node.nextSibling) {
target_node = target_node.nextSibling;
} else {
//target_node = target_node.parentNode;
while (target_node.nextSibling === null) {
target_node = target_node.parentNode;
if (target_node === upper_limit_node) {
return null; //no TEXT_NODE found//
}
}
target_node = target_node.nextSibling;
}
}
*/
let target_node = FindNextEffectiveNode(focus_node, focus_offset, upper_limit_node);
while (target_node) {
if (target_node.nodeType === Node.TEXT_NODE) {
return target_node;
} else if (target_node.firstChild) {
target_node = target_node.firstChild;
} else if (target_node.nextSibling) {
target_node = target_node.nextSibling;
} else {
//target_node = target_node.parentNode;
while (target_node.nextSibling === null) {
target_node = target_node.parentNode;
if (target_node === upper_limit_node) {
return null; //no TEXT_NODE found//
}
}
target_node = target_node.nextSibling;
}
}
alert("FindNextTextNode is invalid.");
return null;//no TEXT_NODE found//
}
function FindPreviousEffectiveNode(focus_node, focus_offset, upper_limit_node) {
let target_node;
if (focus_node.nodeType === Node.TEXT_NODE) {
if (0 < focus_offset) {
return focus_node;
}
target_node = focus_node;
} else {
if (0 < focus_offset) {
return focus_node.childNodes[focus_offset - 1];
} else {
target_node = focus_node;
}
}
while (target_node.previousSibling === null) {
target_node = target_node.parentNode;
if (target_node === upper_limit_node) {
return null; //no TEXT_NODE found//
}
}
target_node = target_node.previousSibling;
return target_node;
}
function FindPreviousTextNode(focus_node, focus_offset, upper_limit_node) {
/*
var target_node;
var is_begin_of_children = false;
if (focus_node.nodeType === Node.TEXT_NODE) {
if (0 < focus_offset) {
return focus_node;
}
is_begin_of_children = true;
target_node = focus_node;
} else {
if (0 < focus_offset) {
target_node = focus_node.childNodes[focus_offset - 1];
} else {
is_begin_of_children = true;
target_node = focus_node;
}
}
if (is_begin_of_children) {
if (target_node.previousSibling) {
target_node = target_node.previousSibling;
} else {
//target_node = target_node.parentNode;
while (target_node.previousSibling === null) {
target_node = target_node.parentNode;
if (target_node === upper_limit_node) {
return null; //no TEXT_NODE found//
}
}
target_node = target_node.previousSibling;
}
}
*/
let target_node = FindPreviousEffectiveNode(focus_node, focus_offset, upper_limit_node);
while (target_node) {
if (target_node.nodeType === Node.TEXT_NODE) {
return target_node;
} else if (target_node.lastChild) {
target_node = target_node.lastChild;
} else if (target_node.previousSibling) {
target_node = target_node.previousSibling;
} else {
//target_node = target_node.parentNode;
while (target_node.previousSibling === null) {
target_node = target_node.parentNode;
if (target_node === upper_limit_node) {
return null; //no TEXT_NODE found//
}
}
target_node = target_node.previousSibling;
}
}
alert("FindPrvoiusTextNode is invalid.");
return null;//no TEXT_NODE found//
}
function GetFirstTextNode(target) {
while (target) {
if (target.nodeType === Node.TEXT_NODE) {
return target;
}
target = target.firstChild;
}
return null;
}
function FindLastestNode(target) {
while (target.hasChildNodes()) {
target = target.lastChild;
}
return target;
}
|
ut-issl/c2a-core
|
System/AnomalyLogger/anomaly_logger.c
|
#pragma section REPRO
#include "anomaly_logger.h"
#ifdef AL_ENABLE
#include <src_user/Settings/System/anomaly_logger_settings.h>
#include <string.h> // memset
#include "../TimeManager/time_manager.h"
#include "../../Library/endian_memcpy.h"
static void AL_clear_records_(void);
static int AC_is_equal_(const AL_AnomalyCode* lhs,
const AL_AnomalyCode* rhs);
static void AL_init_logging_ena_flag_(void);
static int AL_is_logging_enable_(uint32_t group);
static int AL_enable_logging_(uint32_t group);
static int AL_disable_logging_(uint32_t group);
static AnomalyLogger anomaly_logger_;
const AnomalyLogger* const anomaly_logger = &anomaly_logger_;
const AL_AnomalyRecord* AL_get_record(size_t pos)
{
// 指定範囲エラーの場合はNULLを返す
if (pos >= anomaly_logger_.header) return NULL;
return &(anomaly_logger_.records[pos]);
}
const AL_AnomalyRecord* AL_get_latest_record(void)
{
// 登録アノマリーがない場合は先頭要素を返す。
// この場合の先頭要素はAL_initialize()によってゼロクリア済み。
if (anomaly_logger_.header == 0) return &(anomaly_logger_.records[0]);
return &(anomaly_logger_.records[anomaly_logger_.header - 1]);
}
void AL_initialize(void)
{
AL_clear();
AL_init_logging_ena_flag_();
anomaly_logger_.threshold_of_nearly_full = AL_RECORD_MAX - 10; // 仮の値 2019/02/06
AL_load_default_settings();
}
CCP_EXEC_STS Cmd_AL_ADD_ANOMALY(const CommonCmdPacket* packet)
{
const uint8_t* param = CCP_get_param_head(packet);
uint32_t group, local;
int ret;
// パラメータを抽出
endian_memcpy(&group, param, 4);
endian_memcpy(&local, param + 4, 4);
// パラメータを登録
ret = AL_add_anomaly(group, local);
if (ret == AL_ADD_SUCCESS)
{
return CCP_EXEC_SUCCESS;
}
else
{
return CCP_EXEC_UNKNOWN;
}
}
int AL_add_anomaly(uint32_t group, uint32_t local)
{
const AL_AnomalyRecord* prev_anomaly_record = AL_get_latest_record();
AL_AnomalyRecord new_anomaly_record;
int ret;
ret = AL_is_logging_enable_(group);
if (ret == -1) return AL_ADD_ERR_INVALID;
if (ret == 0) return AL_ADD_DISABLE_LOGGING;
new_anomaly_record.time = TMGR_get_master_clock();
new_anomaly_record.code.group = group;
new_anomaly_record.code.local = local;
new_anomaly_record.run_length = 1;
// 登録数上限の場合はその事実を記録する
if (anomaly_logger_.header == AL_RECORD_MAX - 1)
{
new_anomaly_record.code.group = AL_CORE_GROUP_ANOMALY_LOGGER;
new_anomaly_record.code.local = AL_FULL;
}
// 同じAL_AnomalyCodeの登録は圧縮する
if (AC_is_equal_(&(new_anomaly_record.code), &(prev_anomaly_record->code)))
{
// 時刻と連長を更新し再登録
new_anomaly_record.run_length += prev_anomaly_record->run_length;
anomaly_logger_.records[anomaly_logger_.header - 1] = new_anomaly_record;
}
else
{
// 新規登録
anomaly_logger_.records[anomaly_logger_.header] = new_anomaly_record;
// 登録数が上限でないなら先頭位置をインクリメント
if (anomaly_logger_.header != AL_RECORD_MAX - 1)
{
++anomaly_logger_.header;
}
}
++anomaly_logger_.counter;
if (anomaly_logger_.header == anomaly_logger_.threshold_of_nearly_full)
{
AL_add_anomaly(AL_CORE_GROUP_ANOMALY_LOGGER, AL_NEARLY_FULL);
}
return AL_ADD_SUCCESS;
}
CCP_EXEC_STS Cmd_AL_CLEAR_LIST(const CommonCmdPacket* packet)
{
(void)packet;
AL_clear();
return CCP_EXEC_SUCCESS;
}
// こいつは,AHからも呼ばれるので注意!
void AL_clear(void)
{
anomaly_logger_.counter = 0;
anomaly_logger_.header = 0;
AL_clear_records_();
anomaly_logger_.page_no = 0;
}
static void AL_clear_records_(void)
{
int i;
AL_AnomalyRecord ar = {{0, 0, 0}, {0, 0}, 0};
for (i = 0; i < AL_RECORD_MAX; ++i)
{
anomaly_logger_.records[i] = ar;
}
}
static int AC_is_equal_(const AL_AnomalyCode* lhs,
const AL_AnomalyCode* rhs)
{
return ((lhs->group == rhs->group) && (lhs->local == rhs->local));
}
CCP_EXEC_STS Cmd_AL_SET_PAGE_FOR_TLM(const CommonCmdPacket* packet)
{
uint8_t page;
page = CCP_get_param_head(packet)[0];
if (page >= AL_TLM_PAGE_MAX)
{
// ページ番号がコマンドテーブル範囲外
return CCP_EXEC_ILLEGAL_PARAMETER;
}
anomaly_logger_.page_no = page;
return CCP_EXEC_SUCCESS;
}
// 2019-01-18
// 追加
CCP_EXEC_STS Cmd_AL_INIT_LOGGING_ENA_FLAG(const CommonCmdPacket* packet)
{
(void)packet;
AL_init_logging_ena_flag_();
return CCP_EXEC_SUCCESS;
}
static void AL_init_logging_ena_flag_(void)
{
int i;
// デフォルトでは全GROUP IDでロギングが有効
for (i = 0; i < (AL_GROUP_MAX / 8); ++i)
{
anomaly_logger_.is_logging_enable[i] = 0xff;
}
}
CCP_EXEC_STS Cmd_AL_ENABLE_LOGGING(const CommonCmdPacket* packet)
{
const uint8_t* param = CCP_get_param_head(packet);
uint32_t group;
int ret;
// パラメータを抽出
endian_memcpy(&group, param, 4);
if ( !(0 <= group && group < AL_GROUP_MAX) )
{
return CCP_EXEC_ILLEGAL_PARAMETER;
}
ret = AL_enable_logging_(group);
if (ret == 0)
{
return CCP_EXEC_SUCCESS;
}
else
{
return CCP_EXEC_UNKNOWN;
}
}
CCP_EXEC_STS Cmd_AL_DISABLE_LOGGING(const CommonCmdPacket* packet)
{
const uint8_t* param = CCP_get_param_head(packet);
uint32_t group;
int ret;
// パラメータを抽出
endian_memcpy(&group, param, 4);
if ( !(0 <= group && group < AL_GROUP_MAX) )
{
return CCP_EXEC_ILLEGAL_PARAMETER;
}
ret = AL_disable_logging_(group);
if (ret == 0)
{
return CCP_EXEC_SUCCESS;
}
else
{
return CCP_EXEC_UNKNOWN;
}
}
// 有効なら1
// 無効なら0
// エラーは-1
static int AL_is_logging_enable_(uint32_t group)
{
uint32_t group_idx = group / 8;
uint32_t group_subidx = 7 - group % 8; // 反転
uint8_t info;
uint8_t mask;
uint8_t ret;
if ( !(0 <= group && group < AL_GROUP_MAX) )
{
return -1;
}
info = anomaly_logger_.is_logging_enable[group_idx];
mask = (uint8_t)(0x01 << group_subidx);
ret = (uint8_t)(info & mask);
if (ret == 0) return 0;
return 1;
}
static int AL_enable_logging_(uint32_t group)
{
uint32_t group_idx = group / 8;
uint32_t group_subidx = 7 - group % 8; // 反転
uint8_t info;
uint8_t mask;
if ( !(0 <= group && group < AL_GROUP_MAX) )
{
return -1;
}
info = anomaly_logger_.is_logging_enable[group_idx];
mask = (uint8_t)(0x01 << group_subidx);
info = (uint8_t)(info | mask);
anomaly_logger_.is_logging_enable[group_idx] = info;
return 0;
}
static int AL_disable_logging_(uint32_t group)
{
uint32_t group_idx = group / 8;
uint32_t group_subidx = 7 - group % 8; // 反転
uint8_t info;
uint8_t mask;
if ( !(0 <= group && group < AL_GROUP_MAX) )
{
return -1;
}
info = anomaly_logger_.is_logging_enable[group_idx];
mask = (uint8_t)(0x01 << group_subidx);
mask = (uint8_t)(~mask); // ビット反転
info = (uint8_t)(info & mask);
anomaly_logger_.is_logging_enable[group_idx] = info;
return 0;
}
CCP_EXEC_STS Cmd_AL_SET_THRES_OF_NEARLY_FULL(const CommonCmdPacket* packet)
{
const uint8_t* param = CCP_get_param_head(packet);
uint16_t thres;
// パラメータを抽出
endian_memcpy(&thres, param, 2);
anomaly_logger_.threshold_of_nearly_full = thres;
return CCP_EXEC_SUCCESS;
}
// 2019/04/26 公開した
int AL_enable_logging(uint32_t group)
{
return AL_enable_logging_(group);
}
int AL_disable_logging(uint32_t group)
{
return AL_disable_logging_(group);
}
int AL_is_logging_enable(uint32_t group)
{
return AL_is_logging_enable_(group);
}
#endif
#pragma section
|
nehasuman24/TestT24Automation
|
T24Automation/src/test/java/com/scb/t24/glue/ForexForwardDealStepDefinitionFile.java
|
/**
*
*/
package com.scb.t24.glue;
import com.scb.t24.pages.AuthoriseConfirmForexDealsPage;
import com.scb.t24.pages.CaptureForwardDealsDetailPage;
import com.scb.t24.pages.ChooseForexForwardDealPage;
import com.scb.t24.pages.HomePage_Threasurey;
import com.scb.t24.pages.LoginPage;
import com.scb.t24.pages.TransactionsSearchPage;
import com.scb.t24.runner.ReadTestData;
import cucumber.api.java.en.Then;
/**
* @author dineshkumar.rc
*
*/
public class ForexForwardDealStepDefinitionFile extends ReadTestData {/*
@Then("^Navigate to Capture Forex Forward Deal$")
public void navigate_to_Capture_Forex_Forward_Deal() throws Throwable {
new HomePage_Threasurey().navigaToForexForwardDeal().navigateToCaptureForexForwardDeal();
}
@Then("^Enter Mandatory fields in Forex Forward deal ([0-9]*)$")
public void enter_Mandatory_fields_in_Forex_Spot_deal(int iteration) throws Throwable {
new ChooseForexForwardDealPage().selectInterBankOption().enterMandatoryFields(
tdForexForwardDeal.get(0).get(iteration), tdForexForwardDeal.get(1).get(iteration),
tdForexForwardDeal.get(2).get(iteration), tdForexForwardDeal.get(3).get(iteration),
tdForexForwardDeal.get(4).get(iteration), tdForexForwardDeal.get(5).get(iteration),
tdForexForwardDeal.get(6).get(iteration), tdForexForwardDeal.get(7).get(iteration));
}
@Then("^Commit the Deal and get the transaction id$")
public void commit_the_Deal_and_get_the_transaction_id() throws Throwable {
new CaptureForwardDealsDetailPage().CommitForexForwardDeal().getTransactionId();
closeAllBrowser();
}
@Then("^Navigate to Authorise/Confirm Forex deals ([0-9]*)$")
public void navigate_to_Authorise_Confirm_Forex_deals(int iteration) throws Throwable {
launchChromeBrowser();
loadURL("https://192.168.127.12/t24trngR14/");
new LoginPage().loginToApplicationWithSecondUser(tdLogin.get(0).get(iteration), tdLogin.get(1).get(iteration))
.navigateToAuthoriseConfirmForexDeals();
}
@Then("^Search the deal and authorise$")
public void search_the_deal_and_authorise() throws Throwable {
new AuthoriseConfirmForexDealsPage().clickSearchButton();
new TransactionsSearchPage().searchTransactionId();
new AuthoriseConfirmForexDealsPage().clickAuthorizeButton().clickAuthorizeADealButton();
}*/
}
|
packedapp/packedtmp
|
modules/packed/src/main/java/packed/internal/component/ComponentSetup.java
|
/*
* Copyright (c) 2008 <NAME>.
*
* 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 packed.internal.component;
import static java.util.Objects.requireNonNull;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;
import app.packed.application.ApplicationMirror;
import app.packed.attribute.Attribute;
import app.packed.attribute.AttributeMap;
import app.packed.base.NamespacePath;
import app.packed.base.Nullable;
import app.packed.bundle.BundleMirror;
import app.packed.component.ComponentMirror;
import app.packed.component.ComponentMirrorStream;
import app.packed.component.ComponentScope;
import app.packed.component.Realm;
import app.packed.extension.Extension;
import packed.internal.application.ApplicationSetup;
import packed.internal.attribute.DefaultAttributeMap;
import packed.internal.bundle.BundleSetup;
import packed.internal.component.bean.BeanSetup;
import packed.internal.lifetime.LifetimeSetup;
import packed.internal.util.CollectionUtil;
/** Abstract build-time setup of a component. */
public abstract sealed class ComponentSetup permits BundleSetup,BeanSetup {
/** The application this component is a part of. */
public final ApplicationSetup application;
/** Children of this node (lazily initialized) in insertion order. */
@Nullable
LinkedHashMap<String, ComponentSetup> children;
/** The container this component is a part of. A container is a part of it self. */
public final BundleSetup container;
/** The depth of the component in the tree. */
protected final int depth;
/** The lifetime of this component. */
public final LifetimeSetup lifetime;
/** The name of this component. */
public String name;
/** An action that, if present, must be called whenever the component has been completely wired. */
@Nullable
public Consumer<? super ComponentMirror> onWire;
/** The parent of this component, or null for a root component. */
@Nullable
protected final ComponentSetup parent;
/** The realm this component is a part of. */
public final RealmSetup realm;
/**
* Create a new component. This constructor is only invoked from subclasses of this class
*
* @param application
* the application the component is a part of
* @param realm
* the realm this component is part of
* @param lifetime
* the lifetime this component is part of
* @param parent
* any parent component this component might have
*/
protected ComponentSetup(ApplicationSetup application, RealmSetup realm, LifetimeSetup lifetime, @Nullable ComponentSetup parent) {
this.parent = parent;
if (parent == null) {
this.depth = 0;
} else {
this.depth = parent.depth + 1;
this.onWire = parent.onWire;
}
this.realm = requireNonNull(realm);
this.lifetime = requireNonNull(lifetime);
this.application = requireNonNull(application);
this.container = this instanceof BundleSetup container ? container : parent.container;
}
final AttributeMap attributes() {
// Det er ikke super vigtigt at den her er hurtig paa configurations tidspunktet...
// Maaske er det simpelthen et view...
// Hvor vi lazily fx calculere EntrySet (og gemmer i et felt)
DefaultAttributeMap dam = new DefaultAttributeMap();
attributesAdd(dam);
return dam;
}
protected void attributesAdd(DefaultAttributeMap dam) {}
public final void checkIsWiring() {
if (realm.current() != this) {
String errorMsg;
if (realm.root == this) {
errorMsg = "This operation must be called as the first thing in Assembly#build()";
} else {
errorMsg = "This operation must be called immediately after the component has been wired";
}
throw new IllegalStateException(errorMsg);
}
}
//
public final String getName() {
// Dette kunne ogsaa wire componenten?
return name;
}
protected final void initializeNameWithPrefix(String name) {
String n = name;
if (parent != null) {
LinkedHashMap<String, ComponentSetup> c = parent.children;
if (c == null) {
c = parent.children = new LinkedHashMap<>();
c.put(name, this);
} else {
int counter = 1;
while (c.putIfAbsent(n, this) != null) {
n = name + counter++; // maybe store some kind of map<ComponentSetup, LongCounter> in BuildSetup.. for those that want to test adding 1
// million of the same component type
}
}
}
this.name = n;
}
/**
* Tests that this component is in the same specified scope as another component.
*
* @param scope
* the scope to test
* @param other
* the other component to test
* @return true if in the same scope, otherwise false
*/
public final boolean isInSame(ComponentScope scope, ComponentSetup other) {
requireNonNull(scope, "scope is null");
requireNonNull(other, "other is null");
return switch (scope) {
case CONTAINER -> application == other.application;
case APPLICATION -> application.build == other.application.build;
case COMPONENT -> this == other;
case BUNDLE -> container == other.container;
case NAMESPACE -> application.build.namespace == other.application.build.namespace;
};
}
/** {@inheritDoc} */
public abstract ComponentMirror mirror();
/** {@inheritDoc} */
public final void named(String name) {
checkComponentName(name); // Check if the name is valid
checkIsWiring();
// If a name has been set using a wirelet it cannot be overridden
if (this instanceof BundleSetup cs && cs.nameInitializedWithWirelet) {
return;
} else if (name.equals(this.name)) {
return;
}
// maybe assume s==0
if (parent != null) {
parent.children.remove(this.name);
if (parent.children.putIfAbsent(name, this) != null) {
throw new IllegalArgumentException("A component with the specified name '" + name + "' already exists");
}
}
this.name = name;
}
final void onWired() {
if (onWire != null) {
onWire.accept(mirror());
}
}
/** {@return the path of this component} */
public final NamespacePath path() {
return PackedTreePath.of(this);
}
public final <T> void setRuntimeAttribute(Attribute<T> attribute, T value) {
requireNonNull(attribute, "attribute is null");
requireNonNull(value, "value is null");
// check realm.open + attribute.write
}
/**
* Checks the name of the component.
*
* @param name
* the name to check
* @return the name if valid
*/
public static String checkComponentName(String name) {
requireNonNull(name, "name is null");
if (name != null) {
}
return name;
}
/** An mirror adaptor for {@link ComponentSetup}. */
public non-sealed abstract class AbstractBuildTimeComponentMirror implements ComponentMirror {
/** {@inheritDoc} */
@Override
public final ApplicationMirror application() {
return application.mirror();
}
/** {@inheritDoc} */
@Override
public final Realm registrant() {
Class<? extends Extension> extensionType = realm.extensionType;
return extensionType == null ? Realm.application() : Realm.extension(extensionType);
}
/** {@inheritDoc} */
@Override
public final Collection<ComponentMirror> children() {
LinkedHashMap<String, ComponentSetup> m = children;
return m == null ? List.of() : CollectionUtil.unmodifiableView(m.values(), c -> c.mirror());
}
@Override
public Stream<ComponentMirror> components() {
return stream();
}
/** {@inheritDoc} */
@Override
public final BundleMirror bundle() {
return container.mirror();
}
/** {@inheritDoc} */
@Override
public final int depth() {
return depth;
}
/** {@inheritDoc} */
@Override
public final boolean isInSame(ComponentScope scope, ComponentMirror other) {
requireNonNull(other, "other is null");
return ComponentSetup.this.isInSame(scope, ((AbstractBuildTimeComponentMirror) other).outer());
}
/** {@inheritDoc} */
@Override
public final String name() {
return name;
}
private ComponentSetup outer() {
return ComponentSetup.this;
}
/** {@inheritDoc} */
@Override
public final Optional<ComponentMirror> parent() {
ComponentSetup parent = ComponentSetup.this.parent;
return parent == null ? Optional.empty() : Optional.of(parent.mirror());
}
/** {@inheritDoc} */
@Override
public final NamespacePath path() {
return ComponentSetup.this.path();
}
/** {@inheritDoc} */
@Override
public final Relation relationTo(ComponentMirror other) {
requireNonNull(other, "other is null");
return ComponentSetupRelation.of(ComponentSetup.this, ((AbstractBuildTimeComponentMirror) other).outer());
}
/** {@inheritDoc} */
@Override
public final ComponentMirror resolve(CharSequence path) {
LinkedHashMap<String, ComponentSetup> map = children;
if (map != null) {
ComponentSetup cs = map.get(path.toString());
if (cs != null) {
return cs.mirror();
}
}
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override
public final ComponentMirror root() {
ComponentSetup c = ComponentSetup.this;
while (c.parent != null) {
c = c.parent;
}
return c == ComponentSetup.this ? this : c.mirror();
}
/** {@inheritDoc} */
@Override
public final ComponentMirrorStream stream(ComponentMirrorStream.Option... options) {
return new PackedComponentStream(stream0(ComponentSetup.this, true, PackedComponentStreamOption.of(options)));
}
private Stream<ComponentMirror> stream0(ComponentSetup origin, boolean isRoot, PackedComponentStreamOption option) {
// Also fix in ComponentConfigurationToComponentAdaptor when changing stuff here
@SuppressWarnings({ "unchecked", "rawtypes" })
Collection<AbstractBuildTimeComponentMirror> c = (Collection) children();
if (c != null && !c.isEmpty()) {
if (option.processThisDeeper(origin, ComponentSetup.this)) {
Stream<ComponentMirror> s = c.stream().flatMap(co -> co.stream0(origin, false, option));
return isRoot && option.excludeOrigin() ? s : Stream.concat(Stream.of(this), s);
}
return Stream.empty();
} else {
return isRoot && option.excludeOrigin() ? Stream.empty() : Stream.of(this);
}
}
}
}
|
brunocanella/OpenAUTOS
|
os/osek/os.h
|
#ifndef OSEK_OS_H
#define OSEK_OS_H
#include "types.h"
/**This data type represents the application mode.*/
typedef uint8_t AppModeType;
/**
* This service returns the current application mode. It may be used to write mode dependent code.
*
* @remark See chapter 5 for a general description of application modes.
* @remark Allowed for task, ISR and all hook routines.
*
* @return The current application mode.
*
* @remark [Conformance] BCC1, BCC2, ECC1, ECC2
*/
AppModeType GetActiveApplicationMode( void );
/**
* The user can call this system service to start the operating system in a specific mode, see chapter 5, Application modes.
*
* @remark Only allowed outside of the operating system, therefore implementation specific restrictions may apply. See also chapter 11.3, System start-up, especially with respect to systems where OSEK and OSEKtime coexist. This call does not need to return.
*
* @param[in] Mode The application mode to start the OS.
*
* @remark [Conformance] BCC1, BCC2, ECC1, ECC2
*/
void StartOS( AppModeType Mode );
/**
* @brief The user can call this system service to abort the overall system (e.g. emergency off). The operating system also calls this function internally, if it has reached an undefined internal state and is no longer ready to run.
* @brief If a ShutdownHook is configured the hook routine ShutdownHook is always called (with <Error> as argument) before shutting down the operating system. If ShutdownHook returns, further behaviour of ShutdownOS is implementation specific.
* @brief In case of a system where OSEK OS and OSEKtime OS coexist, ShutdownHook has to return.
* @brief <Error> needs to be a valid error code supported by OSEK OS. In case of a system where OSEK OS and OSEKtime OS coexist, <Error> might also be a value accepted by OSEKtime OS. In this case, if enabled by an OSEKtime configuration parameter, OSEKtime OS will be shut down after OSEK OS shutdown.
*
* @remark After this service the operating system is shut down.
* @remark Allowed at task level, ISR level, in ErrorHook and StartupHook, and also called internally by the operating system.
* @remark If the operating system calls ShutdownOS it never uses E_OK as the passed parameter value.
*
* @param[in] Error The error
*/
void ShutdownOS( StatusType Error );
/**Default application mode, always a valid parameter to StartOS.*/
extern const AppModeType OSDEFAULTAPPMODE;
#endif//OSEK_OS_H
|
hstove/universal-wallet
|
packages/webapp/src/components/BlockstackLink.js
|
import React, { Component, Fragment } from 'react';
import { Button, Center } from '../theme';
export default class BlockstackLink extends Component {
state = { mode: null, url: null };
componentDidUpdate(prevProps) {
const { qrData } = this.props;
if (!prevProps.qrData && qrData) {
this.setState({ url: qrData });
}
}
render() {
const { mode, url } = this.state;
if (url) {
if (mode === 'setup') {
setTimeout(() => {
window.location = url;
}, 3000);
return (
<Center>
You will be redirected to setup your Blockstack info
</Center>
);
}
localStorage.setItem('BLOCKSTACK_LINK', url);
return <Center>The link has been set, you are ready to sign in.</Center>;
}
return (
<Fragment>
<Button
onClick={() => this.setState({ mode: 'link' }, this.props.qrScan)}
>
Link your device
</Button>
<Button
onClick={() => this.setState({ mode: 'setup' }, this.props.qrScan)}
>
Setup Blockstack Link
</Button>
</Fragment>
);
}
}
|
samtingleff/dgrid
|
java/src/client/com/dgrid/helpers/impl/SDBHelperImpl.java
|
<filename>java/src/client/com/dgrid/helpers/impl/SDBHelperImpl.java
package com.dgrid.helpers.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dgrid.errors.SDBException;
import com.dgrid.errors.TransportException;
import com.dgrid.gen.InvalidApiKey;
import com.dgrid.helpers.AWSConstants;
import com.dgrid.helpers.SDBHelper;
import com.dgrid.service.DGridClient;
import com.xerox.amazonws.sdb.SimpleDB;
public class SDBHelperImpl implements SDBHelper
{
private Log log = LogFactory.getLog(getClass());
private DGridClient gridClient;
public void setGridClient(DGridClient gridClient)
{
this.gridClient = gridClient;
}
public SimpleDB getSimpleDB() throws TransportException, InvalidApiKey, SDBException
{
log.trace("getSimpleDB()");
String awsAccessKey = gridClient.getSetting(AWSConstants.AWS_ACCESS_KEY_SETTING, "");
String awsSecretKey = gridClient.getSetting(AWSConstants.AWS_SECRET_KEY_SETTING, "");
return new SimpleDB(awsAccessKey, awsSecretKey);
}
}
|
kppw99/enVAS
|
dataset/source/SARD/SARD-3/89422/CWE197_Numeric_Truncation_Error__short_listen_socket_83.h
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__short_listen_socket_83.h
Label Definition File: CWE197_Numeric_Truncation_Error__short.label.xml
Template File: sources-sink-83.tmpl.h
*/
/*
* @description
* CWE: 197 Numeric Truncation Error
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Less than CHAR_MAX
* Sinks:
* BadSink : Convert data to a char
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#include "std_testcase.h"
namespace CWE197_Numeric_Truncation_Error__short_listen_socket_83
{
#ifndef OMITBAD
class CWE197_Numeric_Truncation_Error__short_listen_socket_83_bad
{
public:
CWE197_Numeric_Truncation_Error__short_listen_socket_83_bad(short dataCopy);
~CWE197_Numeric_Truncation_Error__short_listen_socket_83_bad();
private:
short data;
};
#endif /* OMITBAD */
#ifndef OMITGOOD
class CWE197_Numeric_Truncation_Error__short_listen_socket_83_goodG2B
{
public:
CWE197_Numeric_Truncation_Error__short_listen_socket_83_goodG2B(short dataCopy);
~CWE197_Numeric_Truncation_Error__short_listen_socket_83_goodG2B();
private:
short data;
};
#endif /* OMITGOOD */
}
|
redfast00/daily-algorithm-challenge
|
src/122_maximum_matrix_path_sum.py
|
from utils import INFINITY
def maximum_matrix_path_sum(matrix):
'''Returns the maximum amount of 'coins' on the path.
The path taken is a shortest path from the upper-left corner to the bottom-right corner.
>>> maximum_matrix_path_sum([[0, 3, 1, 1], [2, 0, 0, 4], [1, 5, 3, 1]])
12
'''
height = len(matrix)
width = len(matrix[0])
new_matrix = [[None for _ in range(width)] for _ in range(height)]
return get_parent(matrix, new_matrix, height - 1, width - 1, width, height)
def get_parent(matrix, new_matrix, x, y, width, height):
# This is kinda inefficent, this can be done with two nested for-loops
# Using for-loops doesn't have the overhead of the callstack
max_ = -INFINITY
# Calculate 'parents'
for dx, dy in ((-1, 0), (0, -1)):
nx, ny = x + dx, y + dy
if nx in range(height) and ny in range(width):
if new_matrix[nx][ny] is None:
new_matrix[nx][ny] = get_parent(matrix, new_matrix, nx, ny, width, height)
max_ = max(new_matrix[nx][ny], max_)
if max_ == -INFINITY:
return matrix[x][y]
return max_ + matrix[x][y]
|
multifascinated/elevate-ui
|
src/Hr/index.js
|
// @flow
import React, { Component } from "react";
import withStyles from "../withStyles";
import classNames from "classnames";
type Props = {
/**
* Accepts any classNames to be passed to the component.
*/
className: string,
classes: Object,
/**
* Color to be applied to the Hr component. Can be "primary", "secondary", or any custom value.
*/
color?: string,
/**
* Adds default margin bottom
*/
gutterBottom: boolean,
/**
* Adds default margin top
*/
gutterTop: boolean,
/**
* Style object with any applicable overrides
*/
style: Object,
/**
* Default theme object from `withStyles`
*/
theme: Object,
/**
* Height/thickness of the Hr component.
*/
thickness?: string | number,
};
/**
* A component used to render a styled hr.
*/
class Hr extends Component<Props> {
static defaultProps = {
gutterTop: true,
gutterBottom: true,
};
render() {
const { classes, className, style } = this.props;
return (
<div className={classNames(classes.root, className)} style={style} />
);
}
}
const styles = (theme) => ({
root: {
display: "flex",
width: "100%",
height: (props) => props.thickness || "1px",
backgroundColor: (props) =>
theme.colors[props.color] || props.color || theme.colors.gray300,
marginTop: (props) => (props.gutterTop ? "16px" : 0),
marginBottom: (props) => (props.gutterBottom ? "16px" : 0),
},
});
export default withStyles(styles, { name: "EuiHr" })(Hr);
|
glathoud/flatorize
|
lib/flatmat.js
|
/* Fast math functions for 2-D matrices stored as flat (1-D) arrays of
numbers.
Requires: ../flatorize.js
Copyright 2017 <NAME>
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.
A copy of the Apache License Version 2.0 as of February 20th, 2013
can be found in the file ../LICENSE.TXT
*/
/*global FR flatmat Float64Array JSON setTimeout
fm_unittest
fm_id
fm_inv_of_ij
fm_mul_of_ijk
fm_mu_sigma_of_dim
fm_xvmxv_of_dim
zz_fm_mul_of_ijk_abc
zz_fm_mul_of_ijk_ab
zz_fm_matmul
zz_fm_mu_sigma_of_dim
zz_fm_xvmxv_of_dim_xvm
zz_fm_matmul_of_ijk_ab
*/
var flatmat;
fm_unittest();
function fm_unittest()
{
fm_unittest.fm_mul_of_ijk = fm_unittest_fm_mul_of_ijk;
fm_unittest.fm_xvmxv_of_dim = fm_unittest_fm_xvmxv_of_dim;
fm_unittest.fm_inv_of_ij = fm_unittest_fm_inv_of_ij;
if ('undefined' === typeof FR)
setTimeout( fm_unittest_impl, 100 );
else
fm_unittest_impl();
function fm_unittest_impl()
{
fm_unittest.fm_mul_of_ijk();
fm_unittest.fm_xvmxv_of_dim();
fm_unittest.fm_inv_of_ij();
// -- Done!
flatmat = true;
}
function fm_unittest_fm_mul_of_ijk()
{
// -- Does flat matrix multiplication work?
var flatmatmul_342 = fm_mul_of_ijk( 3, 4, 2 );
var a = new Float64Array([
1,2,3,4
, 5,6,7,8
, 9,10,11,12
])
, b = new Float64Array([
13,14
, 15,16
, 17,18
, 19,20
])
, c = new Float64Array( 3 * 2 )
;
flatmatmul_342( a, b, c );
JSON.stringify( Array.apply( null, c ) ) === JSON.stringify([
1*13+2*15+3*17+4*19, 1*14+2*16+3*18+4*20
, 5*13+6*15+7*17+8*19, 5*14+6*16+7*18+8*20
, 9*13+10*15+11*17+12*19, 9*14+10*16+11*18+12*20
])
|| null.bug
;
}
function fm_unittest_fm_xvmxv_of_dim()
{
// -- Does flat matrix implementation of (x - v)^T * m * (x - v) work?
var x = new Float64Array([
1
, 3
, 4
])
, v = new Float64Array([
7
, 11
, 18
])
, m = new Float64Array([
29, 47, 76
, 123, 199, 322
, 521, 843, 1364
])
, flatmat_xvmxv_3 = fm_xvmxv_of_dim( 3 )
, obtained = flatmat_xvmxv_3( x, v, m )
, xv = [ x[ 0 ] - v[ 0 ]
, x[ 1 ] - v[ 1 ]
, x[ 2 ] - v[ 2 ]
]
, xv_m = [
xv[0] * m[0] + xv[1] * m[3] + xv[2] * m[6]
, xv[0] * m[1] + xv[1] * m[4] + xv[2] * m[7]
, xv[0] * m[2] + xv[1] * m[5] + xv[2] * m[8]
]
, expected = xv_m[0] * xv[0] + xv_m[1] * xv[1] + xv_m[2] * xv[2]
;
1e-7 > Math.abs( expected - obtained ) || null.bug;
}
function fm_unittest_fm_inv_of_ij()
{
// -- Does matrix inversion work?
var fm_inv_4 = fm_inv_of_ij( 4 )
, fm_mul_4 = fm_mul_of_ijk( 4 )
;
var m = new Float64Array([
1, 4, 2, 17
, 54, 23, 12, 56
, 7, 324, 23, 56
, 542, 3, 23, 43
])
, minv = new Float64Array([
0.02666295701993568, -0.010690122413924162, 0.0004032528845117337, 0.0028556842862368756
, 0.03806261011863206, -0.016499239220523557, 0.0037736340871618243, 0.001524872452360714
, -0.9276078787064798, 0.31489411381119636, -0.010628270423968902, -0.029524495155222024
, 0.1574295505834409, -0.03253536166625731, 0.00033875009498698656, 0.0029466950714567243
])
, Id = fm_id( 4 )
, tmp = new Float64Array( 16 )
, epsilon = 1e-10
;
// First, check minv itself
fm_mul_4( m, minv, tmp );
is_finite( tmp ) || null.bug;
epsilon > compare( tmp, Id ) || null.bug;
// Second, check the implementation
var obtained = fm_inv_4( m, tmp );
obtained === tmp || null.bug;
is_finite( tmp ) || null.bug;
epsilon > compare( tmp, minv ) || null.bug;
// --- Does matrix inversion fail where it should?
var m = new Float64Array([
1, 3, 4, 7
, 11, 18, 29, 47
, 76, 123, 199, 322
, 521, 843, 1364, 2207
])
, tmp = new Float64Array( 16 ) // filled with zeroes
, obtained = fm_inv_4( m, tmp )
;
obtained === false || null.bug;
!is_finite( tmp ) || null.bug; // filled with NaNs
}
// -- Details
function compare( a, b )
{
is_finite( a ) || null.bug;
is_finite( b ) || null.bug;
return a.reduce( compare_one_pair, 0 );
function compare_one_pair(current, va, ind)
{
var vb = b[ ind ];
return Math.max(
current
, Math.abs( va - vb )
);
}
}
function is_finite( arr )
{
return arr.every( function ( v ) {
return 'number' === typeof v && isFinite( v );
} );
}
}
// ---------- Top-level API
function fm_id( /*integer*/I, /*?integer?*/J )
/*
Returns an identity matrix of dimensions `(I,J)`: a Float64Array of `I*J` numbers.
By default `J = I` (square matrix).
*/
{
J != null || (J = I); // default: square matrix
var m = new Float64Array( I*J );
for (var i = 0, i_end = Math.min( I, J ), ind = 0, Jp1 = J + 1;
i < i_end;
++i, ind += Jp1
)
m[ ind ] = 1
;
return m;
}
function fm_inv_of_ij( /*integer*/I, /*?integer?*/J )
/*
Returns a fast function `f( m_flat, out )`
that inverts a matrix `m_flat` and writes the result in pre-allocated `out`.
`m_flat` and `out` must both be (Float64)Arrays of `I*J` numbers.
By default `J = I` (square matrix).
*/
{
J != null || (J = I); // default: square matrix
var IJ = I*J
, A_flat = new Float64Array( IJ )
// B will be initialized with the identity matrix
, B_flat = fm_id( I, J )
, B_flat_init = fm_id( I, J )
// For matrix inversion it is faster to work in 2-D the whole
// time, probably because of faster row swaps.
, A = Array.apply( null, { length : I } )
.map( function (_,i) {
return A_flat.subarray( i*J, (i+1)*J );
})
, B = Array.apply( null, { length : I } )
.map( function (_,i) {
return B_flat.subarray( i*J, (i+1)*J );
})
// remember the initial order of rows
, A_init = A
, B_init = B
, abs = Math.abs
;
return hand_thru2d_fm_inv;
function hand_thru2d_fm_inv
( /*Float64Array[I*J]*/m_flat, /*Float64Array[I*J]*/out )
// Implementation: I took numeric.inv() from numeric.js and
// adapted it to flat matrices (Float64Array).
{
// The intermediary values
A_flat.set( m_flat ); // init: copy of the input
B_flat.set( B_flat_init ); // init: identity matrix
// remember the initial order of rows
A = A_init;
B = B_init;
for(j=0;j<J;++j) {
var i0 = -1;
var v0 = -1;
for(i=j;i!==I;++i) { k = abs(A[i][j]); if(k>v0) { i0 = i; v0 = k; } }
if (i0 === j)
{
Aj = A[j];
Bj = B[j];
}
else
{
Aj = A[i0]; A[i0] = A[j]; A[j] = Aj;
Bj = B[i0]; B[i0] = B[j]; B[j] = Bj;
}
x = Aj[j];
if (x === 0)
{
// Failed to inverse
//
// Matrix not invertible at all and/or not invertible
// within the Float64 numerical precision.
out.fill( NaN );
return false;
}
for(k=j;k!==J;++k) Aj[k] /= x;
for(k=J-1;k!==-1;--k) Bj[k] /= x;
for(i=I-1;i!==-1;--i) {
if(i!==j) {
Ai = A[i];
Bi = B[i];
x = Ai[j];
for(k=j+1;k!==J;++k) Ai[k] -= Aj[k]*x;
for(k=J-1;k>0;--k) { Bi[k] -= Bj[k]*x; --k; Bi[k] -= Bj[k]*x; }
if(k===0) Bi[0] -= Bj[0]*x;
}
}
}
// Copy the resulting values: *not* from B_flat, but rather
// row-by-row because B's rows have been swapped
for (var i = 0, ind = 0;
i<I;
++i,
ind += J
)
out.set( B[ i ], ind )
;
return out;
}
}
function fm_mul_of_ijk( /*integer*/I, /*?integer?*/J, /*?integer?*/K )
/*
Returns a fast function `f(a,b,c)` that computes the matrix
multiplication `a*b` and stores the output into pre-allocated `c`. <ul><li>Input: `a` has dimensions `(I,J)`,</li>
<li>Input: `b` has dimensions `(J,K)`,</li><li>Output: `c` has dimensions `(I,K)`.</li></ul>
`a`, `b` and `c` must all be (Float64)Arrays of respectively `I*J`, `J*K` and `I*K` numbers.
By default `I=J=K` (square matrices).
*/
{
J != null || (J = I); // default
K != null || (K = J); // default
var a_n = I*J
, b_n = J*K
, c_n = I*K
, key = [ I, J, K ].join( '#' )
;
if (!(key in fm_mul_of_ijk))
{
var func = FR(
// note the :[type] declarations, ignored by `FR`
// but useful later in asm.js, C or D contexts
'a:[' + a_n + ' double],b:[' + b_n + ' double],c:[' + c_n + ' double]->c:[' + c_n + ' double]'
, zz_fm_mul_of_ijk_abc.bind( null, I, J, K )
)
.getDirect() // no FR wrapper, to get the fastest performance
;
fm_mul_of_ijk[ key ] = func;
}
return fm_mul_of_ijk[ key ];
}
function fm_mu_sigma_of_dim( /*integer*/dim )
/*
Returns a fast function `f` that computes the mean vector and covariance
matrix of an array of vectors `v_arr`.
The returned function itself `f( v_arr, maybe_mu, maybe_sigma )` takes as input `v_arr`, and
optionally pre-allocated output arrays: `maybe_mu` & `maybe_sigma`,
both (Float64)Arrays of numbers. Returned value: object `{mu,sigma}`
*/
{
if (!(dim in fm_mu_sigma_of_dim))
fm_mu_sigma_of_dim[ dim ] = zz_fm_mu_sigma_of_dim( dim );
return fm_mu_sigma_of_dim[ dim ];
}
function fm_xvmxv_of_dim( /*integer*/dim )
/*
Returns a fast function `f(x,v,m)` that takes vectors `x` and `v`, and matrix
`m` as input, and returns a float number: `(x - v)^T * m * (x - v)`
Example of use: compute the exponent of a Gaussian PDF:<ul><li>`v` would be
the mean vector,</li><li>`m` the inverse of the covariance matrix.</li></ul>
*/
{
if (!(dim in fm_xvmxv_of_dim))
{
var func = FR(
'x:['+dim+' double],v:['+dim+' double],m:['+(dim*dim)+' double]->out:double'
, zz_fm_xvmxv_of_dim_xvm.bind( null, dim )
).getDirect()
;
fm_xvmxv_of_dim[ dim ] = func;
}
return fm_xvmxv_of_dim[ dim ];
}
// ---------- Lower-level implementation, normally not needed
function zz_fm_mul_of_ijk_abc( /*integer*/I, /*integer*/J, /*integer*/K, a, b, c )
// `a`, `b` and `c` can be any expressions, typically simple
// characters (e.g. a==="a", b==="b", c==="c") meaning: array named
// "a", array named "b", array named "c".
{
return FR.inplace_array_output(
zz_fm_mul_of_ijk_ab( I, J, K, a, b )
, c
// , I*K // not using auto_alloc_length because it costs performance, even if c already allocated
);
}
function zz_fm_mul_of_ijk_ab( /*integer*/I, /*integer*/J, /*integer*/K, a, b )
// `a` and `b` can be any expressions, typically simple characters
// (e.g. a==="a", b==="b"), meaning: array named "a", array named "b".
{
// Create 2-D matrices of symbolic expressions (NOT numbers)
var ma = FR.matrix_of_array( [ I, J ], a )
, mb = FR.matrix_of_array( [ J, K ], b )
// Multiply in 2-D space
, mc = zz_fm_matmul( ma, mb )
;
// Come back to 1-D space
return FR.array_of_matrix( [ I, K ], mc );
}
function zz_fm_matmul( ma, mb )
// `ma` and `mb` are 2D matrices - i.e. array of array of expressions.
//
// See also: `FR.matrix()` in ../FR.js
{
var mbT = FR.transpose( mb );
return ma.map( function ( row_a ) {
return mbT.map( function ( col_b ) {
// dot product of row_a and col_b
return FR.sum(
FR
.zip( row_a, col_b )
.map( function ( va_vb ) {
return FR.expr( va_vb[ 0 ], '*', va_vb[ 1 ] );
} )
);
} );
} );
}
function zz_fm_mu_sigma_of_dim( dim )
// Create a function that computes the mean vector and covariance
// (flat)matrix of an array of vectors `v_arr`.
//
// The returned function itself takes as input `v_arr`, and optionally
// two pre-allocated output arrays: `maybe_mu` and `maybe_sigma`, both
// (Float64)Arrays of numbers. Returned value : `{mu,sigma}`
{
var arr_dim = FR.empty_array( dim ).map( function (_,i) { return i; } );
var param = 'v_arr,maybe_mu,maybe_sigma'
, code = [
'var n = v_arr.length'
, 'var mu = maybe_mu || new Float64Array(' + dim + ')'
, 'var sigma = maybe_sigma || new Float64Array(' + (dim*dim) + ')'
, 'var ' + arr_dim.map( function (i) {
return [ 'v' + i
, 'mu' + i + ' = 0'
]
.concat( arr_dim.slice( i ).map( function (j) {
return 'sigma' + i + '_' + j + ' = 0';
}))
.join( ', ' )
;
} ).join( ', ' )
, 'for (var k = n; k--;) {'
, ' var v = v_arr[ k ]'
]
.concat(
arr_dim.map( function (i) {
return 'mu' + i + ' += (v' + i +' = v[' + i + ']); sigma' + i + '_' + i + ' += v'+i+' * v'+i;
})
)
.concat(
arr_dim.map( function (i) {
return arr_dim.slice( i+1 ).map( function (j) {
return 'sigma' + i + '_' + j + ' += v'+i+' * v'+j;
});
})
.reduce( function (a,b) { return a.concat( b ); } )
)
.concat([
'}'
])
.concat(
arr_dim.map( function (i) {
return 'mu['+i+'] = (mu' + i + '/= n)';
})
)
.concat(
arr_dim.map( function (i) {
return arr_dim.slice( i ).map( function (j) {
return (i < j ? 'sigma[' + (j*dim+i)+ '] = ' : '') +
'sigma[' + (i*dim+j) +'] = ' +
'sigma' + i + '_' + j + '/n - mu' + i + ' * mu' + j
;
})
})
.reduce( function (a,b) { return a.concat( b ); } )
)
.concat([
'return { mu : mu, sigma : sigma }'
])
.join( ';\n' )
;
return new Function( param, code );
}
function zz_fm_xvmxv_of_dim_xvm( dim, x, v, m )
{
var xv = FR.vecsub( FR.vec( dim, x ), FR.vec( dim, v ) )
, xv_M = FR.matrix_of_array( [ dim, 1 ], xv )
, m_M = FR.matrix_of_array( [ dim, dim ], m )
, M_ret = zz_fm_matmul(
zz_fm_matmul( FR.transpose( xv_M ) , m_M )
, xv_M
)
;
return M_ret[ 0 ][ 0 ];
}
// ---------- In case someone wants to directly work in 2D (slower)
function zz_fm_matmul_of_ijk_ab( I, J, K, a, b )
{
// Create matrices of symbolic expressions (NOT numbers)
var ma = FR.matrix( [ I, J ], a )
, mb = FR.matrix( [ J, K ], b )
;
// Multiply the symbolic matrices
return zz_fm_matmul( ma, mb );
}
|
ZubinGou/Learn-Python3-The-Hard-Way
|
ex-data-structure/ds_tuples_sequences.py
|
<reponame>ZubinGou/Learn-Python3-The-Hard-Way
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-19 20:15:29
# @Author : ZubinGou (<EMAIL>)
# @Link : https://github.com/ZubinGou
# @Version : $Id$
import os
# del statement
a = list(range(10))
print(a)
del a[2]
print(a)
del a[:]
print(a)
# tuples and sequences
t = 1233, 243543, 'welle'
print(type(t))
print(t)
u = t, (34, 34)
print(u)
v = t, 34, 33
print(v)
w = ((23,4324), [342,'sdf'])
print(w)
print(type(w[1]))
singleton = 'hell'
print(len(singleton))
# see, magic
singleton = 'hell',
print(len(singleton))
t = 434,'343','bd'
a, b, c = t
print(b,a)
|
dmgerman/hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java
|
<filename>hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.client.api.impl
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|client
operator|.
name|api
operator|.
name|impl
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|Serializable
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collection
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collections
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Comparator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashMap
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|HashSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Iterator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|LinkedHashSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|LinkedList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|TreeSet
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|AbstractMap
operator|.
name|SimpleEntry
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
operator|.
name|Private
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceStability
operator|.
name|Unstable
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|conf
operator|.
name|Configuration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|io
operator|.
name|Text
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|ipc
operator|.
name|RPC
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|net
operator|.
name|Node
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|UserGroupInformation
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|ApplicationMasterProtocol
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|protocolrecords
operator|.
name|AllocateRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|protocolrecords
operator|.
name|AllocateResponse
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|protocolrecords
operator|.
name|FinishApplicationMasterRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|protocolrecords
operator|.
name|FinishApplicationMasterResponse
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|protocolrecords
operator|.
name|RegisterApplicationMasterRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|protocolrecords
operator|.
name|RegisterApplicationMasterResponse
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|Container
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ContainerId
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ContainerStatus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ContainerUpdateType
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ExecutionType
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ExecutionTypeRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|FinalApplicationStatus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|NMToken
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|Priority
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|Resource
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ResourceBlacklistRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ResourceInformation
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ResourceRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|SchedulingRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|Token
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|UpdateContainerRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|UpdatedContainer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|resource
operator|.
name|PlacementConstraint
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|client
operator|.
name|AMRMClientUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|client
operator|.
name|ClientRMProxy
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|client
operator|.
name|api
operator|.
name|AMRMClient
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|client
operator|.
name|api
operator|.
name|AMRMClient
operator|.
name|ContainerRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|client
operator|.
name|api
operator|.
name|InvalidContainerRequestException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|conf
operator|.
name|YarnConfiguration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|exceptions
operator|.
name|ApplicationMasterNotRegisteredException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|exceptions
operator|.
name|YarnException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|exceptions
operator|.
name|YarnRuntimeException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|security
operator|.
name|AMRMTokenIdentifier
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|util
operator|.
name|RackResolver
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|annotations
operator|.
name|VisibleForTesting
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Joiner
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Preconditions
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|util
operator|.
name|resource
operator|.
name|Resources
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_class
annotation|@
name|Private
annotation|@
name|Unstable
DECL|class|AMRMClientImpl
specifier|public
class|class
name|AMRMClientImpl
parameter_list|<
name|T
extends|extends
name|ContainerRequest
parameter_list|>
extends|extends
name|AMRMClient
argument_list|<
name|T
argument_list|>
block|{
DECL|field|LOG
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|AMRMClientImpl
operator|.
name|class
argument_list|)
decl_stmt|;
DECL|field|ANY_LIST
specifier|private
specifier|static
specifier|final
name|List
argument_list|<
name|String
argument_list|>
name|ANY_LIST
init|=
name|Collections
operator|.
name|singletonList
argument_list|(
name|ResourceRequest
operator|.
name|ANY
argument_list|)
decl_stmt|;
DECL|field|lastResponseId
specifier|private
name|int
name|lastResponseId
init|=
literal|0
decl_stmt|;
DECL|field|appHostName
specifier|protected
name|String
name|appHostName
decl_stmt|;
DECL|field|appHostPort
specifier|protected
name|int
name|appHostPort
decl_stmt|;
DECL|field|appTrackingUrl
specifier|protected
name|String
name|appTrackingUrl
decl_stmt|;
DECL|field|newTrackingUrl
specifier|protected
name|String
name|newTrackingUrl
decl_stmt|;
DECL|field|rmClient
specifier|protected
name|ApplicationMasterProtocol
name|rmClient
decl_stmt|;
DECL|field|clusterAvailableResources
specifier|protected
name|Resource
name|clusterAvailableResources
decl_stmt|;
DECL|field|clusterNodeCount
specifier|protected
name|int
name|clusterNodeCount
decl_stmt|;
comment|// blacklistedNodes is required for keeping history of blacklisted nodes that
comment|// are sent to RM. On RESYNC command from RM, blacklistedNodes are used to get
comment|// current blacklisted nodes and send back to RM.
DECL|field|blacklistedNodes
specifier|protected
specifier|final
name|Set
argument_list|<
name|String
argument_list|>
name|blacklistedNodes
init|=
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
DECL|field|blacklistAdditions
specifier|protected
specifier|final
name|Set
argument_list|<
name|String
argument_list|>
name|blacklistAdditions
init|=
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
DECL|field|blacklistRemovals
specifier|protected
specifier|final
name|Set
argument_list|<
name|String
argument_list|>
name|blacklistRemovals
init|=
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
DECL|field|placementConstraints
specifier|private
name|Map
argument_list|<
name|Set
argument_list|<
name|String
argument_list|>
argument_list|,
name|PlacementConstraint
argument_list|>
name|placementConstraints
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
DECL|field|resourceProfilesMap
specifier|protected
name|Map
argument_list|<
name|String
argument_list|,
name|Resource
argument_list|>
name|resourceProfilesMap
decl_stmt|;
DECL|class|ResourceRequestInfo
specifier|static
class|class
name|ResourceRequestInfo
parameter_list|<
name|T
parameter_list|>
block|{
DECL|field|remoteRequest
name|ResourceRequest
name|remoteRequest
decl_stmt|;
DECL|field|containerRequests
name|LinkedHashSet
argument_list|<
name|T
argument_list|>
name|containerRequests
decl_stmt|;
DECL|method|ResourceRequestInfo (Long allocationRequestId, Priority priority, String resourceName, Resource capability, boolean relaxLocality)
name|ResourceRequestInfo
parameter_list|(
name|Long
name|allocationRequestId
parameter_list|,
name|Priority
name|priority
parameter_list|,
name|String
name|resourceName
parameter_list|,
name|Resource
name|capability
parameter_list|,
name|boolean
name|relaxLocality
parameter_list|)
block|{
name|remoteRequest
operator|=
name|ResourceRequest
operator|.
name|newBuilder
argument_list|()
operator|.
name|priority
argument_list|(
name|priority
argument_list|)
operator|.
name|resourceName
argument_list|(
name|resourceName
argument_list|)
operator|.
name|capability
argument_list|(
name|capability
argument_list|)
operator|.
name|numContainers
argument_list|(
literal|0
argument_list|)
operator|.
name|allocationRequestId
argument_list|(
name|allocationRequestId
argument_list|)
operator|.
name|relaxLocality
argument_list|(
name|relaxLocality
argument_list|)
operator|.
name|build
argument_list|()
expr_stmt|;
name|containerRequests
operator|=
operator|new
name|LinkedHashSet
argument_list|<
name|T
argument_list|>
argument_list|()
expr_stmt|;
block|}
block|}
comment|/** * Class compares Resource by memory, then cpu and then the remaining resource * types in reverse order. */
DECL|class|ResourceReverseComparator
specifier|static
class|class
name|ResourceReverseComparator
parameter_list|<
name|T
extends|extends
name|Resource
parameter_list|>
implements|implements
name|Comparator
argument_list|<
name|T
argument_list|>
implements|,
name|Serializable
block|{
DECL|method|compare (Resource res0, Resource res1)
specifier|public
name|int
name|compare
parameter_list|(
name|Resource
name|res0
parameter_list|,
name|Resource
name|res1
parameter_list|)
block|{
return|return
name|res1
operator|.
name|compareTo
argument_list|(
name|res0
argument_list|)
return|;
block|}
block|}
DECL|field|remoteRequests
specifier|private
specifier|final
name|Map
argument_list|<
name|Long
argument_list|,
name|RemoteRequestsTable
argument_list|<
name|T
argument_list|>
argument_list|>
name|remoteRequests
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
DECL|field|ask
specifier|protected
specifier|final
name|Set
argument_list|<
name|ResourceRequest
argument_list|>
name|ask
init|=
operator|new
name|TreeSet
argument_list|<
name|ResourceRequest
argument_list|>
argument_list|(
operator|new
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ResourceRequest
operator|.
name|ResourceRequestComparator
argument_list|()
argument_list|)
decl_stmt|;
DECL|field|release
specifier|protected
specifier|final
name|Set
argument_list|<
name|ContainerId
argument_list|>
name|release
init|=
operator|new
name|TreeSet
argument_list|<
name|ContainerId
argument_list|>
argument_list|()
decl_stmt|;
comment|// pendingRelease holds history of release requests.
comment|// request is removed only if RM sends completedContainer.
comment|// How it different from release? --> release is for per allocate() request.
DECL|field|pendingRelease
specifier|protected
name|Set
argument_list|<
name|ContainerId
argument_list|>
name|pendingRelease
init|=
operator|new
name|TreeSet
argument_list|<
name|ContainerId
argument_list|>
argument_list|()
decl_stmt|;
comment|// change map holds container resource change requests between two allocate()
comment|// calls, and are cleared after each successful allocate() call.
specifier|protected
specifier|final
name|Map
argument_list|<
name|ContainerId
argument_list|,
DECL|field|change
name|SimpleEntry
argument_list|<
name|Container
argument_list|,
name|UpdateContainerRequest
argument_list|>
argument_list|>
name|change
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
comment|// pendingChange map holds history of container resource change requests in
comment|// case AM needs to reregister with the ResourceManager.
comment|// Change requests are removed from this map if RM confirms the change
comment|// through allocate response, or if RM confirms that the container has been
comment|// completed.
specifier|protected
specifier|final
name|Map
argument_list|<
name|ContainerId
argument_list|,
DECL|field|pendingChange
name|SimpleEntry
argument_list|<
name|Container
argument_list|,
name|UpdateContainerRequest
argument_list|>
argument_list|>
name|pendingChange
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
DECL|field|schedulingRequests
specifier|private
name|List
argument_list|<
name|SchedulingRequest
argument_list|>
name|schedulingRequests
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
DECL|field|outstandingSchedRequests
specifier|private
name|Map
argument_list|<
name|Set
argument_list|<
name|String
argument_list|>
argument_list|,
name|List
argument_list|<
name|SchedulingRequest
argument_list|>
argument_list|>
name|outstandingSchedRequests
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
DECL|method|AMRMClientImpl ()
specifier|public
name|AMRMClientImpl
parameter_list|()
block|{
name|super
argument_list|(
name|AMRMClientImpl
operator|.
name|class
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|VisibleForTesting
DECL|method|AMRMClientImpl (ApplicationMasterProtocol protocol)
name|AMRMClientImpl
parameter_list|(
name|ApplicationMasterProtocol
name|protocol
parameter_list|)
block|{
name|super
argument_list|(
name|AMRMClientImpl
operator|.
name|class
operator|.
name|getName
argument_list|()
argument_list|)
expr_stmt|;
name|this
operator|.
name|rmClient
operator|=
name|protocol
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|serviceInit (Configuration conf)
specifier|protected
name|void
name|serviceInit
parameter_list|(
name|Configuration
name|conf
parameter_list|)
throws|throws
name|Exception
block|{
name|RackResolver
operator|.
name|init
argument_list|(
name|conf
argument_list|)
expr_stmt|;
name|super
operator|.
name|serviceInit
argument_list|(
name|conf
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|serviceStart ()
specifier|protected
name|void
name|serviceStart
parameter_list|()
throws|throws
name|Exception
block|{
specifier|final
name|YarnConfiguration
name|conf
init|=
operator|new
name|YarnConfiguration
argument_list|(
name|getConfig
argument_list|()
argument_list|)
decl_stmt|;
try|try
block|{
if|if
condition|(
name|rmClient
operator|==
literal|null
condition|)
block|{
name|rmClient
operator|=
name|ClientRMProxy
operator|.
name|createRMProxy
argument_list|(
name|conf
argument_list|,
name|ApplicationMasterProtocol
operator|.
name|class
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|YarnRuntimeException
argument_list|(
name|e
argument_list|)
throw|;
block|}
name|super
operator|.
name|serviceStart
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|serviceStop ()
specifier|protected
name|void
name|serviceStop
parameter_list|()
throws|throws
name|Exception
block|{
if|if
condition|(
name|this
operator|.
name|rmClient
operator|!=
literal|null
condition|)
block|{
name|RPC
operator|.
name|stopProxy
argument_list|(
name|this
operator|.
name|rmClient
argument_list|)
expr_stmt|;
block|}
name|super
operator|.
name|serviceStop
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|registerApplicationMaster ( String appHostName, int appHostPort, String appTrackingUrl)
specifier|public
name|RegisterApplicationMasterResponse
name|registerApplicationMaster
parameter_list|(
name|String
name|appHostName
parameter_list|,
name|int
name|appHostPort
parameter_list|,
name|String
name|appTrackingUrl
parameter_list|)
throws|throws
name|YarnException
throws|,
name|IOException
block|{
return|return
name|registerApplicationMaster
argument_list|(
name|appHostName
argument_list|,
name|appHostPort
argument_list|,
name|appTrackingUrl
argument_list|,
literal|null
argument_list|)
return|;
block|}
annotation|@
name|Override
DECL|method|registerApplicationMaster ( String appHostName, int appHostPort, String appTrackingUrl, Map<Set<String>, PlacementConstraint> placementConstraintsMap)
specifier|public
name|RegisterApplicationMasterResponse
name|registerApplicationMaster
parameter_list|(
name|String
name|appHostName
parameter_list|,
name|int
name|appHostPort
parameter_list|,
name|String
name|appTrackingUrl
parameter_list|,
name|Map
argument_list|<
name|Set
argument_list|<
name|String
argument_list|>
argument_list|,
name|PlacementConstraint
argument_list|>
name|placementConstraintsMap
parameter_list|)
throws|throws
name|YarnException
throws|,
name|IOException
block|{
name|this
operator|.
name|appHostName
operator|=
name|appHostName
expr_stmt|;
name|this
operator|.
name|appHostPort
operator|=
name|appHostPort
expr_stmt|;
name|this
operator|.
name|appTrackingUrl
operator|=
name|appTrackingUrl
expr_stmt|;
if|if
condition|(
name|placementConstraintsMap
operator|!=
literal|null
operator|&&
operator|!
name|placementConstraintsMap
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|this
operator|.
name|placementConstraints
operator|.
name|putAll
argument_list|(
name|placementConstraintsMap
argument_list|)
expr_stmt|;
block|}
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|appHostName
operator|!=
literal|null
argument_list|,
literal|"The host name should not be null"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|appHostPort
operator|>=
operator|-
literal|1
argument_list|,
literal|"Port number of the host"
operator|+
literal|" should be any integers larger than or equal to -1"
argument_list|)
expr_stmt|;
return|return
name|registerApplicationMaster
argument_list|()
return|;
block|}
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
DECL|method|registerApplicationMaster ()
specifier|private
name|RegisterApplicationMasterResponse
name|registerApplicationMaster
parameter_list|()
throws|throws
name|YarnException
throws|,
name|IOException
block|{
name|RegisterApplicationMasterRequest
name|request
init|=
name|RegisterApplicationMasterRequest
operator|.
name|newInstance
argument_list|(
name|this
operator|.
name|appHostName
argument_list|,
name|this
operator|.
name|appHostPort
argument_list|,
name|this
operator|.
name|appTrackingUrl
argument_list|)
decl_stmt|;
if|if
condition|(
operator|!
name|this
operator|.
name|placementConstraints
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|request
operator|.
name|setPlacementConstraints
argument_list|(
name|this
operator|.
name|placementConstraints
argument_list|)
expr_stmt|;
block|}
name|RegisterApplicationMasterResponse
name|response
init|=
name|rmClient
operator|.
name|registerApplicationMaster
argument_list|(
name|request
argument_list|)
decl_stmt|;
synchronized|synchronized
init|(
name|this
init|)
block|{
name|lastResponseId
operator|=
literal|0
expr_stmt|;
if|if
condition|(
operator|!
name|response
operator|.
name|getNMTokensFromPreviousAttempts
argument_list|()
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|populateNMTokens
argument_list|(
name|response
operator|.
name|getNMTokensFromPreviousAttempts
argument_list|()
argument_list|)
expr_stmt|;
block|}
name|this
operator|.
name|resourceProfilesMap
operator|=
name|response
operator|.
name|getResourceProfiles
argument_list|()
expr_stmt|;
name|List
argument_list|<
name|Container
argument_list|>
name|prevContainers
init|=
name|response
operator|.
name|getContainersFromPreviousAttempts
argument_list|()
decl_stmt|;
name|AMRMClientUtils
operator|.
name|removeFromOutstandingSchedulingRequests
argument_list|(
name|prevContainers
argument_list|,
name|this
operator|.
name|outstandingSchedRequests
argument_list|)
expr_stmt|;
block|}
return|return
name|response
return|;
block|}
annotation|@
name|Override
DECL|method|addSchedulingRequests ( Collection<SchedulingRequest> newSchedulingRequests)
specifier|public
specifier|synchronized
name|void
name|addSchedulingRequests
parameter_list|(
name|Collection
argument_list|<
name|SchedulingRequest
argument_list|>
name|newSchedulingRequests
parameter_list|)
block|{
name|this
operator|.
name|schedulingRequests
operator|.
name|addAll
argument_list|(
name|newSchedulingRequests
argument_list|)
expr_stmt|;
name|AMRMClientUtils
operator|.
name|addToOutstandingSchedulingRequests
argument_list|(
name|newSchedulingRequests
argument_list|,
name|this
operator|.
name|outstandingSchedRequests
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|allocate (float progressIndicator)
specifier|public
name|AllocateResponse
name|allocate
parameter_list|(
name|float
name|progressIndicator
parameter_list|)
throws|throws
name|YarnException
throws|,
name|IOException
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|progressIndicator
operator|>=
literal|0
argument_list|,
literal|"Progress indicator should not be negative"
argument_list|)
expr_stmt|;
name|AllocateResponse
name|allocateResponse
init|=
literal|null
decl_stmt|;
name|List
argument_list|<
name|ResourceRequest
argument_list|>
name|askList
init|=
literal|null
decl_stmt|;
name|List
argument_list|<
name|ContainerId
argument_list|>
name|releaseList
init|=
literal|null
decl_stmt|;
name|AllocateRequest
name|allocateRequest
init|=
literal|null
decl_stmt|;
name|List
argument_list|<
name|String
argument_list|>
name|blacklistToAdd
init|=
operator|new
name|ArrayList
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
name|List
argument_list|<
name|String
argument_list|>
name|blacklistToRemove
init|=
operator|new
name|ArrayList
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
name|Map
argument_list|<
name|ContainerId
argument_list|,
name|SimpleEntry
argument_list|<
name|Container
argument_list|,
name|UpdateContainerRequest
argument_list|>
argument_list|>
name|oldChange
init|=
operator|new
name|HashMap
argument_list|<>
argument_list|()
decl_stmt|;
name|List
argument_list|<
name|SchedulingRequest
argument_list|>
name|schedulingRequestList
init|=
operator|new
name|LinkedList
argument_list|<>
argument_list|()
decl_stmt|;
try|try
block|{
synchronized|synchronized
init|(
name|this
init|)
block|{
name|askList
operator|=
name|cloneAsks
argument_list|()
expr_stmt|;
comment|// Save the current change for recovery
name|oldChange
operator|.
name|putAll
argument_list|(
name|change
argument_list|)
expr_stmt|;
name|List
argument_list|<
name|UpdateContainerRequest
argument_list|>
name|updateList
init|=
name|createUpdateList
argument_list|()
decl_stmt|;
name|releaseList
operator|=
operator|new
name|ArrayList
argument_list|<
name|ContainerId
argument_list|>
argument_list|(
name|release
argument_list|)
expr_stmt|;
name|schedulingRequestList
operator|=
operator|new
name|ArrayList
argument_list|<>
argument_list|(
name|schedulingRequests
argument_list|)
expr_stmt|;
comment|// optimistically clear this collection assuming no RPC failure
name|ask
operator|.
name|clear
argument_list|()
expr_stmt|;
name|release
operator|.
name|clear
argument_list|()
expr_stmt|;
name|change
operator|.
name|clear
argument_list|()
expr_stmt|;
name|schedulingRequests
operator|.
name|clear
argument_list|()
expr_stmt|;
name|blacklistToAdd
operator|.
name|addAll
argument_list|(
name|blacklistAdditions
argument_list|)
expr_stmt|;
name|blacklistToRemove
operator|.
name|addAll
argument_list|(
name|blacklistRemovals
argument_list|)
expr_stmt|;
name|ResourceBlacklistRequest
name|blacklistRequest
init|=
name|ResourceBlacklistRequest
operator|.
name|newInstance
argument_list|(
name|blacklistToAdd
argument_list|,
name|blacklistToRemove
argument_list|)
decl_stmt|;
name|allocateRequest
operator|=
name|AllocateRequest
operator|.
name|newBuilder
argument_list|()
operator|.
name|responseId
argument_list|(
name|lastResponseId
argument_list|)
operator|.
name|progress
argument_list|(
name|progressIndicator
argument_list|)
operator|.
name|askList
argument_list|(
name|askList
argument_list|)
operator|.
name|resourceBlacklistRequest
argument_list|(
name|blacklistRequest
argument_list|)
operator|.
name|releaseList
argument_list|(
name|releaseList
argument_list|)
operator|.
name|updateRequests
argument_list|(
name|updateList
argument_list|)
operator|.
name|schedulingRequests
argument_list|(
name|schedulingRequestList
argument_list|)
operator|.
name|build
argument_list|()
expr_stmt|;
if|if
condition|(
name|this
operator|.
name|newTrackingUrl
operator|!=
literal|null
condition|)
block|{
name|allocateRequest
operator|.
name|setTrackingUrl
argument_list|(
name|this
operator|.
name|newTrackingUrl
argument_list|)
expr_stmt|;
name|this
operator|.
name|appTrackingUrl
operator|=
name|this
operator|.
name|newTrackingUrl
expr_stmt|;
name|this
operator|.
name|newTrackingUrl
operator|=
literal|null
expr_stmt|;
block|}
comment|// clear blacklistAdditions and blacklistRemovals before
comment|// unsynchronized part
name|blacklistAdditions
operator|.
name|clear
argument_list|()
expr_stmt|;
name|blacklistRemovals
operator|.
name|clear
argument_list|()
expr_stmt|;
block|}
try|try
block|{
name|allocateResponse
operator|=
name|rmClient
operator|.
name|allocate
argument_list|(
name|allocateRequest
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|ApplicationMasterNotRegisteredException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|warn
argument_list|(
literal|"ApplicationMaster is out of sync with ResourceManager,"
operator|+
literal|" hence resyncing."
argument_list|)
expr_stmt|;
synchronized|synchronized
init|(
name|this
init|)
block|{
name|release
operator|.
name|addAll
argument_list|(
name|this
operator|.
name|pendingRelease
argument_list|)
expr_stmt|;
name|blacklistAdditions
operator|.
name|addAll
argument_list|(
name|this
operator|.
name|blacklistedNodes
argument_list|)
expr_stmt|;
for|for
control|(
name|RemoteRequestsTable
name|remoteRequestsTable
range|:
name|remoteRequests
operator|.
name|values
argument_list|()
control|)
block|{
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
name|Iterator
argument_list|<
name|ResourceRequestInfo
argument_list|<
name|T
argument_list|>
argument_list|>
name|reqIter
init|=
name|remoteRequestsTable
operator|.
name|iterator
argument_list|()
decl_stmt|;
while|while
condition|(
name|reqIter
operator|.
name|hasNext
argument_list|()
condition|)
block|{
name|addResourceRequestToAsk
argument_list|(
name|reqIter
operator|.
name|next
argument_list|()
operator|.
name|remoteRequest
argument_list|)
expr_stmt|;
block|}
block|}
name|change
operator|.
name|putAll
argument_list|(
name|this
operator|.
name|pendingChange
argument_list|)
expr_stmt|;
for|for
control|(
name|List
argument_list|<
name|SchedulingRequest
argument_list|>
name|schedReqs
range|:
name|this
operator|.
name|outstandingSchedRequests
operator|.
name|values
argument_list|()
control|)
block|{
name|this
operator|.
name|schedulingRequests
operator|.
name|addAll
argument_list|(
name|schedReqs
argument_list|)
expr_stmt|;
block|}
block|}
comment|// re register with RM
name|registerApplicationMaster
argument_list|()
expr_stmt|;
name|allocateResponse
operator|=
name|allocate
argument_list|(
name|progressIndicator
argument_list|)
expr_stmt|;
return|return
name|allocateResponse
return|;
block|}
synchronized|synchronized
init|(
name|this
init|)
block|{
comment|// update these on successful RPC
name|clusterNodeCount
operator|=
name|allocateResponse
operator|.
name|getNumClusterNodes
argument_list|()
expr_stmt|;
name|lastResponseId
operator|=
name|allocateResponse
operator|.
name|getResponseId
argument_list|()
expr_stmt|;
name|clusterAvailableResources
operator|=
name|allocateResponse
operator|.
name|getAvailableResources
argument_list|()
expr_stmt|;
if|if
condition|(
operator|!
name|allocateResponse
operator|.
name|getNMTokens
argument_list|()
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|populateNMTokens
argument_list|(
name|allocateResponse
operator|.
name|getNMTokens
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|allocateResponse
operator|.
name|getAMRMToken
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|updateAMRMToken
argument_list|(
name|allocateResponse
operator|.
name|getAMRMToken
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
operator|!
name|pendingRelease
operator|.
name|isEmpty
argument_list|()
operator|&&
operator|!
name|allocateResponse
operator|.
name|getCompletedContainersStatuses
argument_list|()
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|removePendingReleaseRequests
argument_list|(
name|allocateResponse
operator|.
name|getCompletedContainersStatuses
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
operator|!
name|pendingChange
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|List
argument_list|<
name|ContainerStatus
argument_list|>
name|completed
init|=
name|allocateResponse
operator|.
name|getCompletedContainersStatuses
argument_list|()
decl_stmt|;
name|List
argument_list|<
name|UpdatedContainer
argument_list|>
name|changed
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
name|changed
operator|.
name|addAll
argument_list|(
name|allocateResponse
operator|.
name|getUpdatedContainers
argument_list|()
argument_list|)
expr_stmt|;
comment|// remove all pending change requests that belong to the completed
comment|// containers
for|for
control|(
name|ContainerStatus
name|status
range|:
name|completed
control|)
block|{
name|ContainerId
name|containerId
init|=
name|status
operator|.
name|getContainerId
argument_list|()
decl_stmt|;
name|pendingChange
operator|.
name|remove
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
block|}
comment|// remove all pending change requests that have been satisfied
if|if
condition|(
operator|!
name|changed
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|removePendingChangeRequests
argument_list|(
name|changed
argument_list|)
expr_stmt|;
block|}
block|}
name|AMRMClientUtils
operator|.
name|removeFromOutstandingSchedulingRequests
argument_list|(
name|allocateResponse
operator|.
name|getAllocatedContainers
argument_list|()
argument_list|,
name|this
operator|.
name|outstandingSchedRequests
argument_list|)
expr_stmt|;
name|AMRMClientUtils
operator|.
name|removeFromOutstandingSchedulingRequests
argument_list|(
name|allocateResponse
operator|.
name|getContainersFromPreviousAttempts
argument_list|()
argument_list|,
name|this
operator|.
name|outstandingSchedRequests
argument_list|)
expr_stmt|;
block|}
block|}
finally|finally
block|{
comment|// TODO how to differentiate remote yarn exception vs error in rpc
if|if
condition|(
name|allocateResponse
operator|==
literal|null
condition|)
block|{
comment|// we hit an exception in allocate()
comment|// preserve ask and release for next call to allocate()
synchronized|synchronized
init|(
name|this
init|)
block|{
name|release
operator|.
name|addAll
argument_list|(
name|releaseList
argument_list|)
expr_stmt|;
comment|// requests could have been added or deleted during call to allocate
comment|// If requests were added/removed then there is nothing to do since
comment|// the ResourceRequest object in ask would have the actual new value.
comment|// If ask does not have this ResourceRequest then it was unchanged and
comment|// so we can add the value back safely.
comment|// This assumes that there will no concurrent calls to allocate() and
comment|// so we dont have to worry about ask being changed in the
comment|// synchronized block at the beginning of this method.
for|for
control|(
name|ResourceRequest
name|oldAsk
range|:
name|askList
control|)
block|{
if|if
condition|(
operator|!
name|ask
operator|.
name|contains
argument_list|(
name|oldAsk
argument_list|)
condition|)
block|{
name|ask
operator|.
name|add
argument_list|(
name|oldAsk
argument_list|)
expr_stmt|;
block|}
block|}
comment|// change requests could have been added during the allocate call.
comment|// Those are the newest requests which take precedence
comment|// over requests cached in the oldChange map.
comment|//
comment|// Only insert entries from the cached oldChange map
comment|// that do not exist in the current change map:
for|for
control|(
name|Map
operator|.
name|Entry
argument_list|<
name|ContainerId
argument_list|,
name|SimpleEntry
argument_list|<
name|Container
argument_list|,
name|UpdateContainerRequest
argument_list|>
argument_list|>
name|entry
range|:
name|oldChange
operator|.
name|entrySet
argument_list|()
control|)
block|{
name|ContainerId
name|oldContainerId
init|=
name|entry
operator|.
name|getKey
argument_list|()
decl_stmt|;
name|Container
name|oldContainer
init|=
name|entry
operator|.
name|getValue
argument_list|()
operator|.
name|getKey
argument_list|()
decl_stmt|;
name|UpdateContainerRequest
name|oldupdate
init|=
name|entry
operator|.
name|getValue
argument_list|()
operator|.
name|getValue
argument_list|()
decl_stmt|;
if|if
condition|(
name|change
operator|.
name|get
argument_list|(
name|oldContainerId
argument_list|)
operator|==
literal|null
condition|)
block|{
name|change
operator|.
name|put
argument_list|(
name|oldContainerId
argument_list|,
operator|new
name|SimpleEntry
argument_list|<>
argument_list|(
name|oldContainer
argument_list|,
name|oldupdate
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
name|blacklistAdditions
operator|.
name|addAll
argument_list|(
name|blacklistToAdd
argument_list|)
expr_stmt|;
name|blacklistRemovals
operator|.
name|addAll
argument_list|(
name|blacklistToRemove
argument_list|)
expr_stmt|;
name|schedulingRequests
operator|.
name|addAll
argument_list|(
name|schedulingRequestList
argument_list|)
expr_stmt|;
block|}
block|}
block|}
return|return
name|allocateResponse
return|;
block|}
DECL|method|createUpdateList ()
specifier|private
name|List
argument_list|<
name|UpdateContainerRequest
argument_list|>
name|createUpdateList
parameter_list|()
block|{
name|List
argument_list|<
name|UpdateContainerRequest
argument_list|>
name|updateList
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
for|for
control|(
name|Map
operator|.
name|Entry
argument_list|<
name|ContainerId
argument_list|,
name|SimpleEntry
argument_list|<
name|Container
argument_list|,
name|UpdateContainerRequest
argument_list|>
argument_list|>
name|entry
range|:
name|change
operator|.
name|entrySet
argument_list|()
control|)
block|{
name|Resource
name|targetCapability
init|=
name|entry
operator|.
name|getValue
argument_list|()
operator|.
name|getValue
argument_list|()
operator|.
name|getCapability
argument_list|()
decl_stmt|;
name|ExecutionType
name|targetExecType
init|=
name|entry
operator|.
name|getValue
argument_list|()
operator|.
name|getValue
argument_list|()
operator|.
name|getExecutionType
argument_list|()
decl_stmt|;
name|ContainerUpdateType
name|updateType
init|=
name|entry
operator|.
name|getValue
argument_list|()
operator|.
name|getValue
argument_list|()
operator|.
name|getContainerUpdateType
argument_list|()
decl_stmt|;
name|int
name|version
init|=
name|entry
operator|.
name|getValue
argument_list|()
operator|.
name|getKey
argument_list|()
operator|.
name|getVersion
argument_list|()
decl_stmt|;
name|updateList
operator|.
name|add
argument_list|(
name|UpdateContainerRequest
operator|.
name|newInstance
argument_list|(
name|version
argument_list|,
name|entry
operator|.
name|getKey
argument_list|()
argument_list|,
name|updateType
argument_list|,
name|targetCapability
argument_list|,
name|targetExecType
argument_list|)
argument_list|)
expr_stmt|;
block|}
return|return
name|updateList
return|;
block|}
DECL|method|cloneAsks ()
specifier|private
name|List
argument_list|<
name|ResourceRequest
argument_list|>
name|cloneAsks
parameter_list|()
block|{
name|List
argument_list|<
name|ResourceRequest
argument_list|>
name|askList
init|=
operator|new
name|ArrayList
argument_list|<
name|ResourceRequest
argument_list|>
argument_list|(
name|ask
operator|.
name|size
argument_list|()
argument_list|)
decl_stmt|;
for|for
control|(
name|ResourceRequest
name|r
range|:
name|ask
control|)
block|{
comment|// create a copy of ResourceRequest as we might change it while the
comment|// RPC layer is using it to send info across
name|askList
operator|.
name|add
argument_list|(
name|ResourceRequest
operator|.
name|clone
argument_list|(
name|r
argument_list|)
argument_list|)
expr_stmt|;
block|}
return|return
name|askList
return|;
block|}
DECL|method|removePendingReleaseRequests ( List<ContainerStatus> completedContainersStatuses)
specifier|protected
name|void
name|removePendingReleaseRequests
parameter_list|(
name|List
argument_list|<
name|ContainerStatus
argument_list|>
name|completedContainersStatuses
parameter_list|)
block|{
for|for
control|(
name|ContainerStatus
name|containerStatus
range|:
name|completedContainersStatuses
control|)
block|{
name|pendingRelease
operator|.
name|remove
argument_list|(
name|containerStatus
operator|.
name|getContainerId
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|removePendingChangeRequests ( List<UpdatedContainer> changedContainers)
specifier|protected
name|void
name|removePendingChangeRequests
parameter_list|(
name|List
argument_list|<
name|UpdatedContainer
argument_list|>
name|changedContainers
parameter_list|)
block|{
for|for
control|(
name|UpdatedContainer
name|changedContainer
range|:
name|changedContainers
control|)
block|{
name|ContainerId
name|containerId
init|=
name|changedContainer
operator|.
name|getContainer
argument_list|()
operator|.
name|getId
argument_list|()
decl_stmt|;
if|if
condition|(
name|pendingChange
operator|.
name|get
argument_list|(
name|containerId
argument_list|)
operator|==
literal|null
condition|)
block|{
continue|continue;
block|}
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"RM has confirmed changed resource allocation for "
operator|+
literal|"container "
operator|+
name|containerId
operator|+
literal|". Current resource allocation:"
operator|+
name|changedContainer
operator|.
name|getContainer
argument_list|()
operator|.
name|getResource
argument_list|()
operator|+
literal|". Remove pending change request:"
operator|+
name|pendingChange
operator|.
name|get
argument_list|(
name|containerId
argument_list|)
operator|.
name|getValue
argument_list|()
argument_list|)
expr_stmt|;
block|}
name|pendingChange
operator|.
name|remove
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Private
annotation|@
name|VisibleForTesting
DECL|method|populateNMTokens (List<NMToken> nmTokens)
specifier|protected
name|void
name|populateNMTokens
parameter_list|(
name|List
argument_list|<
name|NMToken
argument_list|>
name|nmTokens
parameter_list|)
block|{
for|for
control|(
name|NMToken
name|token
range|:
name|nmTokens
control|)
block|{
name|String
name|nodeId
init|=
name|token
operator|.
name|getNodeId
argument_list|()
operator|.
name|toString
argument_list|()
decl_stmt|;
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
if|if
condition|(
name|getNMTokenCache
argument_list|()
operator|.
name|containsToken
argument_list|(
name|nodeId
argument_list|)
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Replacing token for : "
operator|+
name|nodeId
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Received new token for : "
operator|+
name|nodeId
argument_list|)
expr_stmt|;
block|}
block|}
name|getNMTokenCache
argument_list|()
operator|.
name|setToken
argument_list|(
name|nodeId
argument_list|,
name|token
operator|.
name|getToken
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|unregisterApplicationMaster (FinalApplicationStatus appStatus, String appMessage, String appTrackingUrl)
specifier|public
name|void
name|unregisterApplicationMaster
parameter_list|(
name|FinalApplicationStatus
name|appStatus
parameter_list|,
name|String
name|appMessage
parameter_list|,
name|String
name|appTrackingUrl
parameter_list|)
throws|throws
name|YarnException
throws|,
name|IOException
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|appStatus
operator|!=
literal|null
argument_list|,
literal|"AppStatus should not be null."
argument_list|)
expr_stmt|;
name|FinishApplicationMasterRequest
name|request
init|=
name|FinishApplicationMasterRequest
operator|.
name|newInstance
argument_list|(
name|appStatus
argument_list|,
name|appMessage
argument_list|,
name|appTrackingUrl
argument_list|)
decl_stmt|;
try|try
block|{
while|while
condition|(
literal|true
condition|)
block|{
name|FinishApplicationMasterResponse
name|response
init|=
name|rmClient
operator|.
name|finishApplicationMaster
argument_list|(
name|request
argument_list|)
decl_stmt|;
if|if
condition|(
name|response
operator|.
name|getIsUnregistered
argument_list|()
condition|)
block|{
break|break;
block|}
name|LOG
operator|.
name|info
argument_list|(
literal|"Waiting for application to be successfully unregistered."
argument_list|)
expr_stmt|;
name|Thread
operator|.
name|sleep
argument_list|(
literal|100
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|InterruptedException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|info
argument_list|(
literal|"Interrupted while waiting for application"
operator|+
literal|" to be removed from RMStateStore"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|ApplicationMasterNotRegisteredException
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|warn
argument_list|(
literal|"ApplicationMaster is out of sync with ResourceManager,"
operator|+
literal|" hence resyncing."
argument_list|)
expr_stmt|;
comment|// re register with RM
name|registerApplicationMaster
argument_list|()
expr_stmt|;
name|unregisterApplicationMaster
argument_list|(
name|appStatus
argument_list|,
name|appMessage
argument_list|,
name|appTrackingUrl
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|addContainerRequest (T req)
specifier|public
specifier|synchronized
name|void
name|addContainerRequest
parameter_list|(
name|T
name|req
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|req
operator|!=
literal|null
argument_list|,
literal|"Resource request can not be null."
argument_list|)
expr_stmt|;
name|Set
argument_list|<
name|String
argument_list|>
name|dedupedRacks
init|=
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
if|if
condition|(
name|req
operator|.
name|getRacks
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|dedupedRacks
operator|.
name|addAll
argument_list|(
name|req
operator|.
name|getRacks
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|req
operator|.
name|getRacks
argument_list|()
operator|.
name|size
argument_list|()
operator|!=
name|dedupedRacks
operator|.
name|size
argument_list|()
condition|)
block|{
name|Joiner
name|joiner
init|=
name|Joiner
operator|.
name|on
argument_list|(
literal|','
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|warn
argument_list|(
literal|"ContainerRequest has duplicate racks: "
operator|+
name|joiner
operator|.
name|join
argument_list|(
name|req
operator|.
name|getRacks
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
block|}
block|}
name|Set
argument_list|<
name|String
argument_list|>
name|inferredRacks
init|=
name|resolveRacks
argument_list|(
name|req
operator|.
name|getNodes
argument_list|()
argument_list|)
decl_stmt|;
name|inferredRacks
operator|.
name|removeAll
argument_list|(
name|dedupedRacks
argument_list|)
expr_stmt|;
name|Resource
name|resource
init|=
name|checkAndGetResourceProfile
argument_list|(
name|req
operator|.
name|getResourceProfile
argument_list|()
argument_list|,
name|req
operator|.
name|getCapability
argument_list|()
argument_list|)
decl_stmt|;
comment|// check that specific and non-specific requests cannot be mixed within a
comment|// priority
name|checkLocalityRelaxationConflict
argument_list|(
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|,
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|ANY_LIST
argument_list|,
name|req
operator|.
name|getRelaxLocality
argument_list|()
argument_list|)
expr_stmt|;
comment|// check that specific rack cannot be mixed with specific node within a
comment|// priority. If node and its rack are both specified then they must be
comment|// in the same request.
comment|// For explicitly requested racks, we set locality relaxation to true
name|checkLocalityRelaxationConflict
argument_list|(
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|,
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|dedupedRacks
argument_list|,
literal|true
argument_list|)
expr_stmt|;
name|checkLocalityRelaxationConflict
argument_list|(
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|,
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|inferredRacks
argument_list|,
name|req
operator|.
name|getRelaxLocality
argument_list|()
argument_list|)
expr_stmt|;
comment|// check if the node label expression specified is valid
name|checkNodeLabelExpression
argument_list|(
name|req
argument_list|)
expr_stmt|;
if|if
condition|(
name|req
operator|.
name|getNodes
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|HashSet
argument_list|<
name|String
argument_list|>
name|dedupedNodes
init|=
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|(
name|req
operator|.
name|getNodes
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|dedupedNodes
operator|.
name|size
argument_list|()
operator|!=
name|req
operator|.
name|getNodes
argument_list|()
operator|.
name|size
argument_list|()
condition|)
block|{
name|Joiner
name|joiner
init|=
name|Joiner
operator|.
name|on
argument_list|(
literal|','
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|warn
argument_list|(
literal|"ContainerRequest has duplicate nodes: "
operator|+
name|joiner
operator|.
name|join
argument_list|(
name|req
operator|.
name|getNodes
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
block|}
for|for
control|(
name|String
name|node
range|:
name|dedupedNodes
control|)
block|{
name|addResourceRequest
argument_list|(
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|node
argument_list|,
name|req
operator|.
name|getExecutionTypeRequest
argument_list|()
argument_list|,
name|resource
argument_list|,
name|req
argument_list|,
literal|true
argument_list|,
name|req
operator|.
name|getNodeLabelExpression
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
for|for
control|(
name|String
name|rack
range|:
name|dedupedRacks
control|)
block|{
name|addResourceRequest
argument_list|(
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|rack
argument_list|,
name|req
operator|.
name|getExecutionTypeRequest
argument_list|()
argument_list|,
name|resource
argument_list|,
name|req
argument_list|,
literal|true
argument_list|,
name|req
operator|.
name|getNodeLabelExpression
argument_list|()
argument_list|)
expr_stmt|;
block|}
comment|// Ensure node requests are accompanied by requests for
comment|// corresponding rack
for|for
control|(
name|String
name|rack
range|:
name|inferredRacks
control|)
block|{
name|addResourceRequest
argument_list|(
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|rack
argument_list|,
name|req
operator|.
name|getExecutionTypeRequest
argument_list|()
argument_list|,
name|resource
argument_list|,
name|req
argument_list|,
name|req
operator|.
name|getRelaxLocality
argument_list|()
argument_list|,
name|req
operator|.
name|getNodeLabelExpression
argument_list|()
argument_list|)
expr_stmt|;
block|}
comment|// Off-switch
name|addResourceRequest
argument_list|(
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|ResourceRequest
operator|.
name|ANY
argument_list|,
name|req
operator|.
name|getExecutionTypeRequest
argument_list|()
argument_list|,
name|resource
argument_list|,
name|req
argument_list|,
name|req
operator|.
name|getRelaxLocality
argument_list|()
argument_list|,
name|req
operator|.
name|getNodeLabelExpression
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|removeContainerRequest (T req)
specifier|public
specifier|synchronized
name|void
name|removeContainerRequest
parameter_list|(
name|T
name|req
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|req
operator|!=
literal|null
argument_list|,
literal|"Resource request can not be null."
argument_list|)
expr_stmt|;
name|Resource
name|resource
init|=
name|checkAndGetResourceProfile
argument_list|(
name|req
operator|.
name|getResourceProfile
argument_list|()
argument_list|,
name|req
operator|.
name|getCapability
argument_list|()
argument_list|)
decl_stmt|;
name|Set
argument_list|<
name|String
argument_list|>
name|allRacks
init|=
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
if|if
condition|(
name|req
operator|.
name|getRacks
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|allRacks
operator|.
name|addAll
argument_list|(
name|req
operator|.
name|getRacks
argument_list|()
argument_list|)
expr_stmt|;
block|}
name|allRacks
operator|.
name|addAll
argument_list|(
name|resolveRacks
argument_list|(
name|req
operator|.
name|getNodes
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
comment|// Update resource requests
if|if
condition|(
name|req
operator|.
name|getNodes
argument_list|()
operator|!=
literal|null
condition|)
block|{
for|for
control|(
name|String
name|node
range|:
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|(
name|req
operator|.
name|getNodes
argument_list|()
argument_list|)
control|)
block|{
name|decResourceRequest
argument_list|(
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|node
argument_list|,
name|req
operator|.
name|getExecutionTypeRequest
argument_list|()
argument_list|,
name|resource
argument_list|,
name|req
argument_list|)
expr_stmt|;
block|}
block|}
for|for
control|(
name|String
name|rack
range|:
name|allRacks
control|)
block|{
name|decResourceRequest
argument_list|(
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|rack
argument_list|,
name|req
operator|.
name|getExecutionTypeRequest
argument_list|()
argument_list|,
name|resource
argument_list|,
name|req
argument_list|)
expr_stmt|;
block|}
name|decResourceRequest
argument_list|(
name|req
operator|.
name|getPriority
argument_list|()
argument_list|,
name|ResourceRequest
operator|.
name|ANY
argument_list|,
name|req
operator|.
name|getExecutionTypeRequest
argument_list|()
argument_list|,
name|resource
argument_list|,
name|req
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|requestContainerUpdate ( Container container, UpdateContainerRequest updateContainerRequest)
specifier|public
specifier|synchronized
name|void
name|requestContainerUpdate
parameter_list|(
name|Container
name|container
parameter_list|,
name|UpdateContainerRequest
name|updateContainerRequest
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkNotNull
argument_list|(
name|container
argument_list|,
literal|"Container cannot be null!!"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkNotNull
argument_list|(
name|updateContainerRequest
argument_list|,
literal|"UpdateContainerRequest cannot be null!!"
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|info
argument_list|(
literal|"Requesting Container update : "
operator|+
literal|"container="
operator|+
name|container
operator|+
literal|", "
operator|+
literal|"updateType="
operator|+
name|updateContainerRequest
operator|.
name|getContainerUpdateType
argument_list|()
operator|+
literal|", "
operator|+
literal|"targetCapability="
operator|+
name|updateContainerRequest
operator|.
name|getCapability
argument_list|()
operator|+
literal|", "
operator|+
literal|"targetExecType="
operator|+
name|updateContainerRequest
operator|.
name|getExecutionType
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|updateContainerRequest
operator|.
name|getCapability
argument_list|()
operator|!=
literal|null
operator|&&
name|updateContainerRequest
operator|.
name|getExecutionType
argument_list|()
operator|==
literal|null
condition|)
block|{
name|validateContainerResourceChangeRequest
argument_list|(
name|updateContainerRequest
operator|.
name|getContainerUpdateType
argument_list|()
argument_list|,
name|container
operator|.
name|getId
argument_list|()
argument_list|,
name|container
operator|.
name|getResource
argument_list|()
argument_list|,
name|updateContainerRequest
operator|.
name|getCapability
argument_list|()
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|updateContainerRequest
operator|.
name|getExecutionType
argument_list|()
operator|!=
literal|null
operator|&&
name|updateContainerRequest
operator|.
name|getCapability
argument_list|()
operator|==
literal|null
condition|)
block|{
name|validateContainerExecTypeChangeRequest
argument_list|(
name|updateContainerRequest
operator|.
name|getContainerUpdateType
argument_list|()
argument_list|,
name|container
operator|.
name|getId
argument_list|()
argument_list|,
name|container
operator|.
name|getExecutionType
argument_list|()
argument_list|,
name|updateContainerRequest
operator|.
name|getExecutionType
argument_list|()
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|updateContainerRequest
operator|.
name|getExecutionType
argument_list|()
operator|==
literal|null
operator|&&
name|updateContainerRequest
operator|.
name|getCapability
argument_list|()
operator|==
literal|null
condition|)
block|{
throw|throw
operator|new
name|IllegalArgumentException
argument_list|(
literal|"Both target Capability and"
operator|+
literal|"target Execution Type are null"
argument_list|)
throw|;
block|}
else|else
block|{
throw|throw
operator|new
name|IllegalArgumentException
argument_list|(
literal|"Support currently exists only for"
operator|+
literal|" EITHER update of Capability OR update of Execution Type NOT both"
argument_list|)
throw|;
block|}
if|if
condition|(
name|change
operator|.
name|get
argument_list|(
name|container
operator|.
name|getId
argument_list|()
argument_list|)
operator|==
literal|null
condition|)
block|{
name|change
operator|.
name|put
argument_list|(
name|container
operator|.
name|getId
argument_list|()
argument_list|,
operator|new
name|SimpleEntry
argument_list|<>
argument_list|(
name|container
argument_list|,
name|updateContainerRequest
argument_list|)
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|change
operator|.
name|get
argument_list|(
name|container
operator|.
name|getId
argument_list|()
argument_list|)
operator|.
name|setValue
argument_list|(
name|updateContainerRequest
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|pendingChange
operator|.
name|get
argument_list|(
name|container
operator|.
name|getId
argument_list|()
argument_list|)
operator|==
literal|null
condition|)
block|{
name|pendingChange
operator|.
name|put
argument_list|(
name|container
operator|.
name|getId
argument_list|()
argument_list|,
operator|new
name|SimpleEntry
argument_list|<>
argument_list|(
name|container
argument_list|,
name|updateContainerRequest
argument_list|)
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|pendingChange
operator|.
name|get
argument_list|(
name|container
operator|.
name|getId
argument_list|()
argument_list|)
operator|.
name|setValue
argument_list|(
name|updateContainerRequest
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|releaseAssignedContainer (ContainerId containerId)
specifier|public
specifier|synchronized
name|void
name|releaseAssignedContainer
parameter_list|(
name|ContainerId
name|containerId
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|containerId
operator|!=
literal|null
argument_list|,
literal|"ContainerId can not be null."
argument_list|)
expr_stmt|;
name|pendingRelease
operator|.
name|add
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
name|release
operator|.
name|add
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
name|pendingChange
operator|.
name|remove
argument_list|(
name|containerId
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getAvailableResources ()
specifier|public
specifier|synchronized
name|Resource
name|getAvailableResources
parameter_list|()
block|{
return|return
name|clusterAvailableResources
return|;
block|}
annotation|@
name|Override
DECL|method|getClusterNodeCount ()
specifier|public
specifier|synchronized
name|int
name|getClusterNodeCount
parameter_list|()
block|{
return|return
name|clusterNodeCount
return|;
block|}
annotation|@
name|Override
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
DECL|method|getMatchingRequests (long allocationRequestId)
specifier|public
name|Collection
argument_list|<
name|T
argument_list|>
name|getMatchingRequests
parameter_list|(
name|long
name|allocationRequestId
parameter_list|)
block|{
name|RemoteRequestsTable
name|remoteRequestsTable
init|=
name|getTable
argument_list|(
name|allocationRequestId
argument_list|)
decl_stmt|;
name|LinkedHashSet
argument_list|<
name|T
argument_list|>
name|list
init|=
operator|new
name|LinkedHashSet
argument_list|<>
argument_list|()
decl_stmt|;
if|if
condition|(
name|remoteRequestsTable
operator|!=
literal|null
condition|)
block|{
name|Iterator
argument_list|<
name|ResourceRequestInfo
argument_list|<
name|T
argument_list|>
argument_list|>
name|reqIter
init|=
name|remoteRequestsTable
operator|.
name|iterator
argument_list|()
decl_stmt|;
while|while
condition|(
name|reqIter
operator|.
name|hasNext
argument_list|()
condition|)
block|{
name|ResourceRequestInfo
argument_list|<
name|T
argument_list|>
name|resReqInfo
init|=
name|reqIter
operator|.
name|next
argument_list|()
decl_stmt|;
name|list
operator|.
name|addAll
argument_list|(
name|resReqInfo
operator|.
name|containerRequests
argument_list|)
expr_stmt|;
block|}
block|}
return|return
name|list
return|;
block|}
annotation|@
name|Override
DECL|method|getMatchingRequests ( Priority priority, String resourceName, Resource capability)
specifier|public
specifier|synchronized
name|List
argument_list|<
name|?
extends|extends
name|Collection
argument_list|<
name|T
argument_list|>
argument_list|>
name|getMatchingRequests
parameter_list|(
name|Priority
name|priority
parameter_list|,
name|String
name|resourceName
parameter_list|,
name|Resource
name|capability
parameter_list|)
block|{
return|return
name|getMatchingRequests
argument_list|(
name|priority
argument_list|,
name|resourceName
argument_list|,
name|ExecutionType
operator|.
name|GUARANTEED
argument_list|,
name|capability
argument_list|)
return|;
block|}
annotation|@
name|Override
DECL|method|getMatchingRequests (Priority priority, String resourceName, ExecutionType executionType, Resource capability, String profile)
specifier|public
name|List
argument_list|<
name|?
extends|extends
name|Collection
argument_list|<
name|T
argument_list|>
argument_list|>
name|getMatchingRequests
parameter_list|(
name|Priority
name|priority
parameter_list|,
name|String
name|resourceName
parameter_list|,
name|ExecutionType
name|executionType
parameter_list|,
name|Resource
name|capability
parameter_list|,
name|String
name|profile
parameter_list|)
block|{
name|capability
operator|=
name|checkAndGetResourceProfile
argument_list|(
name|profile
argument_list|,
name|capability
argument_list|)
expr_stmt|;
return|return
name|getMatchingRequests
argument_list|(
name|priority
argument_list|,
name|resourceName
argument_list|,
name|executionType
argument_list|,
name|capability
argument_list|)
return|;
block|}
annotation|@
name|Override
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
DECL|method|getMatchingRequests ( Priority priority, String resourceName, ExecutionType executionType, Resource capability)
specifier|public
specifier|synchronized
name|List
argument_list|<
name|?
extends|extends
name|Collection
argument_list|<
name|T
argument_list|>
argument_list|>
name|getMatchingRequests
parameter_list|(
name|Priority
name|priority
parameter_list|,
name|String
name|resourceName
parameter_list|,
name|ExecutionType
name|executionType
parameter_list|,
name|Resource
name|capability
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|capability
operator|!=
literal|null
argument_list|,
literal|"The Resource to be requested should not be null "
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|priority
operator|!=
literal|null
argument_list|,
literal|"The priority at which to request containers should not be null "
argument_list|)
expr_stmt|;
name|List
argument_list|<
name|LinkedHashSet
argument_list|<
name|T
argument_list|>
argument_list|>
name|list
init|=
operator|new
name|LinkedList
argument_list|<>
argument_list|()
decl_stmt|;
name|RemoteRequestsTable
name|remoteRequestsTable
init|=
name|getTable
argument_list|(
literal|0
argument_list|)
decl_stmt|;
if|if
condition|(
literal|null
operator|!=
name|remoteRequestsTable
condition|)
block|{
name|List
argument_list|<
name|ResourceRequestInfo
argument_list|<
name|T
argument_list|>
argument_list|>
name|matchingRequests
init|=
name|remoteRequestsTable
operator|.
name|getMatchingRequests
argument_list|(
name|priority
argument_list|,
name|resourceName
argument_list|,
name|executionType
argument_list|,
name|capability
argument_list|)
decl_stmt|;
if|if
condition|(
literal|null
operator|!=
name|matchingRequests
condition|)
block|{
comment|// If no exact match. Container may be larger than what was requested.
comment|// get all resources<= capability. map is reverse sorted.
for|for
control|(
name|ResourceRequestInfo
argument_list|<
name|T
argument_list|>
name|resReqInfo
range|:
name|matchingRequests
control|)
block|{
if|if
condition|(
name|Resources
operator|.
name|fitsIn
argument_list|(
name|resReqInfo
operator|.
name|remoteRequest
operator|.
name|getCapability
argument_list|()
argument_list|,
name|capability
argument_list|)
operator|&&
operator|!
name|resReqInfo
operator|.
name|containerRequests
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
name|list
operator|.
name|add
argument_list|(
name|resReqInfo
operator|.
name|containerRequests
argument_list|)
expr_stmt|;
block|}
block|}
block|}
block|}
comment|// no match found
return|return
name|list
return|;
block|}
DECL|method|resolveRacks (List<String> nodes)
specifier|private
name|Set
argument_list|<
name|String
argument_list|>
name|resolveRacks
parameter_list|(
name|List
argument_list|<
name|String
argument_list|>
name|nodes
parameter_list|)
block|{
name|Set
argument_list|<
name|String
argument_list|>
name|racks
init|=
operator|new
name|HashSet
argument_list|<
name|String
argument_list|>
argument_list|()
decl_stmt|;
if|if
condition|(
name|nodes
operator|!=
literal|null
condition|)
block|{
name|List
argument_list|<
name|Node
argument_list|>
name|tmpList
init|=
name|RackResolver
operator|.
name|resolve
argument_list|(
name|nodes
argument_list|)
decl_stmt|;
for|for
control|(
name|Node
name|node
range|:
name|tmpList
control|)
block|{
name|String
name|rack
init|=
name|node
operator|.
name|getNetworkLocation
argument_list|()
decl_stmt|;
comment|// Ensure node requests are accompanied by requests for
comment|// corresponding rack
if|if
condition|(
name|rack
operator|==
literal|null
condition|)
block|{
name|LOG
operator|.
name|warn
argument_list|(
literal|"Failed to resolve rack for node "
operator|+
name|node
operator|+
literal|"."
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|racks
operator|.
name|add
argument_list|(
name|rack
argument_list|)
expr_stmt|;
block|}
block|}
block|}
return|return
name|racks
return|;
block|}
comment|/** * ContainerRequests with locality relaxation cannot be made at the same * priority as ContainerRequests without locality relaxation. */
DECL|method|checkLocalityRelaxationConflict (Long allocationReqId, Priority priority, Collection<String> locations, boolean relaxLocality)
specifier|private
name|void
name|checkLocalityRelaxationConflict
parameter_list|(
name|Long
name|allocationReqId
parameter_list|,
name|Priority
name|priority
parameter_list|,
name|Collection
argument_list|<
name|String
argument_list|>
name|locations
parameter_list|,
name|boolean
name|relaxLocality
parameter_list|)
block|{
comment|// Locality relaxation will be set to relaxLocality for all implicitly
comment|// requested racks. Make sure that existing rack requests match this.
name|RemoteRequestsTable
argument_list|<
name|T
argument_list|>
name|remoteRequestsTable
init|=
name|getTable
argument_list|(
name|allocationReqId
argument_list|)
decl_stmt|;
if|if
condition|(
name|remoteRequestsTable
operator|!=
literal|null
condition|)
block|{
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
name|List
argument_list|<
name|ResourceRequestInfo
argument_list|>
name|allCapabilityMaps
init|=
name|remoteRequestsTable
operator|.
name|getAllResourceRequestInfos
argument_list|(
name|priority
argument_list|,
name|locations
argument_list|)
decl_stmt|;
for|for
control|(
name|ResourceRequestInfo
name|reqs
range|:
name|allCapabilityMaps
control|)
block|{
name|ResourceRequest
name|remoteRequest
init|=
name|reqs
operator|.
name|remoteRequest
decl_stmt|;
name|boolean
name|existingRelaxLocality
init|=
name|remoteRequest
operator|.
name|getRelaxLocality
argument_list|()
decl_stmt|;
if|if
condition|(
name|relaxLocality
operator|!=
name|existingRelaxLocality
condition|)
block|{
throw|throw
operator|new
name|InvalidContainerRequestException
argument_list|(
literal|"Cannot submit a "
operator|+
literal|"ContainerRequest asking for location "
operator|+
name|remoteRequest
operator|.
name|getResourceName
argument_list|()
operator|+
literal|" with locality relaxation "
operator|+
name|relaxLocality
operator|+
literal|" when it has already been requested"
operator|+
literal|"with locality relaxation "
operator|+
name|existingRelaxLocality
argument_list|)
throw|;
block|}
block|}
block|}
block|}
comment|// When profile and override resource are specified at the same time, override
comment|// predefined resource value in profile if any resource type has a positive
comment|// value.
DECL|method|checkAndGetResourceProfile (String profile, Resource overrideResource)
specifier|private
name|Resource
name|checkAndGetResourceProfile
parameter_list|(
name|String
name|profile
parameter_list|,
name|Resource
name|overrideResource
parameter_list|)
block|{
name|Resource
name|returnResource
init|=
name|overrideResource
decl_stmt|;
comment|// if application requested a non-empty/null profile, and the
if|if
condition|(
name|profile
operator|!=
literal|null
operator|&&
operator|!
name|profile
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
if|if
condition|(
name|resourceProfilesMap
operator|==
literal|null
operator|||
operator|(
operator|!
name|resourceProfilesMap
operator|.
name|containsKey
argument_list|(
name|profile
argument_list|)
operator|)
condition|)
block|{
throw|throw
operator|new
name|InvalidContainerRequestException
argument_list|(
literal|"Invalid profile name specified="
operator|+
name|profile
operator|+
operator|(
name|resourceProfilesMap
operator|==
literal|null
condition|?
literal|""
else|:
operator|(
literal|", valid profile names are "
operator|+
name|resourceProfilesMap
operator|.
name|keySet
argument_list|()
operator|)
operator|)
argument_list|)
throw|;
block|}
name|returnResource
operator|=
name|Resources
operator|.
name|clone
argument_list|(
name|resourceProfilesMap
operator|.
name|get
argument_list|(
name|profile
argument_list|)
argument_list|)
expr_stmt|;
for|for
control|(
name|ResourceInformation
name|info
range|:
name|overrideResource
operator|.
name|getAllResourcesListCopy
argument_list|()
control|)
block|{
if|if
condition|(
name|info
operator|.
name|getValue
argument_list|()
operator|>
literal|0
condition|)
block|{
name|returnResource
operator|.
name|setResourceInformation
argument_list|(
name|info
operator|.
name|getName
argument_list|()
argument_list|,
name|info
argument_list|)
expr_stmt|;
block|}
block|}
block|}
return|return
name|returnResource
return|;
block|}
comment|/** * Valid if a node label expression specified on container request is valid or * not * * @param containerRequest */
DECL|method|checkNodeLabelExpression (T containerRequest)
specifier|private
name|void
name|checkNodeLabelExpression
parameter_list|(
name|T
name|containerRequest
parameter_list|)
block|{
name|String
name|exp
init|=
name|containerRequest
operator|.
name|getNodeLabelExpression
argument_list|()
decl_stmt|;
if|if
condition|(
literal|null
operator|==
name|exp
operator|||
name|exp
operator|.
name|isEmpty
argument_list|()
condition|)
block|{
return|return;
block|}
comment|// Don't support specifying> 1 node labels in a node label expression now
if|if
condition|(
name|exp
operator|.
name|contains
argument_list|(
literal|"&&"
argument_list|)
operator|||
name|exp
operator|.
name|contains
argument_list|(
literal|"||"
argument_list|)
condition|)
block|{
throw|throw
operator|new
name|InvalidContainerRequestException
argument_list|(
literal|"Cannot specify more than one node label"
operator|+
literal|" in a single node label expression"
argument_list|)
throw|;
block|}
block|}
DECL|method|validateContainerResourceChangeRequest ( ContainerUpdateType updateType, ContainerId containerId, Resource original, Resource target)
specifier|private
name|void
name|validateContainerResourceChangeRequest
parameter_list|(
name|ContainerUpdateType
name|updateType
parameter_list|,
name|ContainerId
name|containerId
parameter_list|,
name|Resource
name|original
parameter_list|,
name|Resource
name|target
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|containerId
operator|!=
literal|null
argument_list|,
literal|"ContainerId cannot be null"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|original
operator|!=
literal|null
argument_list|,
literal|"Original resource capability cannot be null"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
operator|!
name|Resources
operator|.
name|equals
argument_list|(
name|Resources
operator|.
name|none
argument_list|()
argument_list|,
name|original
argument_list|)
operator|&&
name|Resources
operator|.
name|fitsIn
argument_list|(
name|Resources
operator|.
name|none
argument_list|()
argument_list|,
name|original
argument_list|)
argument_list|,
literal|"Original resource capability must be greater than 0"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|target
operator|!=
literal|null
argument_list|,
literal|"Target resource capability cannot be null"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
operator|!
name|Resources
operator|.
name|equals
argument_list|(
name|Resources
operator|.
name|none
argument_list|()
argument_list|,
name|target
argument_list|)
operator|&&
name|Resources
operator|.
name|fitsIn
argument_list|(
name|Resources
operator|.
name|none
argument_list|()
argument_list|,
name|target
argument_list|)
argument_list|,
literal|"Target resource capability must be greater than 0"
argument_list|)
expr_stmt|;
if|if
condition|(
name|ContainerUpdateType
operator|.
name|DECREASE_RESOURCE
operator|==
name|updateType
condition|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|Resources
operator|.
name|fitsIn
argument_list|(
name|target
argument_list|,
name|original
argument_list|)
argument_list|,
literal|"Target resource capability must fit in Original capability"
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|Resources
operator|.
name|fitsIn
argument_list|(
name|original
argument_list|,
name|target
argument_list|)
argument_list|,
literal|"Target resource capability must be more than Original capability"
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|validateContainerExecTypeChangeRequest ( ContainerUpdateType updateType, ContainerId containerId, ExecutionType original, ExecutionType target)
specifier|private
name|void
name|validateContainerExecTypeChangeRequest
parameter_list|(
name|ContainerUpdateType
name|updateType
parameter_list|,
name|ContainerId
name|containerId
parameter_list|,
name|ExecutionType
name|original
parameter_list|,
name|ExecutionType
name|target
parameter_list|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|containerId
operator|!=
literal|null
argument_list|,
literal|"ContainerId cannot be null"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|original
operator|!=
literal|null
argument_list|,
literal|"Original Execution Type cannot be null"
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|target
operator|!=
literal|null
argument_list|,
literal|"Target Execution Type cannot be null"
argument_list|)
expr_stmt|;
if|if
condition|(
name|ContainerUpdateType
operator|.
name|DEMOTE_EXECUTION_TYPE
operator|==
name|updateType
condition|)
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|target
operator|==
name|ExecutionType
operator|.
name|OPPORTUNISTIC
operator|&&
name|original
operator|==
name|ExecutionType
operator|.
name|GUARANTEED
argument_list|,
literal|"Incorrect Container update request, target should be"
operator|+
literal|" OPPORTUNISTIC and original should be GUARANTEED"
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|target
operator|==
name|ExecutionType
operator|.
name|GUARANTEED
operator|&&
name|original
operator|==
name|ExecutionType
operator|.
name|OPPORTUNISTIC
argument_list|,
literal|"Incorrect Container update request, target should be"
operator|+
literal|" GUARANTEED and original should be OPPORTUNISTIC"
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|addResourceRequestToAsk (ResourceRequest remoteRequest)
specifier|private
name|void
name|addResourceRequestToAsk
parameter_list|(
name|ResourceRequest
name|remoteRequest
parameter_list|)
block|{
comment|// This code looks weird but is needed because of the following scenario.
comment|// A ResourceRequest is removed from the remoteRequestTable. A 0 container
comment|// request is added to 'ask' to notify the RM about not needing it any more.
comment|// Before the call to allocate, the user now requests more containers. If
comment|// the locations of the 0 size request and the new request are the same
comment|// (with the difference being only container count), then the set comparator
comment|// will consider both to be the same and not add the new request to ask. So
comment|// we need to check for the "same" request being present and remove it and
comment|// then add it back. The comparator is container count agnostic.
comment|// This should happen only rarely but we do need to guard against it.
if|if
condition|(
name|ask
operator|.
name|contains
argument_list|(
name|remoteRequest
argument_list|)
condition|)
block|{
name|ask
operator|.
name|remove
argument_list|(
name|remoteRequest
argument_list|)
expr_stmt|;
block|}
name|ask
operator|.
name|add
argument_list|(
name|remoteRequest
argument_list|)
expr_stmt|;
block|}
DECL|method|addResourceRequest (Priority priority, String resourceName, ExecutionTypeRequest execTypeReq, Resource capability, T req, boolean relaxLocality, String labelExpression)
specifier|private
name|void
name|addResourceRequest
parameter_list|(
name|Priority
name|priority
parameter_list|,
name|String
name|resourceName
parameter_list|,
name|ExecutionTypeRequest
name|execTypeReq
parameter_list|,
name|Resource
name|capability
parameter_list|,
name|T
name|req
parameter_list|,
name|boolean
name|relaxLocality
parameter_list|,
name|String
name|labelExpression
parameter_list|)
block|{
name|RemoteRequestsTable
argument_list|<
name|T
argument_list|>
name|remoteRequestsTable
init|=
name|getTable
argument_list|(
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|remoteRequestsTable
operator|==
literal|null
condition|)
block|{
name|remoteRequestsTable
operator|=
operator|new
name|RemoteRequestsTable
argument_list|<>
argument_list|()
expr_stmt|;
name|putTable
argument_list|(
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|,
name|remoteRequestsTable
argument_list|)
expr_stmt|;
block|}
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
name|ResourceRequestInfo
name|resourceRequestInfo
init|=
name|remoteRequestsTable
operator|.
name|addResourceRequest
argument_list|(
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|,
name|priority
argument_list|,
name|resourceName
argument_list|,
name|execTypeReq
argument_list|,
name|capability
argument_list|,
name|req
argument_list|,
name|relaxLocality
argument_list|,
name|labelExpression
argument_list|)
decl_stmt|;
comment|// Note this down for next interaction with ResourceManager
name|addResourceRequestToAsk
argument_list|(
name|resourceRequestInfo
operator|.
name|remoteRequest
argument_list|)
expr_stmt|;
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Adding request to ask "
operator|+
name|resourceRequestInfo
operator|.
name|remoteRequest
argument_list|)
expr_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"addResourceRequest:"
operator|+
literal|" applicationId="
operator|+
literal|" priority="
operator|+
name|priority
operator|.
name|getPriority
argument_list|()
operator|+
literal|" resourceName="
operator|+
name|resourceName
operator|+
literal|" numContainers="
operator|+
name|resourceRequestInfo
operator|.
name|remoteRequest
operator|.
name|getNumContainers
argument_list|()
operator|+
literal|" #asks="
operator|+
name|ask
operator|.
name|size
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
DECL|method|decResourceRequest (Priority priority, String resourceName, ExecutionTypeRequest execTypeReq, Resource capability, T req)
specifier|private
name|void
name|decResourceRequest
parameter_list|(
name|Priority
name|priority
parameter_list|,
name|String
name|resourceName
parameter_list|,
name|ExecutionTypeRequest
name|execTypeReq
parameter_list|,
name|Resource
name|capability
parameter_list|,
name|T
name|req
parameter_list|)
block|{
name|RemoteRequestsTable
argument_list|<
name|T
argument_list|>
name|remoteRequestsTable
init|=
name|getTable
argument_list|(
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|)
decl_stmt|;
if|if
condition|(
name|remoteRequestsTable
operator|!=
literal|null
condition|)
block|{
annotation|@
name|SuppressWarnings
argument_list|(
literal|"unchecked"
argument_list|)
name|ResourceRequestInfo
name|resourceRequestInfo
init|=
name|remoteRequestsTable
operator|.
name|decResourceRequest
argument_list|(
name|priority
argument_list|,
name|resourceName
argument_list|,
name|execTypeReq
argument_list|,
name|capability
argument_list|,
name|req
argument_list|)
decl_stmt|;
comment|// send the ResourceRequest to RM even if is 0 because it needs to
comment|// override a previously sent value. If ResourceRequest was not sent
comment|// previously then sending 0 aught to be a no-op on RM
if|if
condition|(
name|resourceRequestInfo
operator|!=
literal|null
condition|)
block|{
name|addResourceRequestToAsk
argument_list|(
name|resourceRequestInfo
operator|.
name|remoteRequest
argument_list|)
expr_stmt|;
comment|// delete entry from map if no longer needed
if|if
condition|(
name|resourceRequestInfo
operator|.
name|remoteRequest
operator|.
name|getNumContainers
argument_list|()
operator|==
literal|0
condition|)
block|{
name|remoteRequestsTable
operator|.
name|remove
argument_list|(
name|priority
argument_list|,
name|resourceName
argument_list|,
name|execTypeReq
operator|.
name|getExecutionType
argument_list|()
argument_list|,
name|capability
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"AFTER decResourceRequest:"
operator|+
literal|" allocationRequestId="
operator|+
name|req
operator|.
name|getAllocationRequestId
argument_list|()
operator|+
literal|" priority="
operator|+
name|priority
operator|.
name|getPriority
argument_list|()
operator|+
literal|" resourceName="
operator|+
name|resourceName
operator|+
literal|" numContainers="
operator|+
name|resourceRequestInfo
operator|.
name|remoteRequest
operator|.
name|getNumContainers
argument_list|()
operator|+
literal|" #asks="
operator|+
name|ask
operator|.
name|size
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
block|}
else|else
block|{
name|LOG
operator|.
name|info
argument_list|(
literal|"No remoteRequestTable found with allocationRequestId="
operator|+
name|req
operator|.
name|getAllocationRequestId
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|updateBlacklist (List<String> blacklistAdditions, List<String> blacklistRemovals)
specifier|public
specifier|synchronized
name|void
name|updateBlacklist
parameter_list|(
name|List
argument_list|<
name|String
argument_list|>
name|blacklistAdditions
parameter_list|,
name|List
argument_list|<
name|String
argument_list|>
name|blacklistRemovals
parameter_list|)
block|{
if|if
condition|(
name|blacklistAdditions
operator|!=
literal|null
condition|)
block|{
name|this
operator|.
name|blacklistAdditions
operator|.
name|addAll
argument_list|(
name|blacklistAdditions
argument_list|)
expr_stmt|;
name|this
operator|.
name|blacklistedNodes
operator|.
name|addAll
argument_list|(
name|blacklistAdditions
argument_list|)
expr_stmt|;
comment|// if some resources are also in blacklistRemovals updated before, we
comment|// should remove them here.
name|this
operator|.
name|blacklistRemovals
operator|.
name|removeAll
argument_list|(
name|blacklistAdditions
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|blacklistRemovals
operator|!=
literal|null
condition|)
block|{
name|this
operator|.
name|blacklistRemovals
operator|.
name|addAll
argument_list|(
name|blacklistRemovals
argument_list|)
expr_stmt|;
name|this
operator|.
name|blacklistedNodes
operator|.
name|removeAll
argument_list|(
name|blacklistRemovals
argument_list|)
expr_stmt|;
comment|// if some resources are in blacklistAdditions before, we should remove
comment|// them here.
name|this
operator|.
name|blacklistAdditions
operator|.
name|removeAll
argument_list|(
name|blacklistRemovals
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|blacklistAdditions
operator|!=
literal|null
operator|&&
name|blacklistRemovals
operator|!=
literal|null
operator|&&
name|blacklistAdditions
operator|.
name|removeAll
argument_list|(
name|blacklistRemovals
argument_list|)
condition|)
block|{
comment|// we allow resources to appear in addition list and removal list in the
comment|// same invocation of updateBlacklist(), but should get a warn here.
name|LOG
operator|.
name|warn
argument_list|(
literal|"The same resources appear in both blacklistAdditions and "
operator|+
literal|"blacklistRemovals in updateBlacklist."
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Override
DECL|method|updateTrackingUrl (String trackingUrl)
specifier|public
specifier|synchronized
name|void
name|updateTrackingUrl
parameter_list|(
name|String
name|trackingUrl
parameter_list|)
block|{
name|this
operator|.
name|newTrackingUrl
operator|=
name|trackingUrl
expr_stmt|;
block|}
DECL|method|updateAMRMToken (Token token)
specifier|private
name|void
name|updateAMRMToken
parameter_list|(
name|Token
name|token
parameter_list|)
throws|throws
name|IOException
block|{
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|Token
argument_list|<
name|AMRMTokenIdentifier
argument_list|>
name|amrmToken
init|=
operator|new
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|Token
argument_list|<
name|AMRMTokenIdentifier
argument_list|>
argument_list|(
name|token
operator|.
name|getIdentifier
argument_list|()
operator|.
name|array
argument_list|()
argument_list|,
name|token
operator|.
name|getPassword
argument_list|()
operator|.
name|array
argument_list|()
argument_list|,
operator|new
name|Text
argument_list|(
name|token
operator|.
name|getKind
argument_list|()
argument_list|)
argument_list|,
operator|new
name|Text
argument_list|(
name|token
operator|.
name|getService
argument_list|()
argument_list|)
argument_list|)
decl_stmt|;
comment|// Preserve the token service sent by the RM when adding the token
comment|// to ensure we replace the previous token setup by the RM.
comment|// Afterwards we can update the service address for the RPC layer.
name|UserGroupInformation
name|currentUGI
init|=
name|UserGroupInformation
operator|.
name|getCurrentUser
argument_list|()
decl_stmt|;
name|currentUGI
operator|.
name|addToken
argument_list|(
name|amrmToken
argument_list|)
expr_stmt|;
name|amrmToken
operator|.
name|setService
argument_list|(
name|ClientRMProxy
operator|.
name|getAMRMTokenService
argument_list|(
name|getConfig
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
block|}
annotation|@
name|VisibleForTesting
DECL|method|getTable (long allocationRequestId)
name|RemoteRequestsTable
argument_list|<
name|T
argument_list|>
name|getTable
parameter_list|(
name|long
name|allocationRequestId
parameter_list|)
block|{
return|return
name|remoteRequests
operator|.
name|get
argument_list|(
name|Long
operator|.
name|valueOf
argument_list|(
name|allocationRequestId
argument_list|)
argument_list|)
return|;
block|}
annotation|@
name|VisibleForTesting
DECL|method|getOutstandingSchedRequests ()
name|Map
argument_list|<
name|Set
argument_list|<
name|String
argument_list|>
argument_list|,
name|List
argument_list|<
name|SchedulingRequest
argument_list|>
argument_list|>
name|getOutstandingSchedRequests
parameter_list|()
block|{
return|return
name|outstandingSchedRequests
return|;
block|}
DECL|method|putTable (long allocationRequestId, RemoteRequestsTable<T> table)
name|RemoteRequestsTable
argument_list|<
name|T
argument_list|>
name|putTable
parameter_list|(
name|long
name|allocationRequestId
parameter_list|,
name|RemoteRequestsTable
argument_list|<
name|T
argument_list|>
name|table
parameter_list|)
block|{
return|return
name|remoteRequests
operator|.
name|put
argument_list|(
name|Long
operator|.
name|valueOf
argument_list|(
name|allocationRequestId
argument_list|)
argument_list|,
name|table
argument_list|)
return|;
block|}
block|}
end_class
end_unit
|
amessier/xenia
|
src/xenia/gpu/vulkan/shaders/bytecode/vulkan_spirv/point_list_gs.h
|
// Generated with `xb buildshaders`.
#if 0
; SPIR-V
; Version: 1.0
; Generator: Khronos Glslang Reference Front End; 10
; Bound: 24916
; Schema: 0
OpCapability Geometry
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Geometry %5663 "main" %5305 %4065 %4930 %5430 %3302 %5753 %5479
OpExecutionMode %5663 InputPoints
OpExecutionMode %5663 Invocations 1
OpExecutionMode %5663 OutputTriangleStrip
OpExecutionMode %5663 OutputVertices 4
OpMemberDecorate %_struct_1017 0 BuiltIn Position
OpDecorate %_struct_1017 Block
OpMemberDecorate %_struct_1287 0 Offset 0
OpMemberDecorate %_struct_1287 1 Offset 16
OpMemberDecorate %_struct_1287 2 Offset 32
OpMemberDecorate %_struct_1287 3 Offset 48
OpMemberDecorate %_struct_1287 4 Offset 64
OpDecorate %_struct_1287 Block
OpDecorate %4065 Location 17
OpMemberDecorate %_struct_1018 0 BuiltIn Position
OpDecorate %_struct_1018 Block
OpDecorate %5430 Location 0
OpDecorate %3302 Location 0
OpDecorate %5753 Location 16
OpDecorate %5479 Location 16
%void = OpTypeVoid
%1282 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_struct_1017 = OpTypeStruct %v4float
%uint = OpTypeInt 32 0
%uint_1 = OpConstant %uint 1
%_arr__struct_1017_uint_1 = OpTypeArray %_struct_1017 %uint_1
%_ptr_Input__arr__struct_1017_uint_1 = OpTypePointer Input %_arr__struct_1017_uint_1
%5305 = OpVariable %_ptr_Input__arr__struct_1017_uint_1 Input
%int = OpTypeInt 32 1
%int_0 = OpConstant %int 0
%_ptr_Input_v4float = OpTypePointer Input %v4float
%v2float = OpTypeVector %float 2
%_ptr_Function_v2float = OpTypePointer Function %v2float
%_struct_1287 = OpTypeStruct %v4float %v4float %v4float %v4float %uint
%_ptr_PushConstant__struct_1287 = OpTypePointer PushConstant %_struct_1287
%3463 = OpVariable %_ptr_PushConstant__struct_1287 PushConstant
%int_2 = OpConstant %int 2
%_ptr_PushConstant_v4float = OpTypePointer PushConstant %v4float
%_arr_float_uint_1 = OpTypeArray %float %uint_1
%_ptr_Input__arr_float_uint_1 = OpTypePointer Input %_arr_float_uint_1
%4065 = OpVariable %_ptr_Input__arr_float_uint_1 Input
%_ptr_Input_float = OpTypePointer Input %float
%float_0 = OpConstant %float 0
%bool = OpTypeBool
%int_4 = OpConstant %int 4
%_struct_1018 = OpTypeStruct %v4float
%_ptr_Output__struct_1018 = OpTypePointer Output %_struct_1018
%4930 = OpVariable %_ptr_Output__struct_1018 Output
%uint_4 = OpConstant %uint 4
%_arr_v2float_uint_4 = OpTypeArray %v2float %uint_4
%float_n1 = OpConstant %float -1
%float_1 = OpConstant %float 1
%73 = OpConstantComposite %v2float %float_n1 %float_1
%768 = OpConstantComposite %v2float %float_1 %float_1
%74 = OpConstantComposite %v2float %float_n1 %float_n1
%769 = OpConstantComposite %v2float %float_1 %float_n1
%2941 = OpConstantComposite %_arr_v2float_uint_4 %73 %768 %74 %769
%_ptr_Function__arr_v2float_uint_4 = OpTypePointer Function %_arr_v2float_uint_4
%_ptr_Output_v4float = OpTypePointer Output %v4float
%uint_16 = OpConstant %uint 16
%_arr_v4float_uint_16 = OpTypeArray %v4float %uint_16
%_ptr_Output__arr_v4float_uint_16 = OpTypePointer Output %_arr_v4float_uint_16
%5430 = OpVariable %_ptr_Output__arr_v4float_uint_16 Output
%_arr__arr_v4float_uint_16_uint_1 = OpTypeArray %_arr_v4float_uint_16 %uint_1
%_ptr_Input__arr__arr_v4float_uint_16_uint_1 = OpTypePointer Input %_arr__arr_v4float_uint_16_uint_1
%3302 = OpVariable %_ptr_Input__arr__arr_v4float_uint_16_uint_1 Input
%_ptr_Input__arr_v4float_uint_16 = OpTypePointer Input %_arr_v4float_uint_16
%_ptr_Output_v2float = OpTypePointer Output %v2float
%5753 = OpVariable %_ptr_Output_v2float Output
%1823 = OpConstantComposite %v2float %float_0 %float_0
%int_1 = OpConstant %int 1
%_arr_v2float_uint_1 = OpTypeArray %v2float %uint_1
%_ptr_Input__arr_v2float_uint_1 = OpTypePointer Input %_arr_v2float_uint_1
%5479 = OpVariable %_ptr_Input__arr_v2float_uint_1 Input
%5663 = OpFunction %void None %1282
%24915 = OpLabel
%18491 = OpVariable %_ptr_Function__arr_v2float_uint_4 Function
%5238 = OpVariable %_ptr_Function__arr_v2float_uint_4 Function
%22270 = OpAccessChain %_ptr_Input_v4float %5305 %int_0 %int_0
%8181 = OpLoad %v4float %22270
%20420 = OpAccessChain %_ptr_PushConstant_v4float %3463 %int_2
%20062 = OpLoad %v4float %20420
%19110 = OpVectorShuffle %v2float %20062 %20062 0 1
%7988 = OpAccessChain %_ptr_Input_float %4065 %int_0
%13069 = OpLoad %float %7988
%23515 = OpFOrdGreaterThan %bool %13069 %float_0
OpSelectionMerge %16839 None
OpBranchConditional %23515 %13106 %16839
%13106 = OpLabel
%18836 = OpCompositeConstruct %v2float %13069 %13069
OpBranch %16839
%16839 = OpLabel
%19748 = OpPhi %v2float %19110 %24915 %18836 %13106
%24067 = OpAccessChain %_ptr_PushConstant_v4float %3463 %int_0
%15439 = OpLoad %v4float %24067
%10399 = OpVectorShuffle %v2float %15439 %15439 2 3
%24282 = OpFDiv %v2float %19748 %10399
OpBranch %6318
%6318 = OpLabel
%22958 = OpPhi %int %int_0 %16839 %11651 %12148
%24788 = OpSLessThan %bool %22958 %int_4
OpLoopMerge %12265 %12148 None
OpBranchConditional %24788 %12148 %12265
%12148 = OpLabel
%17761 = OpVectorShuffle %v2float %8181 %8181 0 1
OpStore %18491 %2941
%19574 = OpAccessChain %_ptr_Function_v2float %18491 %22958
%15971 = OpLoad %v2float %19574
%17243 = OpFMul %v2float %15971 %24282
%16594 = OpFAdd %v2float %17761 %17243
%10618 = OpCompositeExtract %float %16594 0
%14087 = OpCompositeExtract %float %16594 1
%7641 = OpCompositeExtract %float %8181 2
%7529 = OpCompositeExtract %float %8181 3
%18260 = OpCompositeConstruct %v4float %10618 %14087 %7641 %7529
%8483 = OpAccessChain %_ptr_Output_v4float %4930 %int_0
OpStore %8483 %18260
%19848 = OpAccessChain %_ptr_Input__arr_v4float_uint_16 %3302 %int_0
%7910 = OpLoad %_arr_v4float_uint_16 %19848
OpStore %5430 %7910
OpStore %5238 %2941
%13290 = OpAccessChain %_ptr_Function_v2float %5238 %22958
%19207 = OpLoad %v2float %13290
%8973 = OpExtInst %v2float %1 FMax %19207 %1823
OpStore %5753 %8973
OpEmitVertex
%11651 = OpIAdd %int %22958 %int_1
OpBranch %6318
%12265 = OpLabel
OpEndPrimitive
OpReturn
OpFunctionEnd
#endif
const uint32_t point_list_gs[] = {
0x07230203, 0x00010000, 0x0008000A, 0x00006154, 0x00000000, 0x00020011,
0x00000002, 0x0006000B, 0x00000001, 0x4C534C47, 0x6474732E, 0x3035342E,
0x00000000, 0x0003000E, 0x00000000, 0x00000001, 0x000C000F, 0x00000003,
0x0000161F, 0x6E69616D, 0x00000000, 0x000014B9, 0x00000FE1, 0x00001342,
0x00001536, 0x00000CE6, 0x00001679, 0x00001567, 0x00030010, 0x0000161F,
0x00000013, 0x00040010, 0x0000161F, 0x00000000, 0x00000001, 0x00030010,
0x0000161F, 0x0000001D, 0x00040010, 0x0000161F, 0x0000001A, 0x00000004,
0x00050048, 0x000003F9, 0x00000000, 0x0000000B, 0x00000000, 0x00030047,
0x000003F9, 0x00000002, 0x00050048, 0x00000507, 0x00000000, 0x00000023,
0x00000000, 0x00050048, 0x00000507, 0x00000001, 0x00000023, 0x00000010,
0x00050048, 0x00000507, 0x00000002, 0x00000023, 0x00000020, 0x00050048,
0x00000507, 0x00000003, 0x00000023, 0x00000030, 0x00050048, 0x00000507,
0x00000004, 0x00000023, 0x00000040, 0x00030047, 0x00000507, 0x00000002,
0x00040047, 0x00000FE1, 0x0000001E, 0x00000011, 0x00050048, 0x000003FA,
0x00000000, 0x0000000B, 0x00000000, 0x00030047, 0x000003FA, 0x00000002,
0x00040047, 0x00001536, 0x0000001E, 0x00000000, 0x00040047, 0x00000CE6,
0x0000001E, 0x00000000, 0x00040047, 0x00001679, 0x0000001E, 0x00000010,
0x00040047, 0x00001567, 0x0000001E, 0x00000010, 0x00020013, 0x00000008,
0x00030021, 0x00000502, 0x00000008, 0x00030016, 0x0000000D, 0x00000020,
0x00040017, 0x0000001D, 0x0000000D, 0x00000004, 0x0003001E, 0x000003F9,
0x0000001D, 0x00040015, 0x0000000B, 0x00000020, 0x00000000, 0x0004002B,
0x0000000B, 0x00000A0D, 0x00000001, 0x0004001C, 0x0000023D, 0x000003F9,
0x00000A0D, 0x00040020, 0x000004BA, 0x00000001, 0x0000023D, 0x0004003B,
0x000004BA, 0x000014B9, 0x00000001, 0x00040015, 0x0000000C, 0x00000020,
0x00000001, 0x0004002B, 0x0000000C, 0x00000A0B, 0x00000000, 0x00040020,
0x0000029A, 0x00000001, 0x0000001D, 0x00040017, 0x00000013, 0x0000000D,
0x00000002, 0x00040020, 0x00000290, 0x00000007, 0x00000013, 0x0007001E,
0x00000507, 0x0000001D, 0x0000001D, 0x0000001D, 0x0000001D, 0x0000000B,
0x00040020, 0x00000784, 0x00000009, 0x00000507, 0x0004003B, 0x00000784,
0x00000D87, 0x00000009, 0x0004002B, 0x0000000C, 0x00000A11, 0x00000002,
0x00040020, 0x0000029B, 0x00000009, 0x0000001D, 0x0004001C, 0x00000239,
0x0000000D, 0x00000A0D, 0x00040020, 0x000004B6, 0x00000001, 0x00000239,
0x0004003B, 0x000004B6, 0x00000FE1, 0x00000001, 0x00040020, 0x0000028A,
0x00000001, 0x0000000D, 0x0004002B, 0x0000000D, 0x00000A0C, 0x00000000,
0x00020014, 0x00000009, 0x0004002B, 0x0000000C, 0x00000A17, 0x00000004,
0x0003001E, 0x000003FA, 0x0000001D, 0x00040020, 0x00000676, 0x00000003,
0x000003FA, 0x0004003B, 0x00000676, 0x00001342, 0x00000003, 0x0004002B,
0x0000000B, 0x00000A16, 0x00000004, 0x0004001C, 0x000004D3, 0x00000013,
0x00000A16, 0x0004002B, 0x0000000D, 0x00000341, 0xBF800000, 0x0004002B,
0x0000000D, 0x0000008A, 0x3F800000, 0x0005002C, 0x00000013, 0x00000049,
0x00000341, 0x0000008A, 0x0005002C, 0x00000013, 0x00000300, 0x0000008A,
0x0000008A, 0x0005002C, 0x00000013, 0x0000004A, 0x00000341, 0x00000341,
0x0005002C, 0x00000013, 0x00000301, 0x0000008A, 0x00000341, 0x0007002C,
0x000004D3, 0x00000B7D, 0x00000049, 0x00000300, 0x0000004A, 0x00000301,
0x00040020, 0x00000750, 0x00000007, 0x000004D3, 0x00040020, 0x0000029C,
0x00000003, 0x0000001D, 0x0004002B, 0x0000000B, 0x00000A3A, 0x00000010,
0x0004001C, 0x00000989, 0x0000001D, 0x00000A3A, 0x00040020, 0x00000043,
0x00000003, 0x00000989, 0x0004003B, 0x00000043, 0x00001536, 0x00000003,
0x0004001C, 0x00000A2E, 0x00000989, 0x00000A0D, 0x00040020, 0x000000E8,
0x00000001, 0x00000A2E, 0x0004003B, 0x000000E8, 0x00000CE6, 0x00000001,
0x00040020, 0x00000044, 0x00000001, 0x00000989, 0x00040020, 0x00000291,
0x00000003, 0x00000013, 0x0004003B, 0x00000291, 0x00001679, 0x00000003,
0x0005002C, 0x00000013, 0x0000071F, 0x00000A0C, 0x00000A0C, 0x0004002B,
0x0000000C, 0x00000A0E, 0x00000001, 0x0004001C, 0x00000281, 0x00000013,
0x00000A0D, 0x00040020, 0x000004FE, 0x00000001, 0x00000281, 0x0004003B,
0x000004FE, 0x00001567, 0x00000001, 0x00050036, 0x00000008, 0x0000161F,
0x00000000, 0x00000502, 0x000200F8, 0x00006153, 0x0004003B, 0x00000750,
0x0000483B, 0x00000007, 0x0004003B, 0x00000750, 0x00001476, 0x00000007,
0x00060041, 0x0000029A, 0x000056FE, 0x000014B9, 0x00000A0B, 0x00000A0B,
0x0004003D, 0x0000001D, 0x00001FF5, 0x000056FE, 0x00050041, 0x0000029B,
0x00004FC4, 0x00000D87, 0x00000A11, 0x0004003D, 0x0000001D, 0x00004E5E,
0x00004FC4, 0x0007004F, 0x00000013, 0x00004AA6, 0x00004E5E, 0x00004E5E,
0x00000000, 0x00000001, 0x00050041, 0x0000028A, 0x00001F34, 0x00000FE1,
0x00000A0B, 0x0004003D, 0x0000000D, 0x0000330D, 0x00001F34, 0x000500BA,
0x00000009, 0x00005BDB, 0x0000330D, 0x00000A0C, 0x000300F7, 0x000041C7,
0x00000000, 0x000400FA, 0x00005BDB, 0x00003332, 0x000041C7, 0x000200F8,
0x00003332, 0x00050050, 0x00000013, 0x00004994, 0x0000330D, 0x0000330D,
0x000200F9, 0x000041C7, 0x000200F8, 0x000041C7, 0x000700F5, 0x00000013,
0x00004D24, 0x00004AA6, 0x00006153, 0x00004994, 0x00003332, 0x00050041,
0x0000029B, 0x00005E03, 0x00000D87, 0x00000A0B, 0x0004003D, 0x0000001D,
0x00003C4F, 0x00005E03, 0x0007004F, 0x00000013, 0x0000289F, 0x00003C4F,
0x00003C4F, 0x00000002, 0x00000003, 0x00050088, 0x00000013, 0x00005EDA,
0x00004D24, 0x0000289F, 0x000200F9, 0x000018AE, 0x000200F8, 0x000018AE,
0x000700F5, 0x0000000C, 0x000059AE, 0x00000A0B, 0x000041C7, 0x00002D83,
0x00002F74, 0x000500B1, 0x00000009, 0x000060D4, 0x000059AE, 0x00000A17,
0x000400F6, 0x00002FE9, 0x00002F74, 0x00000000, 0x000400FA, 0x000060D4,
0x00002F74, 0x00002FE9, 0x000200F8, 0x00002F74, 0x0007004F, 0x00000013,
0x00004561, 0x00001FF5, 0x00001FF5, 0x00000000, 0x00000001, 0x0003003E,
0x0000483B, 0x00000B7D, 0x00050041, 0x00000290, 0x00004C76, 0x0000483B,
0x000059AE, 0x0004003D, 0x00000013, 0x00003E63, 0x00004C76, 0x00050085,
0x00000013, 0x0000435B, 0x00003E63, 0x00005EDA, 0x00050081, 0x00000013,
0x000040D2, 0x00004561, 0x0000435B, 0x00050051, 0x0000000D, 0x0000297A,
0x000040D2, 0x00000000, 0x00050051, 0x0000000D, 0x00003707, 0x000040D2,
0x00000001, 0x00050051, 0x0000000D, 0x00001DD9, 0x00001FF5, 0x00000002,
0x00050051, 0x0000000D, 0x00001D69, 0x00001FF5, 0x00000003, 0x00070050,
0x0000001D, 0x00004754, 0x0000297A, 0x00003707, 0x00001DD9, 0x00001D69,
0x00050041, 0x0000029C, 0x00002123, 0x00001342, 0x00000A0B, 0x0003003E,
0x00002123, 0x00004754, 0x00050041, 0x00000044, 0x00004D88, 0x00000CE6,
0x00000A0B, 0x0004003D, 0x00000989, 0x00001EE6, 0x00004D88, 0x0003003E,
0x00001536, 0x00001EE6, 0x0003003E, 0x00001476, 0x00000B7D, 0x00050041,
0x00000290, 0x000033EA, 0x00001476, 0x000059AE, 0x0004003D, 0x00000013,
0x00004B07, 0x000033EA, 0x0007000C, 0x00000013, 0x0000230D, 0x00000001,
0x00000028, 0x00004B07, 0x0000071F, 0x0003003E, 0x00001679, 0x0000230D,
0x000100DA, 0x00050080, 0x0000000C, 0x00002D83, 0x000059AE, 0x00000A0E,
0x000200F9, 0x000018AE, 0x000200F8, 0x00002FE9, 0x000100DB, 0x000100FD,
0x00010038,
};
|
Blub/pve-manager
|
www/manager6/qemu/HDEfi.js
|
Ext.define('PVE.qemu.EFIDiskInputPanel', {
extend: 'PVE.panel.InputPanel',
alias: 'widget.pveEFIDiskInputPanel',
insideWizard: false,
unused: false, // ADD usused disk imaged
vmconfig: {}, // used to select usused disks
controller: {
xclass: 'Ext.app.ViewController',
control: {
'field[name=hdstorage]': {
change: function(f, value) {
if (!value) { // initial store loading fires an unwanted 'change'
return;
}
var me = this.getView();
var rec = f.store.getById(value);
var rawArray = ['iscsi', 'lvm', 'lvmthin', 'drbd', 'rbd', 'sheepdog', 'zfs', 'zfspool'];
me.hdfilesel.setDisabled(true);
me.hdfilesel.setVisible(false);
me.formatsel.setValue('qcow2');
me.formatsel.setDisabled(false);
// if rec.data.type exists in the array
if (rawArray.indexOf(rec.data.type) !== -1) {
me.formatsel.setValue('raw');
me.formatsel.setDisabled(true);
}
if (rec.data.type === 'iscsi') {
me.hdfilesel.setStorage(value);
me.hdfilesel.setDisabled(false);
me.hdfilesel.setVisible(true);
}
}
}
}
},
onGetValues: function(values) {
var me = this;
var confid = 'efidisk0';
if (values.hdimage) {
me.drive.file = values.hdimage;
} else {
// we use 1 here, because for efi the size gets overridden from the backend
me.drive.file = values.hdstorage + ":1";
}
me.drive.format = values.diskformat;
var params = {};
params[confid] = PVE.Parser.printQemuDrive(me.drive);
return params;
},
setNodename: function(nodename) {
var me = this;
me.hdstoragesel.setNodename(nodename);
me.hdfilesel.setStorage(undefined, nodename);
},
initComponent : function() {
var me = this;
me.drive = {};
me.items= [];
me.formatsel = Ext.create('PVE.form.DiskFormatSelector', {
name: 'diskformat',
fieldLabel: gettext('Format'),
value: 'qcow2',
allowBlank: false
});
me.hdfilesel = Ext.create('PVE.form.FileSelector', {
name: 'hdimage',
nodename: me.nodename,
storageContent: 'images',
fieldLabel: gettext('Disk image'),
disabled: true,
hidden: true,
allowBlank: false
});
me.hdstoragesel = Ext.create('PVE.form.StorageSelector', {
name: 'hdstorage',
nodename: me.nodename,
fieldLabel: gettext('Storage'),
storageContent: 'images',
autoSelect: me.insideWizard,
allowBlank: false
});
me.items.push(me.hdstoragesel);
me.items.push(me.hdfilesel);
me.items.push(me.formatsel);
me.callParent();
}
});
Ext.define('PVE.qemu.EFIDiskEdit', {
extend: 'PVE.window.Edit',
isAdd: true,
subject: gettext('EFI Disk'),
initComponent : function() {
var me = this;
var nodename = me.pveSelNode.data.node;
if (!nodename) {
throw "no node name specified";
}
me.items = [{
xtype: 'pveEFIDiskInputPanel',
onlineHelp: 'qm_bios_and_uefi',
confid: me.confid,
nodename: nodename,
isCreate: true
}];
me.callParent();
}
});
|
DazEB2/SimplePyScripts
|
telegram_bot_examples/funs_tests__speak_pict_youtube/speak_pict_youtube.py
|
<filename>telegram_bot_examples/funs_tests__speak_pict_youtube/speak_pict_youtube.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import random
import sys
import time
import os
from pathlib import Path
from telegram import Update, InputMediaPhoto
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
sys.path.append('..')
sys.path.append('../../html_parsing')
sys.path.append('../../exchange_rates')
import config
from common import get_logger, log_func, reply_error
from cbr_ru import exchange_rate
from youtube_com__results_search_query import search_youtube
ALL_COMMANDS = []
log = get_logger(__file__)
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(update: Update, context: CallbackContext):
update.effective_message.reply_text(text='Hi!')
def help(update: Update, context: CallbackContext):
text = 'Commands:\n' + '\n'.join(f' /{x}' for x in ALL_COMMANDS)
update.effective_message.reply_text(text)
def echo(update: Update, context: CallbackContext):
message = update.effective_message
message.reply_text(text=f'Echo: {message.text}')
def on_exchange_rates(update: Update, context: CallbackContext):
text = 'Курс:'
for code in ['USD', 'EUR']:
text += f'\n {code}: {exchange_rate(code)[0]}'
log.debug(text)
update.effective_message.reply_text(text=text)
def pict(update: Update, context: CallbackContext):
update.effective_message.reply_photo('https://t8.mangas.rocks/auto/07/48/88/Onepunchman_t1_gl1_18.png')
def pict2(update: Update, context: CallbackContext):
message = update.effective_message
with open('files/Onepunchman_t1_gl1_18.png', 'rb') as f:
message.reply_photo(f)
def pict3(update: Update, context: CallbackContext):
message = update.effective_message
max_parts = 10
files = list(Path('files/readmanga.live_one_punch_man__A1bc88e_vol1_1').glob('*.*'))
media_groups = []
for i in range(0, len(files), max_parts):
media = [
InputMediaPhoto(f.open('rb')) for f in files[i: i+max_parts]
]
media_groups.append(media)
for i, media_group in enumerate(media_groups, 1):
if len(media_groups) > 1:
media_groups[0][0].caption = f'Часть #{i}'
message.reply_media_group(media_group)
# Поиск на YouTube
def video(update: Update, context: CallbackContext):
message = update.effective_message
args = context.args
log.debug(args)
if not args:
message.reply_text(text='К команде добавьте запрос.')
return
msg = ' '.join(args)
search_results = search_youtube(msg)
if not search_results:
message.reply_text(text='Ничего не найдено.')
return
url, title = random.choice(search_results)
message.reply_text(text=title + '\n' + url)
# NOTE: not work, source: https://github.com/gil9red/SimplePyScripts/blob/b366323934eb0ed9557ba7d40c3c64cf6a7b8c36/speak__[does_not_work]
# locale = 'ru-RU'
# gender = 'female'
#
#
# def speak(update: Update, context: CallbackContext):
# args = context.args
# log.debug(args)
#
# if not args:
# # log.debug('Список пуст')
# # return
# args = ['Сорок тысяч обезьян в жопу сунули банан']
#
# def bing_speak(text, locale, gender):
# """
# Функция выполняет запрос в bing сервис синтезирования речи и возвращает получившийся mp3-файл с речью
# в виде байтовой строки.
#
# """
#
# # Примеры запросов в сервис синтезирования речи:
# # http://www.bing.com/translator/api/language/Speak?locale=ru-RU&gender=male&media=audio/mp3&text=gil9red+%D0%BA%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9+%D1%87%D1%83%D0%B2%D0%B0%D0%BA
# # http://www.bing.com/translator/api/language/Speak?locale=ru-RU&gender=female&media=audio/mp3&text=gil9red+%D0%BA%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9+%D1%87%D1%83%D0%B2%D0%B0%D0%BA
#
# url = 'https://www.bing.com/translator/api/language/Speak'
# params = {
# 'locale': locale,
# 'gender': gender,
# 'media': 'audio/mp3',
# 'text': text,
# }
#
# s = requests.Session()
#
# # Получим куки, иначе получим ошибку: {"message": "Service unavailable. Please try again later."}
# rs = s.get('http://www.bing.com/translator')
# if not rs.ok:
# raise Exception('Error [%s]: %s.', rs.status_code, rs.text)
#
# rs = s.get(url, params=params)
# if not rs.ok:
# raise Exception('Error [%s]: %s.', rs.status_code, rs.text)
#
# return rs.content
#
# # with open('OP_836_page02.png', 'rb') as f:
#
# # Первый элемент args -- текст
# # Второй голос
# # Третий локаль
# #
# text = ' '.join(args)
# mp3_content = bing_speak(text, locale, gender)
#
# # Сохраняем в файл и возвращаем объект для считывания
# with open('speak.mp3', 'wb') as f:
# f.write(mp3_content)
#
# with open('speak.mp3', 'rb') as f:
# message.reply_audio(message.chat_id, audio=f, title='Speak {} {}'.format(gender, locale))
#
#
# def speak_set_locale(update: Update, context: CallbackContext):
# log.debug('speak_set_locale')
# args = context.args
# if not args:
# # TODO: писать об ошиюке в чат
# log.debug('Список пуст')
# return
#
# global locale
# last_locale = locale
# locale = args[0]
#
# message.reply_text(text='Speak locale изменена: {} -> {}.'.format(last_locale, locale))
#
#
# def speak_set_gender(update: Update, context: CallbackContext):
# log.debug('speak_set_gender')
# args = context.args
# if not args:
# # TODO: писать об ошиюке в чат
# log.debug('Список пуст')
# return
#
# global gender
# last_gender = gender
# gender = args[0]
#
# message.reply_text(text='Speak gender изменена: {} -> {}.'.format(last_gender, gender))
def on_error(update: Update, context: CallbackContext):
reply_error(log, update, context)
def main():
cpu_count = os.cpu_count()
workers = cpu_count
log.debug('System: CPU_COUNT=%s, WORKERS=%s', cpu_count, workers)
log.debug('Start')
# Create the EventHandler and pass it your bot's token.
updater = Updater(
config.TOKEN,
workers=workers,
use_context=True
)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("hi", lambda update, context: update.message.reply_text(text='hi')))
dp.add_handler(CommandHandler("say", lambda update, context: update.message.reply_text(text=f'''I say: "{" ".join(context.args)}".''')))
dp.add_handler(CommandHandler("exchange_rates", on_exchange_rates))
dp.add_handler(CommandHandler("pict", pict))
dp.add_handler(CommandHandler("pict2", pict2))
dp.add_handler(CommandHandler("pict3", pict3))
dp.add_handler(CommandHandler("yt", video))
# NOTE: not work
# dp.add_handler(CommandHandler("speak", speak))
# dp.add_handler(CommandHandler("speak_set_locale", speak_set_locale))
# dp.add_handler(CommandHandler("speak_set_gender", speak_set_gender))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
for commands in dp.handlers.values():
for command in commands:
if isinstance(command, CommandHandler):
ALL_COMMANDS.extend(command.command)
# log all errors
dp.add_error_handler(on_error)
# Start the Bot
updater.start_polling()
# Run the bot until the you presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
while True:
try:
main()
except:
log.exception('')
timeout = 15
log.info(f'Restarting the bot after {timeout} seconds')
time.sleep(timeout)
|
ScalablyTyped/SlinkyTyped
|
m/mongoose/src/main/scala/typingsSlinky/mongoose/mod/HasJustId.scala
|
<reponame>ScalablyTyped/SlinkyTyped
package typingsSlinky.mongoose.mod
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
// check whether a type consists just of {_id: T} and no other properties
/* Rewritten from type alias, can be one of:
- typingsSlinky.mongoose.mongooseBooleans.`false`
- typingsSlinky.mongoose.mongooseBooleans.`true`
*/
trait HasJustId[T] extends js.Object
|
ishitatsuyuki/watchman
|
FileInformation.cpp
|
/* Copyright 2017-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "FileInformation.h"
#include "watchman_time.h"
namespace watchman {
#ifndef _WIN32
FileInformation::FileInformation(const struct stat& st)
: mode(st.st_mode),
size(off_t(st.st_size)),
uid(st.st_uid),
gid(st.st_gid),
ino(st.st_ino),
dev(st.st_dev),
nlink(st.st_nlink) {
memcpy(&atime, &st.WATCHMAN_ST_TIMESPEC(a), sizeof(atime));
memcpy(&mtime, &st.WATCHMAN_ST_TIMESPEC(m), sizeof(mtime));
memcpy(&ctime, &st.WATCHMAN_ST_TIMESPEC(c), sizeof(ctime));
}
#endif
#ifdef _WIN32
FileInformation::FileInformation(uint32_t dwFileAttributes)
: fileAttributes(dwFileAttributes) {
if (fileAttributes & FILE_ATTRIBUTE_READONLY) {
mode = 0444;
} else {
mode = 0666;
}
if (fileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
// It's a symlink, but to be msvc compatible, we report
// this as a file. Note that a reparse point can also
// have FILE_ATTRIBUTE_DIRECTORY set if the symlink was
// created with the intention of it appearing as a file.
mode |= _S_IFREG;
} else if (fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
mode |= _S_IFDIR | 0111 /* executable/searchable */;
} else {
mode |= _S_IFREG;
}
}
#endif
bool FileInformation::isSymlink() const {
#ifdef _WIN32
// We treat all reparse points as equivalent to symlinks
return fileAttributes & FILE_ATTRIBUTE_REPARSE_POINT;
#else
return S_ISLNK(mode);
#endif
}
bool FileInformation::isDir() const {
#ifdef _WIN32
// Note that junctions have both DIRECTORY and REPARSE_POINT set,
// so we have to check both bits to make sure that we only report
// this as a dir if it isn't a junction, otherwise we will fail to
// opendir.
return (fileAttributes &
(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) ==
FILE_ATTRIBUTE_DIRECTORY;
#else
return S_ISDIR(mode);
#endif
}
bool FileInformation::isFile() const {
#ifdef _WIN32
// We can't simply test for FILE_ATTRIBUTE_NORMAL as that is only
// valid when no other bits are set. Instead we check for the absence
// of DIRECTORY and REPARSE_POINT to decide that it is a regular file.
return (fileAttributes &
(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT)) == 0;
#else
return S_ISREG(mode);
#endif
}
FileInformation FileInformation::makeDeletedFileInformation() {
FileInformation info;
#ifndef _WIN32
info.mode = S_IFREG;
#else
info.mode = _S_IFREG;
#endif
return info;
}
}
|
apptentive-engineering/apptentive-android
|
apptentive/src/main/java/com/apptentive/android/sdk/module/messagecenter/MessagePollingWorker.java
|
/*
* Copyright (c) 2017, Apptentive, Inc. All Rights Reserved.
* Please refer to the LICENSE file for the terms and conditions
* under which redistribution and use of this file is permitted.
*/
package com.apptentive.android.sdk.module.messagecenter;
import androidx.annotation.NonNull;
import com.apptentive.android.sdk.ApptentiveInternal;
import com.apptentive.android.sdk.ApptentiveLog;
import com.apptentive.android.sdk.conversation.Conversation;
import com.apptentive.android.sdk.model.ApptentiveMessage;
import com.apptentive.android.sdk.model.Configuration;
import com.apptentive.android.sdk.notifications.ApptentiveNotificationCenter;
import com.apptentive.android.sdk.util.Destroyable;
import com.apptentive.android.sdk.util.threading.DispatchTask;
import java.util.List;
import static com.apptentive.android.sdk.ApptentiveHelper.dispatchOnConversationQueueOnce;
import static com.apptentive.android.sdk.ApptentiveLogTag.MESSAGES;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_KEY_INTERVAL;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_MESSAGES_STOPPED_POLLING;
import static com.apptentive.android.sdk.ApptentiveNotifications.NOTIFICATION_MESSAGES_STARTED_POLLING;
import static com.apptentive.android.sdk.debug.Assert.assertTrue;
class MessagePollingWorker implements Destroyable, MessageManager.MessageFetchListener {
private final MessageManager messageManager;
private final long backgroundPollingInterval;
private final long foregroundPollingInterval;
private final Configuration conf;
private boolean messageCenterInForeground;
private DispatchTask messagePollingTask;
MessagePollingWorker(MessageManager messageManager) {
if (messageManager == null) {
throw new IllegalArgumentException("Message manager is null");
}
this.messageManager = messageManager;
conf = Configuration.load();
backgroundPollingInterval = conf.getMessageCenterBgPoll() * 1000;
foregroundPollingInterval = conf.getMessageCenterFgPoll() * 1000;
ApptentiveLog.v(MESSAGES, "Message Polling Worker: bg=%d, fg=%d", backgroundPollingInterval, foregroundPollingInterval);
}
@Override
public void destroy() {
stopPolling();
}
//region MessageFetchListener
@Override
public void onFetchFinish(MessageManager manager, List<ApptentiveMessage> messages) {
if (isPolling()) {
long pollingInterval = getPollingInterval();
ApptentiveLog.v(MESSAGES, "Scheduled polling messages in %d sec", pollingInterval / 1000);
dispatchOnConversationQueueOnce(messagePollingTask, pollingInterval);
}
}
//endregion
void appWentToForeground() {
startPolling();
}
void appWentToBackground() {
stopPolling();
}
/**
* If coming from the background, wake the thread so that it immediately starts runs and runs more often. If coming
* from the foreground, let the isPolling interval timeout naturally, at which point the isPolling interval will become
* the background isPolling interval.
*
* @param foreground true if the worker should be in foreground isPolling mode, else false.
*/
void setMessageCenterInForeground(boolean foreground) {
messageCenterInForeground = foreground;
if (foreground) {
startPolling(true);
}
}
void startPolling() {
startPolling(false);
}
private void startPolling(boolean force) {
if (force) {
stopPolling();
}
if (!isPolling()) {
ApptentiveLog.v(MESSAGES, "Start polling messages (%s)", getLocalConversationIdentifier());
messagePollingTask = createPollingTask();
dispatchOnConversationQueueOnce(messagePollingTask, 0L);
notifyStartPolling(getPollingInterval());
}
}
void stopPolling() {
if (isPolling()) {
ApptentiveLog.v(MESSAGES, "Stop polling messages (%s)", getLocalConversationIdentifier());
messagePollingTask.cancel();
messagePollingTask = null;
notifyStopPolling();
}
}
private long getPollingInterval() {
return messageCenterInForeground ? foregroundPollingInterval : backgroundPollingInterval;
}
//region Notifications
private void notifyStartPolling(long interval) {
ApptentiveNotificationCenter.defaultCenter()
.postNotification(NOTIFICATION_MESSAGES_STARTED_POLLING,
NOTIFICATION_KEY_INTERVAL, interval);
}
private void notifyStopPolling() {
ApptentiveNotificationCenter.defaultCenter().postNotification(NOTIFICATION_MESSAGES_STOPPED_POLLING);
}
//endregion
private Conversation getConversation() {
return messageManager.getConversation();
}
private String getLocalConversationIdentifier() {
return getConversation().getLocalIdentifier();
}
boolean isMessageCenterInForeground() {
return messageCenterInForeground;
}
private boolean isPolling() {
return messagePollingTask != null;
}
@NonNull
private DispatchTask createPollingTask() {
return new DispatchTask() { // TODO: convert to ConversationDispatchTask
@Override
protected void execute() {
assertTrue(isPolling(), "Not polling messages");
if (ApptentiveInternal.canShowMessageCenterInternal(getConversation())) {
ApptentiveLog.d(MESSAGES, "Checking server for new messages...");
messageManager.fetchAndStoreMessages(messageCenterInForeground, conf.isMessageCenterNotificationPopupEnabled(), MessagePollingWorker.this);
} else {
ApptentiveLog.w(MESSAGES, "Unable to fetch messages: message center can't be show at this time");
}
}
};
}
}
|
DevvyDoo/Leveled
|
src/main/java/me/devvy/leveled/events/PlayerDealtMeleeDamageEvent.java
|
<reponame>DevvyDoo/Leveled
package me.devvy.leveled.events;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* An event called after a player swaps some armor out, meaning we have to recalculate some of their stats
*/
public class PlayerDealtMeleeDamageEvent extends EntityDamageByEntityEvent {
private static final HandlerList HANDLERS = new HandlerList();
public PlayerDealtMeleeDamageEvent(Entity damager, Entity damagee, DamageCause cause, double damage) {
super(damager, damagee, cause, damage);
}
public Player getPlayer() {
assert this.getDamager() instanceof Player;
return (Player) this.getDamager();
}
public void multiplyDamage(double multiplier) {
setDamage(getDamage() * multiplier);
}
public HandlerList getHandlers() {
return HANDLERS;
}
public static HandlerList getHandlerList() {
return HANDLERS;
}
}
|
Yuunagi-Yu/NumberDisk
|
Project/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Array_InternalEnumerator_1_gen3008434283MethodDeclarations.h
|
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Array
struct Il2CppArray;
// System.Object
struct Il2CppObject;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Array_InternalEnumerator_1_gen3008434283.h"
#include "mscorlib_System_Array3829468939.h"
// System.Void System.Array/InternalEnumerator`1<System.UInt32>::.ctor(System.Array)
extern "C" void InternalEnumerator_1__ctor_m691972083_gshared (InternalEnumerator_1_t3008434283 * __this, Il2CppArray * ___array0, const MethodInfo* method);
#define InternalEnumerator_1__ctor_m691972083(__this, ___array0, method) (( void (*) (InternalEnumerator_1_t3008434283 *, Il2CppArray *, const MethodInfo*))InternalEnumerator_1__ctor_m691972083_gshared)(__this, ___array0, method)
// System.Void System.Array/InternalEnumerator`1<System.UInt32>::System.Collections.IEnumerator.Reset()
extern "C" void InternalEnumerator_1_System_Collections_IEnumerator_Reset_m3107741851_gshared (InternalEnumerator_1_t3008434283 * __this, const MethodInfo* method);
#define InternalEnumerator_1_System_Collections_IEnumerator_Reset_m3107741851(__this, method) (( void (*) (InternalEnumerator_1_t3008434283 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_Reset_m3107741851_gshared)(__this, method)
// System.Object System.Array/InternalEnumerator`1<System.UInt32>::System.Collections.IEnumerator.get_Current()
extern "C" Il2CppObject * InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m2458630467_gshared (InternalEnumerator_1_t3008434283 * __this, const MethodInfo* method);
#define InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m2458630467(__this, method) (( Il2CppObject * (*) (InternalEnumerator_1_t3008434283 *, const MethodInfo*))InternalEnumerator_1_System_Collections_IEnumerator_get_Current_m2458630467_gshared)(__this, method)
// System.Void System.Array/InternalEnumerator`1<System.UInt32>::Dispose()
extern "C" void InternalEnumerator_1_Dispose_m2620838688_gshared (InternalEnumerator_1_t3008434283 * __this, const MethodInfo* method);
#define InternalEnumerator_1_Dispose_m2620838688(__this, method) (( void (*) (InternalEnumerator_1_t3008434283 *, const MethodInfo*))InternalEnumerator_1_Dispose_m2620838688_gshared)(__this, method)
// System.Boolean System.Array/InternalEnumerator`1<System.UInt32>::MoveNext()
extern "C" bool InternalEnumerator_1_MoveNext_m470170271_gshared (InternalEnumerator_1_t3008434283 * __this, const MethodInfo* method);
#define InternalEnumerator_1_MoveNext_m470170271(__this, method) (( bool (*) (InternalEnumerator_1_t3008434283 *, const MethodInfo*))InternalEnumerator_1_MoveNext_m470170271_gshared)(__this, method)
// T System.Array/InternalEnumerator`1<System.UInt32>::get_Current()
extern "C" uint32_t InternalEnumerator_1_get_Current_m2198364332_gshared (InternalEnumerator_1_t3008434283 * __this, const MethodInfo* method);
#define InternalEnumerator_1_get_Current_m2198364332(__this, method) (( uint32_t (*) (InternalEnumerator_1_t3008434283 *, const MethodInfo*))InternalEnumerator_1_get_Current_m2198364332_gshared)(__this, method)
|
astaxie/tsuru
|
collector/suite_test.go
|
<reponame>astaxie/tsuru
// Copyright 2012 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"github.com/globocom/config"
"github.com/globocom/tsuru/app"
"github.com/globocom/tsuru/db"
ttesting "github.com/globocom/tsuru/testing"
"labix.org/v2/mgo"
. "launchpad.net/gocheck"
"testing"
)
func Test(t *testing.T) { TestingT(t) }
type S struct {
session *mgo.Session
tmpdir string
instances []string
provisioner *ttesting.FakeProvisioner
}
var _ = Suite(&S{})
func (s *S) SetUpSuite(c *C) {
var err error
db.Session, err = db.Open("127.0.0.1:27017", "tsuru_collector_test")
c.Assert(err, IsNil)
s.provisioner = ttesting.NewFakeProvisioner()
app.Provisioner = s.provisioner
err = config.ReadConfigFile("../etc/tsuru.conf")
c.Assert(err, IsNil)
config.Set("queue-server", "127.0.0.1:0")
}
func (s *S) TearDownSuite(c *C) {
db.Session.Apps().Database.DropDatabase()
db.Session.Close()
}
func (s *S) TearDownTest(c *C) {
_, err := db.Session.Apps().RemoveAll(nil)
c.Assert(err, IsNil)
s.provisioner.Reset()
}
|
DougBurke/xspeclmodels
|
xspec/XSFit/MCMC/AsciiChain.h
|
<filename>xspec/XSFit/MCMC/AsciiChain.h
// Read the documentation to learn more about C++ code generator
// versioning.
// %X% %Q% %Z% %W%
#ifndef ASCIICHAIN_H
#define ASCIICHAIN_H 1
// ChainIO
#include <XSFit/MCMC/ChainIO.h>
class Chain;
#include <fstream>
class AsciiChain : public ChainIO //## Inherits: <unnamed>%46DD7C75006B
{
public:
AsciiChain (string fileName = string(""));
virtual ~AsciiChain();
virtual void doOpenForReadPoints () const;
virtual void doCloseFile () const;
virtual void doOpenForWrite ();
virtual void doReadPoint (std::vector<Real>& chainVals) const;
virtual void doReadPointFromLine (size_t lineNum, RealArray& parVals) const;
virtual void doReadPointFromLine (size_t lineNum, RealArray& parVals, Real& statVal) const;
virtual const string& getFormatName () const;
virtual void readFileInfo ();
virtual void createFile ();
virtual void writePoint ();
virtual void writePoint (RealArray& paramVals, Real& statVal);
virtual void writeFileInfo ();
virtual void adjustLengthInfo ();
virtual void appendFile (RealArray& startingVals);
virtual void appendFile (RealArray& startingVals, Real& startingStatVal);
virtual void adjustTemperInfo ();
virtual bool checkTemperField (const Real temperature) const;
virtual void setParent (Chain* chain);
virtual bool allowsTemper () const;
static const string& FORMATNAME ();
// Additional Public Declarations
protected:
// Additional Protected Declarations
private:
AsciiChain(const AsciiChain &right);
AsciiChain & operator=(const AsciiChain &right);
void moveToLine (const size_t lineNum) const;
string readTemperInfo ();
void testFile (const string& fileName) const;
// Additional Private Declarations
private: //## implementation
// Data Members for Class Attributes
static const size_t s_LENGTHFIELDWIDTH;
static const int s_TEMPERFIELDWIDTH;
static const string s_FORMATNAME;
static const string s_CHAINTYPE;
static const string s_NWALKERS;
mutable std::fstream m_file;
std::fstream::pos_type m_lengthInfoPos;
std::fstream::pos_type m_pointsStartPos;
std::fstream::pos_type m_temperInfoPos;
// Pointer to the Chain object which owns this object.
// This obviously must be a non-owning pointer or else it
// will be a circular dependency.
Chain* m_chain;
// Additional Implementation Declarations
};
// Class AsciiChain
inline const string& AsciiChain::FORMATNAME ()
{
return s_FORMATNAME;
}
#endif
|
afeng11/tomato-arm
|
release/src-rt-6.x.4708/router/nfs-utils/support/nfs/nfsexport.c
|
<filename>release/src-rt-6.x.4708/router/nfs-utils/support/nfs/nfsexport.c
/*
* support/nfs/export.c
*
* Add or delete an NFS export in knfsd.
*
* Copyright (C) 1995, 1996 <NAME> <<EMAIL>>
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <string.h>
#include <sys/types.h>
#include <asm/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "nfslib.h"
/* if /proc/net/rpc/... exists, then
* write to it, as that interface is more stable.
* Write:
* client fsidtype fsid path
* to /proc/net/rpc/nfsd.fh/channel
* and
* client path expiry flags anonuid anongid fsid
* to /proc/net/rpc/nfsd.export/channel
*/
static int
exp_unexp(struct nfsctl_export *exp, int export)
{
FILE *f;
struct stat stb;
__u32 fsid;
char fsidstr[8];
__u16 dev;
__u32 inode;
int err;
f = fopen("/proc/net/rpc/nfsd.export/channel", "w");
if (f == NULL) return -1;
qword_print(f, exp->ex_client);
qword_print(f, exp->ex_path);
if (export) {
qword_printint(f, 0x7fffffff);
qword_printint(f, exp->ex_flags);
qword_printint(f, exp->ex_anon_uid);
qword_printint(f, exp->ex_anon_gid);
qword_printint(f, exp->ex_dev);
} else
qword_printint(f, 1);
err = qword_eol(f);
fclose(f);
if (stat(exp->ex_path, &stb) != 0)
return -1;
f = fopen("/proc/net/rpc/nfsd.fh/channel", "w");
if (f==NULL) return -1;
if (exp->ex_flags & NFSEXP_FSID) {
qword_print(f,exp->ex_client);
qword_printint(f,1);
fsid = exp->ex_dev;
qword_printhex(f, (char*)&fsid, 4);
if (export) {
qword_printint(f, 0x7fffffff);
qword_print(f, exp->ex_path);
} else
qword_printint(f, 1);
err = qword_eol(f) || err;
}
qword_print(f,exp->ex_client);
qword_printint(f,0);
dev = htons(major(stb.st_dev)); memcpy(fsidstr, &dev, 2);
dev = htons(minor(stb.st_dev)); memcpy(fsidstr+2, &dev, 2);
inode = stb.st_ino; memcpy(fsidstr+4, &inode, 4);
qword_printhex(f, fsidstr, 8);
if (export) {
qword_printint(f, 0x7fffffff);
qword_print(f, exp->ex_path);
} else
qword_printint(f, 1);
err = qword_eol(f) || err;
fclose(f);
return err;
}
int
nfsexport(struct nfsctl_export *exp)
{
struct nfsctl_arg arg;
int fd;
if ((fd=open("/proc/net/rpc/nfsd.fh/channel", O_WRONLY))>= 0) {
close(fd);
return exp_unexp(exp, 1);
}
arg.ca_version = NFSCTL_VERSION;
memcpy(&arg.ca_export, exp, sizeof(arg.ca_export));
return nfsctl(NFSCTL_EXPORT, &arg, NULL);
}
int
nfsunexport(struct nfsctl_export *exp)
{
struct nfsctl_arg arg;
int fd;
if ((fd=open("/proc/net/rpc/nfsd.fh/channel", O_WRONLY))>= 0) {
close(fd);
return exp_unexp(exp, 0);
}
arg.ca_version = NFSCTL_VERSION;
memcpy(&arg.ca_export, exp, sizeof(arg.ca_export));
return nfsctl(NFSCTL_UNEXPORT, &arg, NULL);
}
|
housel/spoofax
|
org.metaborg.core/src/main/java/org/metaborg/core/source/SourceRegion.java
|
package org.metaborg.core.source;
public class SourceRegion implements ISourceRegion {
private static final long serialVersionUID = -3699054067428073315L;
private final int startOffset;
private final int startRow;
private final int startColumn;
private final int endOffset;
private final int endRow;
private final int endColumn;
/**
* Creates a zero-length source region from a single offset. Row and column fields are set to -1 to indicate that
* they are not supported.
*
* @param offset
* Offset in the source file.
*/
public SourceRegion(int offset) {
this.startOffset = offset;
this.startRow = -1;
this.startColumn = -1;
this.endOffset = offset;
this.endRow = -1;
this.endColumn = -1;
}
/**
* Creates a source region from a starting and ending offset. Row and column fields are set to -1 to indicate that
* they are not supported.
*
* @param startOffset
* Starting offset in the source file.
* @param endOffset
* Ending offset in the source file.
*/
public SourceRegion(int startOffset, int endOffset) {
this.startOffset = startOffset;
this.startRow = -1;
this.startColumn = -1;
this.endOffset = endOffset;
this.endRow = -1;
this.endColumn = -1;
}
public SourceRegion(int startOffset, int startRow, int startColumn, int endOffset, int endRow, int endColumn) {
this.startOffset = startOffset;
this.startRow = startRow;
this.startColumn = startColumn;
this.endOffset = endOffset;
this.endRow = endRow;
this.endColumn = endColumn;
}
@Override public int startOffset() {
return startOffset;
}
@Override public int startRow() {
return startRow;
}
@Override public int startColumn() {
return startColumn;
}
@Override public int endOffset() {
return endOffset;
}
@Override public int endRow() {
return endRow;
}
@Override public int endColumn() {
return endColumn;
}
@Override public int length() {
return (endOffset - startOffset) + 1;
}
@Override public boolean contains(ISourceRegion region) {
return region.startOffset() >= this.startOffset && region.startOffset() <= this.endOffset()
&& region.endOffset() <= this.endOffset();
}
@Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + startRow;
result = prime * result + startColumn;
result = prime * result + endRow;
result = prime * result + endColumn;
return result;
}
@Override public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
final SourceRegion other = (SourceRegion) obj;
if(startRow != other.startRow)
return false;
if(startColumn != other.startColumn)
return false;
if(endRow != other.endRow)
return false;
if(endColumn != other.endColumn)
return false;
return true;
}
@Override public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(startOffset);
sb.append("-");
sb.append(endOffset);
if(startRow >= 0 && endRow >= 0) {
sb.append(" ");
sb.append(startRow);
sb.append("-");
sb.append(endRow);
}
if(startColumn >= 0 && endColumn >= 0) {
sb.append(" ");
sb.append(startColumn);
sb.append("-");
sb.append(endColumn);
}
return sb.toString();
}
}
|
maltaisn/transform-swf
|
src/main/java/com/flagstone/transform/filter/ColorMatrixFilter.java
|
/*
* ColorMatrixFilter.java
* Transform
*
* Copyright (c) 2009-2010 Flagstone Software Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Flagstone Software Ltd. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.flagstone.transform.filter;
import java.io.IOException;
import java.util.Arrays;
import com.flagstone.transform.coder.Context;
import com.flagstone.transform.coder.SWFDecoder;
import com.flagstone.transform.coder.SWFEncoder;
/**
* ColorMatrixFilter is used to apply a colour transform to the pixels of an
* object on the display list.
*/
public final class ColorMatrixFilter implements Filter {
/** Format string used in toString() method. */
private static final String FORMAT = "ColorMatrix: { matrix=["
+ "[%f %f %f %f %f];[%f %f %f %f %f];"
+ "[%f %f %f %f %f];[%f %f %f %f %f];]}";
/** The number of elements in the colour matrix. */
private static final int MATRIX_SIZE = 20;
/** The colour matrix. */
private final transient float[] matrix;
/**
* Creates and initialises a ColorMatrix object using values encoded
* in the Flash binary format.
*
* @param coder
* an SWFDecoder object that contains the encoded Flash data.
*
* @throws IOException
* if an error occurs while decoding the data.
*/
public ColorMatrixFilter(final SWFDecoder coder) throws IOException {
matrix = new float[MATRIX_SIZE];
for (int i = 0; i < MATRIX_SIZE; i++) {
matrix[i] = Float.intBitsToFloat(coder.readInt());
}
}
/**
* Create a ColorMatrixFilter with the specified matrix.
*
* @param aMatrix a matrix that will be applied to each pixel of the
* object.
*/
public ColorMatrixFilter(final float[] aMatrix) {
if ((aMatrix == null) || (aMatrix.length != MATRIX_SIZE)) {
throw new IllegalArgumentException("Value not set");
}
matrix = Arrays.copyOf(aMatrix, aMatrix.length);
}
/**
* Get the colour matrix.
*
* @return the 5x4 matrix that will be applied to the object.
*/
public float[] getMatrix() {
return Arrays.copyOf(matrix, matrix.length);
}
@Override
public String toString() {
// CHECKSTYLE:OFF
return String.format(FORMAT,
matrix[0], matrix[1], matrix[2], matrix[3], matrix[4],
matrix[5], matrix[6], matrix[7], matrix[8], matrix[9],
matrix[10], matrix[11], matrix[12], matrix[13], matrix[14],
matrix[15], matrix[16], matrix[17], matrix[18], matrix[19]
);
// CHECKSTYLE:ON
}
@Override
public boolean equals(final Object object) {
boolean result;
ColorMatrixFilter filter;
if (object == null) {
result = false;
} else if (object == this) {
result = true;
} else if (object instanceof ColorMatrixFilter) {
filter = (ColorMatrixFilter) object;
result = Arrays.equals(matrix, filter.matrix);
} else {
result = false;
}
return result;
}
@Override
public int hashCode() {
return Arrays.hashCode(matrix);
}
/** {@inheritDoc} */
public int prepareToEncode(final Context context) {
// CHECKSTYLE IGNORE MagicNumberCheck FOR NEXT 1 LINES
return 81;
}
/** {@inheritDoc} */
public void encode(final SWFEncoder coder, final Context context)
throws IOException {
coder.writeByte(FilterTypes.COLOR_MATRIX);
for (final float value : matrix) {
coder.writeInt(Float.floatToIntBits(value));
}
}
}
|
wgnet/wds_qt
|
qtdeclarative/src/quick/items/qquickview.cpp
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickview.h"
#include "qquickview_p.h"
#include "qquickwindow_p.h"
#include "qquickitem_p.h"
#include "qquickitemchangelistener_p.h"
#include <private/qqmldebugconnector_p.h>
#include <private/qquickprofiler_p.h>
#include <private/qqmldebugserviceinterfaces_p.h>
#include <private/qqmlmemoryprofiler_p.h>
#include <QtQml/qqmlengine.h>
#include <private/qqmlengine_p.h>
#include <QtCore/qbasictimer.h>
QT_BEGIN_NAMESPACE
void QQuickViewPrivate::init(QQmlEngine* e)
{
Q_Q(QQuickView);
engine = e;
if (engine.isNull())
engine = new QQmlEngine(q);
if (!engine.data()->incubationController())
engine.data()->setIncubationController(q->incubationController());
{
// The content item has CppOwnership policy (set in QQuickWindow). Ensure the presence of a JS
// wrapper so that the garbage collector can see the policy.
QV4::ExecutionEngine *v4 = QQmlEnginePrivate::getV4Engine(engine.data());
QV4::QObjectWrapper::wrap(v4, contentItem);
}
QQmlInspectorService *service = QQmlDebugConnector::service<QQmlInspectorService>();
if (service)
service->addView(q);
}
QQuickViewPrivate::QQuickViewPrivate()
: root(0), component(0), resizeMode(QQuickView::SizeViewToRootObject), initialSize(0,0)
{
}
QQuickViewPrivate::~QQuickViewPrivate()
{
QQmlInspectorService *service = QQmlDebugConnector::service<QQmlInspectorService>();
if (service)
service->removeView(q_func());
}
void QQuickViewPrivate::execute()
{
Q_Q(QQuickView);
if (!engine) {
qWarning() << "QQuickView: invalid qml engine.";
return;
}
if (root) {
delete root;
root = 0;
}
if (component) {
delete component;
component = 0;
}
if (!source.isEmpty()) {
QML_MEMORY_SCOPE_URL(engine.data()->baseUrl().resolved(source));
component = new QQmlComponent(engine.data(), source, q);
if (!component->isLoading()) {
q->continueExecute();
} else {
QObject::connect(component, SIGNAL(statusChanged(QQmlComponent::Status)),
q, SLOT(continueExecute()));
}
}
}
void QQuickViewPrivate::itemGeometryChanged(QQuickItem *resizeItem, const QRectF &newGeometry, const QRectF &oldGeometry)
{
Q_Q(QQuickView);
if (resizeItem == root && resizeMode == QQuickView::SizeViewToRootObject) {
// wait for both width and height to be changed
resizetimer.start(0,q);
}
QQuickItemChangeListener::itemGeometryChanged(resizeItem, newGeometry, oldGeometry);
}
/*!
\class QQuickView
\since 5.0
\brief The QQuickView class provides a window for displaying a Qt Quick user interface.
\inmodule QtQuick
This is a convenience subclass of QQuickWindow which
will automatically load and display a QML scene when given the URL of the main source file. Alternatively,
you can instantiate your own objects using QQmlComponent and place them in a manually setup QQuickWindow.
Typical usage:
\code
QQuickView *view = new QQuickView;
view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
view->show();
\endcode
To receive errors related to loading and executing QML with QQuickView,
you can connect to the statusChanged() signal and monitor for QQuickView::Error.
The errors are available via QQuickView::errors().
QQuickView also manages sizing of the view and root object. By default, the \l resizeMode
is SizeViewToRootObject, which will load the component and resize it to the
size of the view. Alternatively the resizeMode may be set to SizeRootObjectToView which
will resize the view to the size of the root object.
\sa {Exposing Attributes of C++ Types to QML}, QQuickWidget
*/
/*! \fn void QQuickView::statusChanged(QQuickView::Status status)
This signal is emitted when the component's current \a status changes.
*/
/*!
Constructs a QQuickView with the given \a parent.
The default value of \a parent is 0.
*/
QQuickView::QQuickView(QWindow *parent)
: QQuickWindow(*(new QQuickViewPrivate), parent)
{
d_func()->init();
}
/*!
Constructs a QQuickView with the given QML \a source and \a parent.
The default value of \a parent is 0.
*/
QQuickView::QQuickView(const QUrl &source, QWindow *parent)
: QQuickWindow(*(new QQuickViewPrivate), parent)
{
d_func()->init();
setSource(source);
}
/*!
Constructs a QQuickView with the given QML \a engine and \a parent.
Note: In this case, the QQuickView does not own the given \a engine object;
it is the caller's responsibility to destroy the engine. If the \a engine is deleted
before the view, status() will return QQuickView::Error.
\sa Status, status(), errors()
*/
QQuickView::QQuickView(QQmlEngine* engine, QWindow *parent)
: QQuickWindow(*(new QQuickViewPrivate), parent)
{
Q_ASSERT(engine);
d_func()->init(engine);
}
/*!
Destroys the QQuickView.
*/
QQuickView::~QQuickView()
{
// Ensure that the component is destroyed before the engine; the engine may
// be a child of the QQuickViewPrivate, and will be destroyed by its dtor
Q_D(QQuickView);
delete d->root;
d->root = 0;
}
/*!
\property QQuickView::source
\brief The URL of the source of the QML component.
Ensure that the URL provided is full and correct, in particular, use
\l QUrl::fromLocalFile() when loading a file from the local filesystem.
Note that setting a source URL will result in the QML component being
instantiated, even if the URL is unchanged from the current value.
*/
/*!
Sets the source to the \a url, loads the QML component and instantiates it.
Ensure that the URL provided is full and correct, in particular, use
\l QUrl::fromLocalFile() when loading a file from the local filesystem.
Calling this method multiple times with the same url will result
in the QML component being reinstantiated.
*/
void QQuickView::setSource(const QUrl& url)
{
Q_D(QQuickView);
d->source = url;
d->execute();
}
/*!
\internal
Set the source \a url, \a component and content \a item (root of the QML object hierarchy) directly.
*/
void QQuickView::setContent(const QUrl& url, QQmlComponent *component, QObject* item)
{
Q_D(QQuickView);
d->source = url;
d->component = component;
if (d->component && d->component->isError()) {
QList<QQmlError> errorList = d->component->errors();
foreach (const QQmlError &error, errorList) {
QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), 0).warning()
<< error;
}
emit statusChanged(status());
return;
}
d->setRootObject(item);
emit statusChanged(status());
}
/*!
Returns the source URL, if set.
\sa setSource()
*/
QUrl QQuickView::source() const
{
Q_D(const QQuickView);
return d->source;
}
/*!
Returns a pointer to the QQmlEngine used for instantiating
QML Components.
*/
QQmlEngine* QQuickView::engine() const
{
Q_D(const QQuickView);
return d->engine ? const_cast<QQmlEngine *>(d->engine.data()) : 0;
}
/*!
This function returns the root of the context hierarchy. Each QML
component is instantiated in a QQmlContext. QQmlContext's are
essential for passing data to QML components. In QML, contexts are
arranged hierarchically and this hierarchy is managed by the
QQmlEngine.
*/
QQmlContext* QQuickView::rootContext() const
{
Q_D(const QQuickView);
return d->engine ? d->engine.data()->rootContext() : 0;
}
/*!
\enum QQuickView::Status
Specifies the loading status of the QQuickView.
\value Null This QQuickView has no source set.
\value Ready This QQuickView has loaded and created the QML component.
\value Loading This QQuickView is loading network data.
\value Error One or more errors has occurred. Call errors() to retrieve a list
of errors.
*/
/*! \enum QQuickView::ResizeMode
This enum specifies how to resize the view.
\value SizeViewToRootObject The view resizes with the root item in the QML.
\value SizeRootObjectToView The view will automatically resize the root item to the size of the view.
*/
/*!
\property QQuickView::status
The component's current \l{QQuickView::Status} {status}.
*/
QQuickView::Status QQuickView::status() const
{
Q_D(const QQuickView);
if (!d->engine)
return QQuickView::Error;
if (!d->component)
return QQuickView::Null;
if (d->component->status() == QQmlComponent::Ready && !d->root)
return QQuickView::Error;
return QQuickView::Status(d->component->status());
}
/*!
Return the list of errors that occurred during the last compile or create
operation. When the status is not Error, an empty list is returned.
*/
QList<QQmlError> QQuickView::errors() const
{
Q_D(const QQuickView);
QList<QQmlError> errs;
if (d->component)
errs = d->component->errors();
if (!d->engine) {
QQmlError error;
error.setDescription(QLatin1String("QQuickView: invalid qml engine."));
errs << error;
} else if (d->component && d->component->status() == QQmlComponent::Ready && !d->root) {
QQmlError error;
error.setDescription(QLatin1String("QQuickView: invalid root object."));
errs << error;
}
return errs;
}
/*!
\property QQuickView::resizeMode
\brief whether the view should resize the window contents
If this property is set to SizeViewToRootObject (the default), the view
resizes to the size of the root item in the QML.
If this property is set to SizeRootObjectToView, the view will
automatically resize the root item to the size of the view.
\sa initialSize()
*/
void QQuickView::setResizeMode(ResizeMode mode)
{
Q_D(QQuickView);
if (d->resizeMode == mode)
return;
if (d->root) {
if (d->resizeMode == SizeViewToRootObject) {
QQuickItemPrivate *p = QQuickItemPrivate::get(d->root);
p->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
}
}
d->resizeMode = mode;
if (d->root) {
d->initResize();
}
}
void QQuickViewPrivate::initResize()
{
if (root) {
if (resizeMode == QQuickView::SizeViewToRootObject) {
QQuickItemPrivate *p = QQuickItemPrivate::get(root);
p->addItemChangeListener(this, QQuickItemPrivate::Geometry);
}
}
updateSize();
}
void QQuickViewPrivate::updateSize()
{
Q_Q(QQuickView);
if (!root)
return;
if (resizeMode == QQuickView::SizeViewToRootObject) {
QSize newSize = QSize(root->width(), root->height());
if (newSize.isValid() && newSize != q->size()) {
q->resize(newSize);
}
} else if (resizeMode == QQuickView::SizeRootObjectToView) {
if (!qFuzzyCompare(q->width(), root->width()))
root->setWidth(q->width());
if (!qFuzzyCompare(q->height(), root->height()))
root->setHeight(q->height());
}
}
QSize QQuickViewPrivate::rootObjectSize() const
{
QSize rootObjectSize(0,0);
int widthCandidate = -1;
int heightCandidate = -1;
if (root) {
widthCandidate = root->width();
heightCandidate = root->height();
}
if (widthCandidate > 0) {
rootObjectSize.setWidth(widthCandidate);
}
if (heightCandidate > 0) {
rootObjectSize.setHeight(heightCandidate);
}
return rootObjectSize;
}
QQuickView::ResizeMode QQuickView::resizeMode() const
{
Q_D(const QQuickView);
return d->resizeMode;
}
/*!
\internal
*/
void QQuickView::continueExecute()
{
Q_D(QQuickView);
disconnect(d->component, SIGNAL(statusChanged(QQmlComponent::Status)), this, SLOT(continueExecute()));
if (d->component->isError()) {
QList<QQmlError> errorList = d->component->errors();
foreach (const QQmlError &error, errorList) {
QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), 0).warning()
<< error;
}
emit statusChanged(status());
return;
}
QObject *obj = d->component->create();
if (d->component->isError()) {
QList<QQmlError> errorList = d->component->errors();
foreach (const QQmlError &error, errorList) {
QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), 0).warning()
<< error;
}
emit statusChanged(status());
return;
}
d->setRootObject(obj);
emit statusChanged(status());
}
/*!
\internal
*/
void QQuickViewPrivate::setRootObject(QObject *obj)
{
Q_Q(QQuickView);
if (root == obj)
return;
if (QQuickItem *sgItem = qobject_cast<QQuickItem *>(obj)) {
root = sgItem;
sgItem->setParentItem(q->QQuickWindow::contentItem());
} else if (qobject_cast<QWindow *>(obj)) {
qWarning() << "QQuickView does not support using windows as a root item." << endl
<< endl
<< "If you wish to create your root window from QML, consider using QQmlApplicationEngine instead." << endl;
} else {
qWarning() << "QQuickView only supports loading of root objects that derive from QQuickItem." << endl
<< endl
<< "Ensure your QML code is written for QtQuick 2, and uses a root that is or" << endl
<< "inherits from QtQuick's Item (not a Timer, QtObject, etc)." << endl;
delete obj;
root = 0;
}
if (root) {
initialSize = rootObjectSize();
if ((resizeMode == QQuickView::SizeViewToRootObject || q->width() <= 1 || q->height() <= 1) &&
initialSize != q->size()) {
q->resize(initialSize);
}
initResize();
}
}
/*!
\internal
If the \l {QTimerEvent} {timer event} \a e is this
view's resize timer, sceneResized() is emitted.
*/
void QQuickView::timerEvent(QTimerEvent* e)
{
Q_D(QQuickView);
if (!e || e->timerId() == d->resizetimer.timerId()) {
d->updateSize();
d->resizetimer.stop();
}
}
/*!
\internal
Preferred size follows the root object geometry.
*/
QSize QQuickView::sizeHint() const
{
Q_D(const QQuickView);
QSize rootObjectSize = d->rootObjectSize();
if (rootObjectSize.isEmpty()) {
return size();
} else {
return rootObjectSize;
}
}
/*!
Returns the initial size of the root object.
If \l resizeMode is QQuickItem::SizeRootObjectToView the root object will be
resized to the size of the view. initialSize contains the size of the
root object before it was resized.
*/
QSize QQuickView::initialSize() const
{
Q_D(const QQuickView);
return d->initialSize;
}
/*!
Returns the view's root \l {QQuickItem} {item}.
*/
QQuickItem *QQuickView::rootObject() const
{
Q_D(const QQuickView);
return d->root;
}
/*!
\internal
This function handles the \l {QResizeEvent} {resize event}
\a e.
*/
void QQuickView::resizeEvent(QResizeEvent *e)
{
Q_D(QQuickView);
if (d->resizeMode == SizeRootObjectToView)
d->updateSize();
QQuickWindow::resizeEvent(e);
}
/*! \reimp */
void QQuickView::keyPressEvent(QKeyEvent *e)
{
Q_QUICK_INPUT_PROFILE(addEvent<QQuickProfiler::Key>());
QQuickWindow::keyPressEvent(e);
}
/*! \reimp */
void QQuickView::keyReleaseEvent(QKeyEvent *e)
{
Q_QUICK_INPUT_PROFILE(addEvent<QQuickProfiler::Key>());
QQuickWindow::keyReleaseEvent(e);
}
/*! \reimp */
void QQuickView::mouseMoveEvent(QMouseEvent *e)
{
Q_QUICK_INPUT_PROFILE(addEvent<QQuickProfiler::Mouse>());
QQuickWindow::mouseMoveEvent(e);
}
/*! \reimp */
void QQuickView::mousePressEvent(QMouseEvent *e)
{
Q_QUICK_INPUT_PROFILE(addEvent<QQuickProfiler::Mouse>());
QQuickWindow::mousePressEvent(e);
}
/*! \reimp */
void QQuickView::mouseReleaseEvent(QMouseEvent *e)
{
Q_QUICK_INPUT_PROFILE(addEvent<QQuickProfiler::Mouse>());
QQuickWindow::mouseReleaseEvent(e);
}
QT_END_NAMESPACE
|
hokamc/core-ng-project
|
core-ng/src/test/java/core/framework/module/ExecutorConfigTest.java
|
<gh_stars>100-1000
package core.framework.module;
import core.framework.async.Executor;
import core.framework.internal.module.ModuleContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author neo
*/
class ExecutorConfigTest {
private ExecutorConfig config;
@BeforeEach
void createExecutorConfig() {
config = new ExecutorConfig();
config.initialize(new ModuleContext(null), null);
}
@Test
void createExecutor() {
Executor executor = config.createExecutor(null, 1);
assertThat(executor).isNotNull();
}
}
|
KHWeb19/Homework
|
DongHyeokLee/java/9th/Homework5&6&7/src/Score.java
|
<gh_stars>10-100
import java.util.Scanner;
public class Score {
private Scanner scan;
int sum = 0;
public void initScore(){
System.out.print("수학 점수를 입력하시오 : ");
scan = new Scanner(System.in);
int mathScore = scan.nextInt();
System.out.print("국어 점수를 입력하시오 : ");
scan = new Scanner(System.in);
int koreanScore = scan.nextInt();
System.out.print("영어 점수를 입력하시오 : ");
scan = new Scanner(System.in);
int englishScore = scan.nextInt();
sum = mathScore + koreanScore + englishScore;
}
}
|
ministryofjustice/smartdown
|
spec/api/question_spec.rb
|
require 'smartdown/api/question'
require 'smartdown/api/date_question'
require 'smartdown/model/element/question/date'
require 'smartdown/model/element/markdown_heading'
require 'smartdown/model/element/markdown_line'
describe Smartdown::Api::Question do
subject(:question) { Smartdown::Api::Question.new(elements) }
let(:question_element) {
Smartdown::Model::Element::Question::Date.new(name, *args)
}
let(:aliaz) { nil }
let(:args) { [start_year, end_year, aliaz] }
let(:name) { "a question" }
let(:start_year) { nil }
let(:end_year) { nil }
let(:heading_content) { "hehehe" }
let(:heading) { Smartdown::Model::Element::MarkdownHeading}
let(:body_content) { 'I <3 bodyshopping' }
let(:body_element) {
Smartdown::Model::Element::MarkdownLine.new(body_content)
}
let(:post_body_content) { 'hur hur such content' }
let(:post_body_element) {
Smartdown::Model::Element::MarkdownLine.new(post_body_content)
}
context "with a body and post_body" do
let(:elements) { [heading, body_element, question_element, post_body_element] }
describe "#body" do
it 'returns the content before the question element' do
expect(question.body).to eq(body_content)
end
end
describe '#post_body' do
it 'returns the content after the question element' do
expect(question.post_body).to eq(post_body_content)
end
end
end
context "missing a body" do
let(:elements) { [heading, question_element, post_body_element] }
describe "#body" do
it 'returns nil' do
expect(question.body).to eq(nil)
end
end
describe '#post_body' do
it 'returns the content after the question element' do
expect(question.post_body).to eq(post_body_content)
end
end
end
context "missing a post body" do
let(:elements) { [heading, body_element, question_element] }
describe "#body" do
it 'returns the content before the question element' do
expect(question.body).to eq(body_content)
end
end
describe '#post_body' do
it 'returns nil' do
expect(question.post_body).to eq(nil)
end
end
end
context "missing a body and post body" do
let(:elements) { [heading, question_element] }
describe "#body" do
it 'returns nil' do
expect(question.body).to eq(nil)
end
end
describe '#post_body' do
it 'returns nil' do
expect(question.post_body).to eq(nil)
end
end
end
end
|
mahmoudimus/ac
|
crowd-support/src/main/java/com/atlassian/plugin/connect/crowd/permissions/ConnectCrowdSysadminHttpClientImpl.java
|
<reponame>mahmoudimus/ac<filename>crowd-support/src/main/java/com/atlassian/plugin/connect/crowd/permissions/ConnectCrowdSysadminHttpClientImpl.java
package com.atlassian.plugin.connect.crowd.permissions;
import com.atlassian.applinks.api.ApplicationLink;
import com.atlassian.applinks.api.ApplicationLinkRequest;
import com.atlassian.applinks.api.ApplicationLinkService;
import com.atlassian.applinks.api.CredentialsRequiredException;
import com.atlassian.applinks.api.ReadOnlyApplicationLink;
import com.atlassian.applinks.api.application.crowd.CrowdApplicationType;
import com.atlassian.crowd.exception.ApplicationAccessDeniedException;
import com.atlassian.crowd.exception.ApplicationPermissionException;
import com.atlassian.crowd.exception.InactiveAccountException;
import com.atlassian.crowd.exception.InvalidAuthenticationException;
import com.atlassian.crowd.exception.OperationFailedException;
import com.atlassian.crowd.model.authentication.UserAuthenticationContext;
import com.atlassian.crowd.model.authentication.ValidationFactor;
import com.atlassian.plugin.connect.crowd.usermanagement.CrowdClientProvider;
import com.atlassian.plugin.spring.scanner.annotation.component.JiraComponent;
import com.atlassian.sal.api.net.Request;
import com.atlassian.sal.api.net.ResponseException;
import com.google.common.collect.Iterables;
import org.springframework.beans.factory.annotation.Autowired;
import java.net.HttpCookie;
import java.util.Optional;
@JiraComponent
public class ConnectCrowdSysadminHttpClientImpl
implements ConnectCrowdSysadminHttpClient {
private final ApplicationLinkService applicationLinkService;
private final CrowdClientProvider crowdClientProvider;
@Autowired
public ConnectCrowdSysadminHttpClientImpl(
ApplicationLinkService applicationLinkService,
CrowdClientProvider crowdClientProvider) {
this.applicationLinkService = applicationLinkService;
this.crowdClientProvider = crowdClientProvider;
}
// This code is adapted from com.atlassian.usermanagement.client.impl.UserManagementRequestServiceImpl#executeAsSysadmin
// in the https://stash.atlassian.com/projects/UN/repos/user-management repo.
// https://ecosystem.atlassian.net/browse/ACDEV-2237 has been raised to move to a stable means of granting admin permission
// provided by the user management plugin, once one becomes available.
public void executeAsSysadmin(Request.MethodType methodType, String url, String jsonString)
throws CredentialsRequiredException, ResponseException,
ApplicationPermissionException, InactiveAccountException,
ApplicationAccessDeniedException, OperationFailedException,
InvalidAuthenticationException {
Optional<ApplicationLink> possibleCrowd = Optional.ofNullable(Iterables.getFirst(applicationLinkService.getApplicationLinks(CrowdApplicationType.class), null));
if (!possibleCrowd.isPresent()) {
throw new OperationFailedException("There was no Crowd application link. This is a problem");
}
ReadOnlyApplicationLink crowd = possibleCrowd.get();
ApplicationLinkRequest request = crowd.createAuthenticatedRequestFactory().createRequest(methodType, url);
request.addHeader("Cookie", generateSysadminCookie().toString());
request.addHeader("Content-Type", "application/json");
request.setEntity(jsonString);
request.execute();
}
private HttpCookie generateSysadminCookie()
throws InactiveAccountException, OperationFailedException,
ApplicationAccessDeniedException, ApplicationPermissionException,
InvalidAuthenticationException {
final UserAuthenticationContext sysadminAuthenticationContext = new UserAuthenticationContext("sysadmin",
null,
new ValidationFactor[]{}, "jira");
{
String ssoToken = crowdClientProvider.getCrowdClient().authenticateSSOUserWithoutValidatingPassword(sysadminAuthenticationContext);
return new HttpCookie("studio.crowd.tokenkey", ssoToken);
}
}
}
|
aleckan53/teamapp-client
|
src/features/Search/actions.js
|
import Api from './api'
export default {
loadProjects (state, setState) {
Api.getAllProjects(state.searchTerm, state.currentPage)
.then(res => setState({
...state,
totalProjects: res.count,
// prevents bubbling up the state
projects: state.currentPage > 1
? [...state.projects, ...res.projects]
: res.projects
}))
},
nextPage (state, setState) {
return state.currentPage === Math.ceil(state.totalProjects/8) // 8 = api response limit
? state.currentPage
: setState({
...state,
currentPage: ++state.currentPage
})
},
searchByTerm (e, state, setState) {
document.getElementById('Scrollable').scrollTop = 0
setState({
...state,
searchTerm: e.target.value,
currentPage: 1
})
},
initialLoad (timer, setTyping, state, setState) {
clearTimeout(timer)
this.loadProjects(state, setState)
setTyping(false)
},
delayedLoad (timer, setTimer, setTyping, state, setState) {
clearTimeout(timer)
setTyping(true)
setTimer(setTimeout(() => {
this.loadProjects(state, setState)
setTyping(false)
}, 600))
}
}
|
maciek1651g/SuperZespol2500K
|
src/LoginPage/ErrorMessage.js
|
<gh_stars>0
import styles from "./loginStyle.module.css";
import Icons from "../img/iconsSVG";
import React from "react";
let closeHandler = null;
const ErrorMessage = (props) => {
const close = () => {
props.setMessage(null);
}
if(props.message!==null)
{
if(closeHandler!=null)
clearTimeout(closeHandler);
closeHandler = setTimeout(close, 3000);
}
return (
<div className={styles.errorMessage}>
<div style={{display: "flex", alignItems: "center", color: "white", fontWeight: "500", margin: "0"}}>
<p style={{margin: "0 40px 0 20px"}}>{props.message}</p>
</div>
<div onClick={close} className={styles.closeButton} style={{color: "#444", width:"30px", height:"30px", position: "absolute", top: "5px", right: "5px"}}>
{Icons.crossIco}
</div>
</div>
)
}
export default ErrorMessage;
|
niuware/instpector
|
examples/get_followers.py
|
from sys import argv
from context import Instpector, endpoints
def get_followers(**options):
instpector = Instpector()
if not instpector.login(user=options.get("user"), password=options.get("password")):
return
followers = endpoints.factory.create("followers", instpector)
for follower in followers.of_user(options.get("target_user_id")):
print(follower)
instpector.logout()
if __name__ == '__main__':
if len(argv) < 6:
print((
"Missing arguments: "
"--user {user} "
"--password {password} "
"--target_user_id {user_id}"
))
exit(1)
get_followers(
user=argv[2],
password=argv[4],
target_user_id=argv[6]
)
|
nbv3/voogasalad_CS308
|
src/com/syntacticsugar/vooga/gameplayer/universe/map/tiles/effects/TileEffectType.java
|
package com.syntacticsugar.vooga.gameplayer.universe.map.tiles.effects;
public enum TileEffectType {
DamagePersistent, DamageTemporary, Slow;
}
|
openharmony-gitee-mirror/ace_ace_engine
|
frameworks/core/components/video/video_component_v2.h
|
<reponame>openharmony-gitee-mirror/ace_ace_engine
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_VIDEO_VIDEO_COMPONENT_V2_H
#define FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_VIDEO_VIDEO_COMPONENT_V2_H
#include "core/components/video/video_component.h"
namespace OHOS::Ace {
class VideoControllerV2 : public virtual AceType {
DECLARE_ACE_TYPE(VideoControllerV2, AceType);
public:
void Start()
{
for (const auto& item : controllers_) {
item->Start();
}
}
void Pause()
{
for (const auto& item : controllers_) {
item->Pause();
}
}
void Stop()
{
for (const auto& item : controllers_) {
item->Stop();
}
}
void SeekTo(uint32_t pos)
{
for (const auto& item : controllers_) {
item->SeekTo(pos);
}
}
void RequestFullscreen(bool isPortrait)
{
for (const auto& item : controllers_) {
item->RequestFullscreen(isPortrait);
}
}
void ExitFullscreen(bool isSync)
{
for (const auto& item : controllers_) {
item->ExitFullscreen(isSync);
}
}
void AddVideoController(const RefPtr<VideoController>& videoController)
{
auto it = std::find(controllers_.begin(), controllers_.end(), videoController);
if (it != controllers_.end()) {
LOGW("Controller is already existed");
return;
}
controllers_.emplace_back(videoController);
}
void RemoveVideoController(const RefPtr<VideoController>& videoController)
{
if (videoController) {
controllers_.remove(videoController);
}
}
void Clear()
{
controllers_.clear();
}
private:
std::list<RefPtr<VideoController>> controllers_;
};
// A component can show Video.
class ACE_EXPORT VideoComponentV2 : public VideoComponent {
DECLARE_ACE_TYPE(VideoComponentV2, VideoComponent);
public:
using SaveComponentEvent = std::function<void(std::unordered_map<std::string, RefPtr<Component>>)>;
VideoComponentV2() = default;
~VideoComponentV2() override;
RefPtr<Element> CreateElement() override;
std::unordered_map<std::string, RefPtr<Component>>& GetGuestureComponentMap()
{
return map_;
}
void SetGuestureComponentMap(std::unordered_map<std::string, RefPtr<Component>> map)
{
map_ = map;
}
void SetVideoControllerV2(const RefPtr<VideoControllerV2>& videoControllerV2)
{
videoControllerV2_ = videoControllerV2;
}
void SetVideoController(const RefPtr<VideoController>& videoController) override
{
if (videoControllerV2_) {
videoControllerV2_->RemoveVideoController(GetVideoController());
}
VideoComponent::SetVideoController(videoController);
if (videoControllerV2_) {
videoControllerV2_->AddVideoController(GetVideoController());
}
}
void SetSaveComponentEvent(SaveComponentEvent&& saveComponentEvent)
{
saveComponentEvent_ = std::move(saveComponentEvent);
}
SaveComponentEvent GetSaveComponentEvent()
{
return saveComponentEvent_;
}
private:
std::unordered_map<std::string, RefPtr<Component>> map_;
RefPtr<VideoControllerV2> videoControllerV2_;
SaveComponentEvent saveComponentEvent_;
};
} // namespace OHOS::Ace
#endif // FOUNDATION_ACE_FRAMEWORKS_CORE_COMPONENTS_VIDEO_VIDEO_COMPONENT_V2_H
|
alphonsetai/RGA
|
RadeonGPUAnalyzerGUI/include/rgSourceEditorSearcher.h
|
#pragma once
// Local.
#include <RadeonGPUAnalyzerGUI/include/qt/rgFindTextWidget.h>
// Forward declarations.
class rgSourceCodeEditor;
// An object responsible for searching a source editor using an rgFindTextWidget.
class rgSourceEditorSearcher : public ISearchable
{
public:
rgSourceEditorSearcher();
virtual ~rgSourceEditorSearcher() = default;
// Override FindNext to find the next instance of text within the source editor.
virtual bool FindNext(const QString& searchString) override;
// Reset the current search.
virtual void ResetSearch() override;
// Select the current search result in the source editor.
virtual void SelectResults() override;
// Set the target source editor being searched.
void SetTargetEditor(rgSourceCodeEditor* pTargetEditor);
private:
// Set cursor for the current editor without changing kernel/correlation context.
void SetCodeEditorCursor(const QTextCursor& cursor);
// The location in the document of the last search result.
int m_lastFoundPosition;
// The string to search for in the document.
QString m_searchString;
// The flag used to determine whether or not matching case matters when searching.
bool m_matchCase = false;
// The source editor instance whose text is being searched.
rgSourceCodeEditor* m_pTargetEditor = nullptr;
};
|
djoun52/udemy_reacy
|
2-react-router/src/Components/Error404/Error404.js
|
<gh_stars>0
import React from 'react'
import { useNavigate } from 'react-router-dom'
export default function Error404() {
const navigate = useNavigate()
const goHome = ()=> {
navigate("/")
}
return (
<div>
<h1>error 404 Page not found</h1>
<div className="d-flex justify-content-center">
<button className="btn btn-primary text-center"
onClick={goHome}> Retourner à l'accueil</button>
</div>
</div>
)
}
|
madhubandubey9/StarEngine
|
StarEngine/jni/EventLoop.h
|
#ifdef ANDROID
#pragma once
#include "defines.h"
#include <android_native_app_glue.h>
#include "BaseGame.h"
#include "Context.h"
#include "TimeManager.h"
namespace star
{
class SceneManager;
class EventLoop final
{
public:
~EventLoop();
static EventLoop * GetInstance();
void Run();
void End();
void Initialize(android_app* pApplication, BaseGame * pBaseGame);
const android_app * GetAndroidApp() const;
protected:
private:
static EventLoop *mEventLoop;
bool mMainGameInitialized;
bool mEnabled;
bool mQuit;
BaseGame* mMainGame;
Context mContext;
android_app* mApplicationPtr;
EventLoop();
static void activityCallback(android_app* pApplication, int32_t pCommand);
static int32 inputCallback(android_app* pApplication, AInputEvent* pEvent);
};
}
#endif
|
jeongjoonyoo/AMD_RGA
|
Utils/Include/rgOptionalRef.h
|
#ifdef _WIN32
#define WEAK_LINK __declspec(selectany)
#else
#define WEAK_LINK __attribute__((weak))
#endif
// This is a "poor man's" implementation of c++ "optional" concept for references.
// It is useful when you need to return a reference that can be "empty".
// Example:
//
// class Item { public: void bar() {} };
//
// class Vector
// {
// public:
// rgOptionalRef<Item> GetItem(int i) {
// if (i >= m_items.size())
// return false;
// else
// return m_items[i];
// }
// private:
// std::vector<Item> m_items;
// };
//
// void foo(Vector& v, int n)
// {
// if (auto item = v.GetItem(n)) {
// item->bar();
// }
// }
//
// Notes:
// 1. This class uses static "empty" object of class T, so use it carefully when sizeof(T) is huge.
// 2. If your compiler supports c++17, consider using std::optional instead.
//
template<typename T>
class rgOptionalRef
{
public:
rgOptionalRef() : m_good(false), m_ref(ms_emptyObj) {}
rgOptionalRef(bool b) : m_good(false), m_ref(ms_emptyObj) { assert(b == false); }
rgOptionalRef(T& ref) : m_ref(ref), m_good(true) {}
inline rgOptionalRef& operator=(T& ref) { m_ref = ref; m_good = true; return *this; }
inline operator bool() { return m_good; }
inline T& operator*() { return m_ref.get(); }
inline T* operator->() { return &m_ref.get(); }
inline T& get() { return m_ref.get(); }
private:
std::reference_wrapper<T> m_ref;
bool m_good;
static T ms_emptyObj;
};
template<typename T> WEAK_LINK
T rgOptionalRef<T>::ms_emptyObj;
|
juhoniinikoski/neroksi-app
|
neroksi-api/src/graphql/types/PageInfo.js
|
import { gql } from 'apollo-server'
export const typeDefs = gql`
type PageInfo {
hasPreviousPage: Boolean!
hasNextPage: Boolean!
startCursor: String
endCursor: String
}
`
export const resolvers = {}
export default {
typeDefs,
resolvers,
}
|
alex-myzhao/FE-6083
|
server-koa/routes/index.js
|
<reponame>alex-myzhao/FE-6083
module.exports = (router) => {
router.prefix('/v1')
router.use('/auth', require('./auth'))
router.use('/users', require('./users'))
router.use('/workspace', require('./workspaces'))
router.use('/winvitation', require('./winvitations'))
router.use('/channel', require('./channels'))
router.use('/cinvitation', require('./cinvitations'))
router.use('/message', require('./messages'))
router.use('/wmember', require('./wmembers'))
router.use('/cmember', require('./cmembers'))
}
|
gdeverlant/dynamic-extensions-for-alfresco
|
webscripts/src/main/java/com/github/dynamicextensionsalfresco/webscripts/UrlModel.java
|
package com.github.dynamicextensionsalfresco.webscripts;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.util.Assert;
import java.util.Collections;
import java.util.Map;
/**
*
* Model representing 'url' object for use. The code is taken from the Spring Web Scripts 1.0.0 release. Later versions
* of the Web Scripts API change the URLModel class into an interface.
* <p>
* Since Dynamic Extensions strives to support older Alfresco releases, we simply use take ownership of this problem
* using this class.
* <p>
* {@link com.github.dynamicextensionsalfresco.webscripts.resolutions.TemplateResolution} uses this class for the 'url' helper in the template model.
* <p>
* This class has public visibility in order to satisfy JavaBeans conventions. (Freemarker requires models to follow
* JavaBeans conventions.)
*
* @author <NAME>
*/
public class UrlModel {
private final WebScriptRequest request;
public UrlModel(final WebScriptRequest request) {
Assert.notNull(request);
this.request = request;
}
public String getServer() {
return request.getServerPath();
}
public String getContext() {
return request.getContextPath();
}
public String getServiceContext() {
return request.getServiceContextPath();
}
public String getService() {
return request.getServicePath();
}
public String getFull() {
return request.getURL();
}
public String getArgs() {
final String args = request.getQueryString();
return (args == null) ? "" : args;
}
public String getMatch() {
return request.getServiceMatch().getPath();
}
public String getExtension() {
return request.getExtensionPath();
}
public String getTemplate() {
return request.getServiceMatch().getTemplate();
}
public Map<String, String> getTemplateArgs() {
final Map<String, String> args = request.getServiceMatch().getTemplateVars();
return (args == null) ? Collections.<String, String> emptyMap() : args;
}
}
|
anthonyalvarez757/rm.soin-net
|
src/main/java/com/soin/sgrm/model/Crontab.java
|
<gh_stars>0
package com.soin.sgrm.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.Valid;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.soin.sgrm.exception.Sentry;
import com.soin.sgrm.utils.Constant;
@SuppressWarnings("serial")
@Entity
@Table(name = "RELEASES_CRONTAB")
public class Crontab implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "RELEASES_CRONTAB_SQ")
@SequenceGenerator(name = "RELEASES_CRONTAB_SQ", sequenceName = "RELEASES_CRONTAB_SQ", allocationSize = 1)
@Column(name = "ID")
private int id;
@SuppressWarnings("deprecation")
@Cascade({ CascadeType.MERGE, CascadeType.DETACH, CascadeType.EVICT })
@ManyToOne(fetch = FetchType.EAGER)
private ReleaseUser release;
@Column(name = "USUARIO")
@NotEmpty(message = Constant.EMPTY)
@NotBlank(message = Constant.EMPTY)
private String user;
@Column(name = "ACTIVA")
private Boolean isActive;
@Column(name = "COMANDO")
@NotEmpty(message = Constant.EMPTY)
@NotBlank(message = Constant.EMPTY)
private String commandCron;
@Column(name = "ENTRADA_COMANDO")
@NotEmpty(message = Constant.EMPTY)
@NotBlank(message = Constant.EMPTY)
private String commandEntry;
@Column(name = "DESCRIPCION")
@NotEmpty(message = Constant.EMPTY)
@NotBlank(message = Constant.EMPTY)
private String descriptionCron;
@Column(name = "MINUTO")
@NotEmpty(message = "Seleccione un minuto")
@NotBlank(message = "Seleccione un minuto")
private String minutes;
@Column(name = "HORA")
@NotEmpty(message = "Seleccione una hora")
@NotBlank(message = "Seleccione una hora")
private String hour;
@Column(name = "DIA_MES")
@NotEmpty(message = "Seleccione un día")
@NotBlank(message = "Seleccione un día")
private String days;
@Column(name = "MES")
@NotEmpty(message = "Seleccione un mes")
@NotBlank(message = "Seleccione un mes")
private String month;
@Column(name = "DIA_SEMANA")
@NotEmpty(message = "Seleccione un día")
@NotBlank(message = "Seleccione un día")
private String weekDays;
@SuppressWarnings("deprecation")
@Cascade({ CascadeType.MERGE, CascadeType.DETACH, CascadeType.EVICT })
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BOTON_ID", nullable = true)
private ButtonCommand button;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ReleaseUser getRelease() {
return release;
}
public void setRelease(ReleaseUser release) {
this.release = release;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Boolean getActive() {
return isActive;
}
public void setActive(Boolean isActive) {
this.isActive = isActive;
}
public String getCommandCron() {
return commandCron;
}
public void setCommandCron(String commandCron) {
this.commandCron = commandCron;
}
public String getCommandEntry() {
return commandEntry;
}
public void setCommandEntry(String commandEntry) {
this.commandEntry = commandEntry;
}
public String getDescriptionCron() {
return descriptionCron;
}
public void setDescriptionCron(String descriptionCron) {
this.descriptionCron = descriptionCron;
}
public String getMinutes() {
return minutes;
}
public void setMinutes(String minutes) {
this.minutes = minutes;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public String getDays() {
return days;
}
public void setDays(String days) {
this.days = days;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getWeekDays() {
return weekDays;
}
public void setWeekDays(String weekDays) {
this.weekDays = weekDays;
}
public ButtonCommand getButton() {
return button;
}
public void setButton(String button) {
ObjectMapper mapper = new ObjectMapper();
try {
ButtonCommand jsonObj = mapper.readValue(button, ButtonCommand.class);
this.button = jsonObj;
} catch (Exception e) {
this.button = null;
Sentry.capture(e, "button");
}
}
public void updateButton(ButtonCommand button) {
this.button = button;
}
}
|
mingyi456/tp
|
src/main/java/seedu/address/ui/HelpWindow.java
|
<reponame>mingyi456/tp
package seedu.address.ui;
import java.awt.Desktop;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
import seedu.address.commons.core.LogsCenter;
import seedu.address.logic.commands.ClearCommand;
import seedu.address.logic.commands.DeleteCommand;
import seedu.address.logic.commands.EditCommand;
import seedu.address.logic.commands.ExitCommand;
import seedu.address.logic.commands.FindCommand;
import seedu.address.logic.commands.HelpCommand;
import seedu.address.logic.commands.ListCommand;
import seedu.address.logic.commands.RedoCommand;
import seedu.address.logic.commands.UndoCommand;
import seedu.address.logic.commands.task.AddTaskCommand;
import seedu.address.logic.commands.task.DeleteTaskCommand;
import seedu.address.logic.commands.task.DoneTaskCommand;
import seedu.address.logic.commands.task.EditTaskCommand;
import seedu.address.logic.commands.task.FindTaskCommand;
import seedu.address.logic.commands.task.ListTaskCommand;
import seedu.address.logic.commands.task.PurgeTaskCommand;
import seedu.address.logic.parser.CommandSpecification;
/**
* Controller for a help page
*/
public class HelpWindow extends UiPart<Stage> {
public static final String USERGUIDE_URL = "https://ay2122s1-cs2103-f09-2.github.io/tp/UserGuide.html";
private static final Logger logger = LogsCenter.getLogger(HelpWindow.class);
private static final String FXML = "HelpWindow.fxml";
private static final List<CommandSpecification> ALL_COMMAND_SPECS = List.of(
AddTaskCommand.COMMAND_SPECS,
DeleteTaskCommand.COMMAND_SPECS,
DoneTaskCommand.COMMAND_SPECS,
EditTaskCommand.COMMAND_SPECS,
FindTaskCommand.COMMAND_SPECS,
ListTaskCommand.COMMAND_SPECS,
PurgeTaskCommand.COMMAND_SPECS,
AddTaskCommand.COMMAND_SPECS,
ClearCommand.COMMAND_SPECS,
DeleteCommand.COMMAND_SPECS,
EditCommand.COMMAND_SPECS,
ExitCommand.COMMAND_SPECS,
FindCommand.COMMAND_SPECS,
HelpCommand.COMMAND_SPECS,
ListCommand.COMMAND_SPECS,
RedoCommand.COMMAND_SPECS,
UndoCommand.COMMAND_SPECS
);
@FXML
private ListView<CommandSpecification> commandList;
/**
* Creates a new HelpWindow.
*
* @param root Stage to use as the root of the HelpWindow.
*/
public HelpWindow(Stage root) {
super(FXML, root);
root.setMinWidth(600);
root.setMinHeight(400);
commandList.maxWidthProperty().bind(root.widthProperty());
commandList.setItems(FXCollections.observableList(ALL_COMMAND_SPECS));
commandList.setCellFactory((ListView<CommandSpecification> param) -> new ListCell<>() {
@Override
protected void updateItem(CommandSpecification specs, boolean empty) {
super.updateItem(specs, empty);
if (!empty) {
Label title = new Label(specs.getWord());
Label description = new Label(specs.getDescription());
Label usage = new Label(specs.getCommandUsage());
Label format = new Label("Format");
title.getStyleClass().add("label-header-small");
usage.getStyleClass().add("mono");
format.getStyleClass().add("italics");
format.setPadding(new Insets(8, 0, 0, 0));
// Enable wrap text
description.setWrapText(true);
usage.setWrapText(true);
VBox vBox = new VBox(
title,
new TextFlow(description),
format,
new TextFlow(usage)
);
vBox.setPadding(new Insets(16));
// Restrict width of text to allow wrap text
description.maxWidthProperty().bind(commandList.maxWidthProperty().subtract(32));
vBox.maxWidthProperty().bind(commandList.maxWidthProperty().subtract(32));
usage.maxWidthProperty().bind(commandList.maxWidthProperty().subtract(32));
if (!specs.getExampleCommands().isEmpty()) {
Label example = new Label("Example");
example.getStyleClass().add("italics");
VBox exampleUsage = new VBox(example);
exampleUsage.setPadding(new Insets(8, 0, 0, 0));
specs.getExampleCommands().stream().map(ec -> {
Label label = new Label(ec);
label.getStyleClass().add("mono");
label.setWrapText(true);
return label;
}).map(TextFlow::new)
.forEach(exampleUsage.getChildren()::add);
vBox.getChildren().add(exampleUsage);
}
setGraphic(vBox);
}
}
});
}
/**
* Creates a new HelpWindow.
*/
public HelpWindow() {
this(new Stage());
}
/**
* Shows the help window.
* @throws IllegalStateException
* <ul>
* <li>
* if this method is called on a thread other than the JavaFX Application Thread.
* </li>
* <li>
* if this method is called during animation or layout processing.
* </li>
* <li>
* if this method is called on the primary stage.
* </li>
* <li>
* if {@code dialogStage} is already showing.
* </li>
* </ul>
*/
public void show() {
logger.fine("Showing help page about the application.");
getRoot().show();
getRoot().centerOnScreen();
}
/**
* Returns true if the help window is currently being shown.
*/
public boolean isShowing() {
return getRoot().isShowing();
}
/**
* Hides the help window.
*/
public void hide() {
getRoot().hide();
}
/**
* Focuses on the help window.
*/
public void focus() {
getRoot().requestFocus();
}
/**
* Copies the URL to the user guide to the clipboard.
*/
@FXML
private void copyUrl() {
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent url = new ClipboardContent();
url.putString(USERGUIDE_URL);
clipboard.setContent(url);
}
/**
* Open the user's Desktop Browser
*/
@FXML
private void openUrl() {
try {
Desktop.getDesktop().browse(new URL(USERGUIDE_URL).toURI());
} catch (MalformedURLException | URISyntaxException e) {
logger.info("Invalid URL");
} catch (IOException ioe) {
logger.info(ioe.getMessage());
}
}
}
|
vladn-ma/vladn-ovs-doc
|
doxygen/ovs_all/html/structovsdb__monitor__row.js
|
var structovsdb__monitor__row =
[
[ "hmap_node", "structovsdb__monitor__row.html#ae6e7239f74c18f4c5a47345850a59ff5", null ],
[ "new", "structovsdb__monitor__row.html#a0c5886d2e0c293530ffafb0f79bb69b1", null ],
[ "old", "structovsdb__monitor__row.html#ab9c47b27cef4dce17d03d5f5ee59dad5", null ],
[ "uuid", "structovsdb__monitor__row.html#af1a5e738bceadf731a2e9981c11bff69", null ]
];
|
hsamgle/wheel
|
framework/basic/src/main/java/com/hsamgle/basic/entity/TokenInfo.java
|
<filename>framework/basic/src/main/java/com/hsamgle/basic/entity/TokenInfo.java
package com.hsamgle.basic.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Set;
/**
*
* @feture : TODO 令牌信息
* @file_name: TokenInfo.java
* @packge: com.hsamgle.basic.entity
* @author: 黄鹤老板
* @create_time: 2018/3/27 9:15
* @company: 江南皮革厂
*/
@Data
@EqualsAndHashCode(callSuper = false,of = "token")
public class TokenInfo extends SEntity{
/** token类型 */
protected String tag;
/** token 标识 */
private String token;
/** 用户id */
private Object userId;
/** token 的创建时间 */
private long createTime;
/** 是否是超级管理员 */
private boolean superAdmin;
/** 如果是小程序端用户,则可以的免去权限校验通过某些特定接口 */
private boolean wechatUser;
/** 权限许可列表 */
private Set<License> licenses;
}
|
navikt/testnorge
|
libs/reactive-session-security/src/main/java/no/nav/testnav/libs/reactivesessionsecurity/manager/WebClientReactiveTokenResponseClient.java
|
package no.nav.testnav.libs.reactivesessionsecurity.manager;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.endpoint.NimbusJwtClientAuthenticationParametersConverter;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.web.reactive.function.OAuth2BodyExtractors;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.util.Collections;
import java.util.Set;
class WebClientReactiveTokenResponseClient implements ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {
private WebClient webClient = WebClient.builder().build();
private NimbusJwtClientAuthenticationParametersConverter<OAuth2AuthorizationCodeGrantRequest> converter;
private ClientRegistration clientRegistration(OAuth2AuthorizationCodeGrantRequest grantRequest) {
return grantRequest.getClientRegistration();
}
private Set<String> defaultScopes(OAuth2AuthorizationCodeGrantRequest grantRequest) {
return grantRequest.getAuthorizationExchange().getAuthorizationRequest().getScopes();
}
private BodyInserters.FormInserter<String> populateTokenRequestBody(
OAuth2AuthorizationCodeGrantRequest grantRequest,
BodyInserters.FormInserter<String> body
) {
ClientRegistration clientRegistration = clientRegistration(grantRequest);
if (!ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(clientRegistration.getClientAuthenticationMethod())
&& !ClientAuthenticationMethod.BASIC.equals(clientRegistration.getClientAuthenticationMethod())) {
body.with(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
}
if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod())
|| ClientAuthenticationMethod.POST.equals(clientRegistration.getClientAuthenticationMethod())) {
body.with(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
}
OAuth2AuthorizationExchange authorizationExchange = grantRequest.getAuthorizationExchange();
OAuth2AuthorizationResponse authorizationResponse = authorizationExchange.getAuthorizationResponse();
body.with(OAuth2ParameterNames.CODE, authorizationResponse.getCode());
String redirectUri = authorizationExchange.getAuthorizationRequest().getRedirectUri();
if (redirectUri != null) {
body.with(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
}
String codeVerifier = authorizationExchange.getAuthorizationRequest()
.getAttribute(PkceParameterNames.CODE_VERIFIER);
if (codeVerifier != null) {
body.with(PkceParameterNames.CODE_VERIFIER, codeVerifier);
}
if (grantRequest.getClientRegistration().getClientAuthenticationMethod().equals(ClientAuthenticationMethod.PRIVATE_KEY_JWT)) {
Assert.notNull(converter, "converter cannot be null");
var map = converter.convert(grantRequest);
map.forEach((key, value) -> value.stream().findFirst().ifPresent(first -> body.with(key, first)));
}
return body;
}
@Override
public Mono<OAuth2AccessTokenResponse> getTokenResponse(OAuth2AuthorizationCodeGrantRequest grantRequest) {
Assert.notNull(grantRequest, "grantRequest cannot be null");
return Mono.defer(() -> this.webClient.post()
.uri(clientRegistration(grantRequest).getProviderDetails().getTokenUri())
.headers((headers) -> populateTokenRequestHeaders(grantRequest, headers))
.body(createTokenRequestBody(grantRequest))
.exchange()
.flatMap((response) -> readTokenResponse(grantRequest, response))
);
}
private void populateTokenRequestHeaders(OAuth2AuthorizationCodeGrantRequest grantRequest, HttpHeaders headers) {
ClientRegistration clientRegistration = clientRegistration(grantRequest);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(clientRegistration.getClientAuthenticationMethod())
|| ClientAuthenticationMethod.BASIC.equals(clientRegistration.getClientAuthenticationMethod())) {
headers.setBasicAuth(clientRegistration.getClientId(), clientRegistration.getClientSecret());
}
}
private BodyInserters.FormInserter<String> createTokenRequestBody(OAuth2AuthorizationCodeGrantRequest grantRequest) {
BodyInserters.FormInserter<String> body = BodyInserters.fromFormData(OAuth2ParameterNames.GRANT_TYPE,
grantRequest.getGrantType().getValue());
return populateTokenRequestBody(grantRequest, body);
}
private Mono<OAuth2AccessTokenResponse> readTokenResponse(OAuth2AuthorizationCodeGrantRequest grantRequest, ClientResponse response) {
return response.body(OAuth2BodyExtractors.oauth2AccessTokenResponse())
.map((tokenResponse) -> populateTokenResponse(grantRequest, tokenResponse));
}
private OAuth2AccessTokenResponse populateTokenResponse(OAuth2AuthorizationCodeGrantRequest grantRequest, OAuth2AccessTokenResponse tokenResponse) {
if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
Set<String> defaultScopes = defaultScopes(grantRequest);
tokenResponse = OAuth2AccessTokenResponse
.withResponse(tokenResponse)
.scopes(defaultScopes)
.build();
}
return tokenResponse;
}
public void setWebClient(WebClient webClient) {
this.webClient = webClient;
}
public void setConverter(NimbusJwtClientAuthenticationParametersConverter<OAuth2AuthorizationCodeGrantRequest> converter) {
this.converter = converter;
}
}
|
farbrorbarbro/ExeMutator
|
source/mutator/InstructionNodes/PushInstruction.h
|
#pragma once
#include "Instruction.h"
#include "RegisterDefinitions.h"
class PushInstruction : public Instruction
{
public:
PushInstruction(RegisterDefinitions inRegister);
};
|
wtmitchell/project_euler
|
lib/project_euler/Problem.cpp
|
//===-- project_euler/Problem.cpp -------------------------------*- C++ -*-===//
//
// Challenge Problem solutions by <NAME>
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//===----------------------------------------------------------------------===//
#include "project_euler/Problem.h"
project_euler::Problem::~Problem() {}
|
techonair/Codeforces
|
Easy Number Challenge 236B.py
|
<gh_stars>0
a,b,c = map(int,input().split())
lis=[0] * 1000001
for i in range(1, 1000001):
j = i
while j <= 1000000:
lis[j] += 1
j += i
ans = 0
for i in range(1, a+1):
for j in range(1, b+1):
for k in range(1, c+1):
ans += (lis[i*j*k]%(1073741824*2**30))
print(ans)
# submit with pypy that works faster
"""
from cmath import sqrt
a, b, c = map(int, input().split())
ans = 0
def divisor(i, j, k):
pro = (((i%(1073741824*2**30)*j%(1073741824*2**30))%(1073741824*2**30))*k%(1073741824*2**30))%(1073741824*2**30)
count = 0
for x in range(1, pro+1):
print(x)
if pro % x == 0:
count += 1
return count
for i in range(1, a+1):
for j in range(1, b+1):
for k in range(1, c+1):
ans += divisor(i, j, k)%(1073741824*2**30)
print(ans)
"""
|
mya12321/taro-demo
|
src/page/API/pages/file/file.js
|
import { Block, View, Image, Button } from '@tarojs/components'
import Taro from '@tarojs/taro'
import withWeapp from '@tarojs/with-weapp'
import FootTmpl from '../../../../imports/FootTmpl.js'
import HeadTmpl from '../../../../imports/HeadTmpl.js'
import './file.scss'
@withWeapp({
onShareAppMessage() {
return {
title: '文件',
path: 'page/API/pages/file/file'
}
},
onLoad() {
this.setData({
savedFilePath: Taro.getStorageSync('savedFilePath')
})
},
data: {
tempFilePath: '',
savedFilePath: '',
dialog: {
hidden: true
}
},
chooseImage() {
const that = this
Taro.chooseImage({
count: 1,
success(res) {
that.setData({
tempFilePath: res.tempFilePaths[0]
})
}
})
},
saveFile() {
if (this.data.tempFilePath.length > 0) {
const that = this
Taro.saveFile({
tempFilePath: this.data.tempFilePath,
success(res) {
that.setData({
savedFilePath: res.savedFilePath
})
Taro.setStorageSync('savedFilePath', res.savedFilePath)
that.setData({
dialog: {
title: '保存成功',
content: '下次进入应用时,此文件仍可用',
hidden: false
}
})
},
fail() {
that.setData({
dialog: {
title: '保存失败',
content: '应该是有 bug 吧',
hidden: false
}
})
}
})
}
},
clear() {
Taro.setStorageSync('savedFilePath', '')
this.setData({
tempFilePath: '',
savedFilePath: ''
})
},
confirm() {
this.setData({
'dialog.hidden': true
})
}
})
class _C extends Taro.Component {
config = {
navigationBarTitleText: '文件'
}
render() {
const { tempFilePath, savedFilePath, dialog } = this.data
return (
<View className="container">
<HeadTmpl data={{ title: 'saveFile' }}></HeadTmpl>
<View className="page-body">
<View className="page-section">
<View className="page-body-info">
{tempFilePath != '' && (
<Block>
<Image
src={tempFilePath}
className="image"
mode="aspectFit"
></Image>
</Block>
)}
{tempFilePath === '' && savedFilePath != '' && (
<Block>
<Image
src={savedFilePath}
className="image"
mode="aspectFit"
></Image>
</Block>
)}
{tempFilePath === '' && savedFilePath === '' && (
<Block>
<View
className="image-plus image-plus-nb"
onClick={this.chooseImage}
>
<View className="image-plus-horizontal"></View>
<View className="image-plus-vertical"></View>
</View>
<View className="image-plus-text">请选择文件</View>
</Block>
)}
</View>
<View className="btn-area">
<Button type="primary" onClick={this.saveFile}>
保存文件
</Button>
<Button onClick={this.clear}>删除文件</Button>
</View>
</View>
</View>
<Modal
title={dialog.title}
hidden={dialog.hidden}
noCancel
onConfirm={this.confirm}
>
{dialog.content}
</Modal>
<FootTmpl></FootTmpl>
</View>
)
}
}
export default _C
|
worldline/kafka-manager
|
backend/src/main/java/com/worldline/kafka/kafkamanager/controller/KafkaConnectController.java
|
package com.worldline.kafka.kafkamanager.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.worldline.kafka.kafkamanager.dto.event.EventArgs;
import com.worldline.kafka.kafkamanager.dto.event.EventType;
import com.worldline.kafka.kafkamanager.dto.kafkaconnect.KafkaConnectConnectorCreationDto;
import com.worldline.kafka.kafkamanager.dto.kafkaconnect.KafkaConnectConnectorDto;
import com.worldline.kafka.kafkamanager.dto.kafkaconnect.KafkaConnectConnectorUpdateDto;
import com.worldline.kafka.kafkamanager.dto.kafkaconnect.KafkaConnectPluginDto;
import com.worldline.kafka.kafkamanager.dto.kafkaconnect.KafkaConnectPluginValidationRequestDto;
import com.worldline.kafka.kafkamanager.dto.kafkaconnect.KafkaConnectPluginValidationResponseDto;
import com.worldline.kafka.kafkamanager.dto.kafkaconnect.KafkaConnectVersionDto;
import com.worldline.kafka.kafkamanager.service.KafkaConnectService;
import com.worldline.kafka.kafkamanager.service.events.ActivityEvent;
import com.worldline.kafka.kafkamanager.service.events.ActivityEventArg;
/**
* Kafka connect controller.
*/
@RestController
@RequestMapping("/clusters/{clusterId}/kafka-connect")
public class KafkaConnectController {
private KafkaConnectService kafkaConnectService;
/**
* Contructor.
*
* @param kafkaConnectService the kafka connect service
*/
@Autowired
public KafkaConnectController(KafkaConnectService kafkaConnectService) {
this.kafkaConnectService = kafkaConnectService;
}
@GetMapping
public ResponseEntity<KafkaConnectVersionDto> getVersion(@PathVariable("clusterId") String clusterId) {
return ResponseEntity.ok(kafkaConnectService.getVersion(clusterId));
}
@GetMapping("/connectors")
public ResponseEntity<Page<KafkaConnectConnectorDto>> getConnectors(@PathVariable("clusterId") String clusterId,
Pageable pageable) {
return ResponseEntity.ok(kafkaConnectService.getConnectors(clusterId, pageable));
}
@GetMapping("/connectors/{connectorId}")
public ResponseEntity<KafkaConnectConnectorDto> getConnector(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId) {
return ResponseEntity.ok(kafkaConnectService.getConnector(clusterId, connectorId));
}
@Secured("ADMIN")
@PutMapping("/connectors/{connectorId}/config")
@ResponseStatus(HttpStatus.OK)
@ActivityEvent(value = EventType.CONNECTOR_UPDATE, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#connectorId") })
public void updateConnector(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId,
@RequestBody @Valid KafkaConnectConnectorUpdateDto request) {
kafkaConnectService.updateConnector(clusterId, connectorId, request);
}
@Secured("ADMIN")
@PostMapping("/connectors")
@ActivityEvent(value = EventType.CONNECTOR_CREATE, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#request.name") })
public ResponseEntity<KafkaConnectConnectorDto> createConnector(@PathVariable("clusterId") String clusterId,
@RequestBody @Valid KafkaConnectConnectorCreationDto request) {
return ResponseEntity.status(HttpStatus.CREATED).body(kafkaConnectService.createConnector(clusterId, request));
}
@PostMapping("/connectors/{connectorId}/restart")
@ResponseStatus(HttpStatus.OK)
@ActivityEvent(value = EventType.CONNECTOR_RESTART, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#connectorId") })
public void restartConnector(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId) {
kafkaConnectService.restartConnector(clusterId, connectorId);
}
@PutMapping("/connectors/{connectorId}/pause")
@ResponseStatus(HttpStatus.OK)
@ActivityEvent(value = EventType.CONNECTOR_PAUSE, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#connectorId") })
public void pauseConnector(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId) {
kafkaConnectService.pauseConnector(clusterId, connectorId);
}
@PutMapping("/connectors/{connectorId}/resume")
@ResponseStatus(HttpStatus.OK)
@ActivityEvent(value = EventType.CONNECTOR_RESUME, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#connectorId") })
public void resumeConnector(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId) {
kafkaConnectService.resumeConnector(clusterId, connectorId);
}
@Secured("ADMIN")
@DeleteMapping("/connectors/{connectorId}")
@ResponseStatus(HttpStatus.OK)
@ActivityEvent(value = EventType.CONNECTOR_DELETE, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#connectorId") })
public void deleteConnector(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId) {
kafkaConnectService.deleteConnector(clusterId, connectorId);
}
@GetMapping("/connector-plugins")
public ResponseEntity<Page<KafkaConnectPluginDto>> getPlugins(@PathVariable("clusterId") String clusterId,
Pageable pageable) {
return ResponseEntity.ok(kafkaConnectService.getPlugins(clusterId, pageable));
}
@PutMapping("/connector-plugins/{pluginName}/config/validate")
public ResponseEntity<KafkaConnectPluginValidationResponseDto> validatePlugin(
@PathVariable("clusterId") String clusterId, @PathVariable("pluginName") String pluginName,
@RequestBody @Valid KafkaConnectPluginValidationRequestDto request) {
return ResponseEntity.ok(kafkaConnectService.validatePlugin(clusterId, pluginName, request));
}
@Secured("ADMIN")
@PutMapping("/connectors/{connectorId}/topics/reset")
@ResponseStatus(HttpStatus.OK)
@ActivityEvent(value = EventType.CONNECTOR_RESET_TOPICS, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#connectorId") })
public void resetTopics(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId) {
kafkaConnectService.resetTopics(clusterId, connectorId);
}
@Secured("ADMIN")
@PostMapping("/connectors/{connectorId}/tasks/{taskId}/restart")
@ResponseStatus(HttpStatus.OK)
@ActivityEvent(value = EventType.CONNECTOR_TASK_RESTART, args = {
@ActivityEventArg(key = EventArgs.CONNECTOR, value = "#connectorId"),
@ActivityEventArg(key = EventArgs.CONNECTOR_TASK, value = "#taskId") })
public void restartTask(@PathVariable("clusterId") String clusterId,
@PathVariable("connectorId") String connectorId, @PathVariable("taskId") String taskId) {
kafkaConnectService.restartTask(clusterId, connectorId, taskId);
}
}
|
vault513/codewars-javascript
|
8 kyu/Remove First and Last Character.js
|
function removeChar(str){
return str.slice(1, str.length - 1);
}
|
deninising/thread_learn
|
src/main/java/com/dennis/conccurency/atomic/chapter01/GetLockException.java
|
<gh_stars>0
package com.dennis.conccurency.atomic.chapter01;
/**
* 描述:获取锁异常
*
* @author Dennis
* @version 1.0
* @date 2020/3/31 16:47
*/
public class GetLockException extends Exception {
public GetLockException() {
super();
}
public GetLockException(String message) {
super(message);
}
public GetLockException(String message, Throwable cause) {
super(message, cause);
}
public GetLockException(Throwable cause) {
super(cause);
}
}
|
cypherdotXd/o3de
|
Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Pass/PassAsset.h
|
<gh_stars>10-100
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <Atom/RPI.Reflect/Asset/AssetHandler.h>
#include <Atom/RPI.Reflect/AssetCreator.h>
#include <Atom/RPI.Reflect/Pass/PassTemplate.h>
#include <AzCore/Asset/AssetCommon.h>
namespace UnitTest
{
class PassBuilderTests;
}
namespace AZ
{
class ReflectContext;
namespace RPI
{
//! An asset that describes the root of a pass by having a PassTemplate.
//! By adding PassRequests to the template you can describe an entire tree of passes.
class PassAsset final
: public Data::AssetData
{
friend class PassSystem;
friend class UnitTest::PassBuilderTests;
public:
AZ_RTTI(PassAsset, "{FBAF94C2-6617-491E-8269-55DBC9845539}", Data::AssetData);
AZ_CLASS_ALLOCATOR(PassAsset, SystemAllocator, 0);
static void Reflect(ReflectContext* context);
static const char* DisplayName;
static const char* Group;
static const char* Extension;
//! Retrieves the underlying PassTemplate
const AZStd::unique_ptr<PassTemplate>& GetPassTemplate() const;
private:
// Sets the pass template on this pass asset. Use for testing only.
void SetPassTemplateForTestingOnly(const PassTemplate& passTemplate);
AZStd::unique_ptr<PassTemplate> m_passTemplate = nullptr;
};
using PassAssetHandler = AssetHandler<PassAsset>;
} // namespace RPI
} // namespace AZ
|
moibenko/enstore
|
src/log_server.py
|
#!/usr/bin/env python
"""
#########################################################################
# Log Server. #
# Receives log messages form the client process and logs them into #
# the log file. #
# Log file is being open for append in the directory specified in the #
# corresponding entry in the configuration dictionary (sever does not #
# take any arguments so far). #
# The log file has a name LOG-YYYY-MM-DD #
# where: #
# YYYY - is four digit year number #
# MM - month of the year (1 - 12) #
# DD - day of the month #
# at midnight currently open log file gets closed and another one is #
# open. #
# Format of the message in the dictionary is as follows: #
# HH:MM:SS HOST PID UID SL CLNTABBREV MESSAGE #
# where: #
# HH:MM:SS - Log Server time when the message has been received #
# HOST - name of the host where client sending the message runs #
# PID - Process ID of the client which sent a message #
# UID - User ID of the client #
# SL - severity level abbreviation (see client code) #
# MESSAGE - arbitrary message received from the client #
#########################################################################
"""
# system imports
import sys
import os
import time
import string
import glob
import pwd
import threading
import socket
import fcntl
import select
import cPickle
#enstore imports
import dispatching_worker
import generic_server
#import event_relay_client
import monitored_server
import enstore_constants
import event_relay_messages
import e_errors
import hostaddr
import Trace
import log_client
import option
import callback
MY_NAME = enstore_constants.LOG_SERVER #"log_server"
FILE_PREFIX = "LOG-"
NO_MAX_LOG_FILE_SIZE = -1L
MAX_TCP_MESSAGE_SIZE = enstore_constants.MB*10
def format_date(tm=None):
if not tm:
tm = time.localtime(time.time()) # get the local time
return '%04d-%02d-%02d' % (tm[0], tm[1], tm[2])
class Logger( dispatching_worker.DispatchingWorker
, generic_server.GenericServer):
"""
Instance of this class is a log server. Multiple instances
of this class can run using unique port numbers. But it actually is not
recommended. It is assumed that the only one Log Server will serve the
whole system.
"""
def __init__(self, csc, test=0):
flags = enstore_constants.NO_LOG
generic_server.GenericServer.__init__(self, csc, MY_NAME, flags=flags,
function = self.handle_er_msg)
self.repeat_count = 0
self.index = 1
self.last_message = ''
# pretend that we are the test system
# remember, in a system, there is only one bfs
# get our port and host from the name server
# exit if the host is not this machine
keys = self.csc.get(MY_NAME)
Trace.init(self.log_name)
Trace.set_log_func(self.log_func) #Log function for itself.
self.max_queue_size = keys.get("max_queue_size") # maximum size of incoming message queue
self.alive_interval = monitored_server.get_alive_interval(self.csc,
MY_NAME,
keys)
self.use_raw_input = keys.get('use_raw_input') # use raw input to buffer incoming messages
dispatching_worker.DispatchingWorker.__init__(self, (keys['hostip'],
keys['port']),
use_raw=self.use_raw_input)
if keys["log_file_path"][0] == '$':
tmp = keys["log_file_path"][1:]
try:
tmp = os.environ[tmp];
except:
Trace.log(12, "log_file_path '%s' configuration ERROR"
%(keys["log_file_path"]))
sys.exit(1)
self.logfile_dir_path = tmp
else:
self.logfile_dir_path = keys["log_file_path"]
if not os.path.exists(self.logfile_dir_path):
try:
os.makedirs(self.logfile_dir_path)
except:
exc, msg, tb = sys.exc_info()
print "Can not create %s. %s %s"%(self.logfile_dir_path, exc, msg)
sys.exit(1)
self.test = test
# get the value for max size of a log file
self.max_log_file_size = keys.get(enstore_constants.MAX_LOG_FILE_SIZE,
NO_MAX_LOG_FILE_SIZE)
# see if no debug log is desired
self.no_debug = keys.has_key(enstore_constants.NO_DEBUG_LOG)
# get the dictionary of ancillary log files
self.msg_type_logs = keys.get('msg_type_logs', {})
self.msg_type_keys = self.msg_type_logs.keys()
self.extra_logfiles = {}
self.lock = threading.Lock()
# setup the communications with the event relay task
self.erc.start([event_relay_messages.NEWCONFIGFILE])
# start our heartbeat to the event relay process
self.erc.start_heartbeat(enstore_constants.LOG_SERVER,
self.alive_interval)
#This is the function for Trace.log to use from withing the log server.
def log_func( self, time, pid, name, args ):
#Even though this implimentation of log_func() does not use the time
# parameter, others will.
__pychecker__ = "unusednames=time"
#Note: The code to create the variable ticket was taken from
# the log client.
severity = args[0]
msg = args[1]
if severity > e_errors.MISC:
msg = '%s %s' % (severity, msg)
severity = e_errors.MISC
msg = '%.6d %.8s %s %s %s' % (pid, pwd.getpwuid(os.getuid())[0],
e_errors.sevdict[severity], name, msg)
ticket = {'work':'log_message', 'message':msg}
#Use the same function to write to the log file as it uses for
# everythin else.
self.log_message(ticket)
def open_extra_logs(self, mode='a+'):
for msg_type in self.msg_type_keys:
filename = self.msg_type_logs[msg_type]
file_path = "%s/%s%s"%(self.logfile_dir_path, filename,
format_date())
self.extra_logfiles[msg_type] = open(file_path, mode)
def close_extra_logs(self):
for msg_type in self.msg_type_keys:
self.extra_logfiles[msg_type].close()
else:
self.extra_logfiles = {}
def open_logfile(self, logfile_name) :
dirname, filename = os.path.split(logfile_name)
debug_file = "DEBUG%s" % (filename,)
debug_file_name = os.path.join(dirname,debug_file)
# try to open log file for append
try:
if not os.path.exists(dirname):
os.mkdir(dirname)
with self.lock:
self.logfile = open(logfile_name, 'a+')
if not self.no_debug:
self.debug_logfile = open(debug_file_name, 'a+')
self.open_extra_logs('a+')
except Exception, detail:
message="cannot open log %s: %s"%(logfile_name, detail)
try:
print message
sys.stderr.write("%s\n" % message)
sys.stderr.flush()
sys.stdout.flush()
except IOError:
pass
os._exit(1)
# return the current log file name
def get_logfile_name(self, ticket):
ticket["status"] = (e_errors.OK, None)
ticket["logfile_name"] = self.logfile_name
self.send_reply(ticket)
# return the last log file name
def get_last_logfile_name(self, ticket):
ticket["status"] = (e_errors.OK, None)
ticket["last_logfile_name"] = self.last_logfile_name
self.send_reply(ticket)
# return the requested list of logfile names
def get_logfiles(self, ticket):
ticket["status"] = (e_errors.OK, None)
period = ticket.get("period", "today")
vperiod_keys = log_client.VALID_PERIODS.keys()
if period in vperiod_keys:
num_files_to_get = log_client.VALID_PERIODS[period]
files = os.listdir(self.logfile_dir_path)
# we want to take the latest files so sort them in reverse order
files.sort()
files.reverse()
num_files = 0
lfiles = []
for fname in files:
if fname[0:4] == FILE_PREFIX:
lfiles.append("%s/%s"%(self.logfile_dir_path,fname))
num_files = num_files +1
if num_files >= num_files_to_get and not period == "all":
break
else:
# it was not a shortcut keyword so we assume it is a string of the
# form LOG*, use globbing to get the list
files = "%s/%s"%(self.logfile_dir_path, period)
lfiles = glob.glob(files)
ticket["logfiles"] = lfiles
self.send_reply(ticket)
def is_encp_xfer_msg(self, msg):
if (string.find(msg, Trace.MSG_ENCP_XFER) == -1) and \
(string.find(msg, " E ENCP") == -1):
# sub-string not found
rtn = 0
else:
rtn = 1
return rtn
def write_to_extra_logfile(self, message):
for msg_type in self.msg_type_keys:
if not string.find(message, msg_type) == -1:
# this message has a message type of msg_type
self.extra_logfiles[msg_type].write(message)
return
# log the message recieved from the log client
def log_message(self, ticket) :
if not ticket.has_key('message'):
return
if 'sender' in ticket: # ticket came over tcp
host = ticket['sender']
else:
host = hostaddr.address_to_name(self.reply_address[0])
## XXX take care of case where we can't figure out the host name
# determine what type of message is it
message_type = string.split(ticket['message'])[2]
message = "%-8s %s"%(host,ticket['message'])
tm = time.localtime(time.time()) # get the local time
if message == self.last_message:
self.repeat_count=self.repeat_count+1
return
elif self.repeat_count:
if message_type != e_errors.sevdict[e_errors.MISC]:
self.logfile.write("%.2d:%.2d:%.2d last message repeated %d times\n"%
(tm[3],tm[4],tm[5], self.repeat_count))
if not self.no_debug:
self.debug_logfile.write("%.2d:%.2d:%.2d last message repeated %d times\n"%
(tm[3],tm[4],tm[5], self.repeat_count))
self.repeat_count=0
self.last_message=message
# alert the event relay if we got an encp transfer message.
if self.is_encp_xfer_msg(message):
Trace.notify(event_relay_messages.ENCPXFER)
# format log message
message = "%.2d:%.2d:%.2d %s\n" % (tm[3], tm[4], tm[5], message)
with self.lock: # to synchronize logging threads
try:
if message_type != e_errors.sevdict[e_errors.MISC]:
res = self.logfile.write(message) # write log message to the file
self.logfile.flush()
if not self.no_debug:
res = self.debug_logfile.write(message) # write log message to the file
if message_type != e_errors.sevdict[e_errors.MISC]:
self.write_to_extra_logfile(message)
except:
exc, value, tb = sys.exc_info()
for l in traceback.format_exception( exc, value, tb ):
print l
def check_for_extended_files(self, filename):
if not self.max_log_file_size == NO_MAX_LOG_FILE_SIZE:
file_l = os.listdir(self.logfile_dir_path)
# pull out all the files that match the current name at a min
size = len(filename)
matching_l = []
for fname in file_l:
if fname[:size] == filename:
matching_l.append(fname)
else:
if matching_l:
matching_l.sort()
# set next file to be 1 greater than latest one
# (size+1 so can skip ".")
if matching_l[-1] != filename:
self.index = int(matching_l[-1][size+1:]) + 1
return matching_l[-1]
return filename
def serve_forever(self): # overrides UDPServer method
self.repeat_count=0
self.last_message=''
tm = time.localtime(time.time()) # get the local time
day = current_day = tm[2];
if self.test :
min1 = current_min = tm[4]
# form the log file name
fn = '%s%s' % (FILE_PREFIX, format_date(tm))
if self.test:
ft = '-%02d-%02d' % (tm[3], tm[4])
fn = fn + ft
# check for any of the extra log files (.1, .2 ...) open the latest
# one of these if they exist.
fn2 = self.check_for_extended_files(fn)
self.logfile_name = self.logfile_dir_path + "/" + fn2
self.logfile_name_orig = self.logfile_dir_path + "/" + fn
self.last_logfile_name = ""
# make sure file is not greater than max
try:
size = os.stat(self.logfile_name)[6]
except OSError:
# don't worry if file did not exist
size = 0
if not self.max_log_file_size == NO_MAX_LOG_FILE_SIZE and \
size >= self.max_log_file_size:
self.logfile_name = "%s.%s"%(self.logfile_name_orig, self.index)
self.index = self.index + 1
# open log file
self.open_logfile(self.logfile_name)
if self.use_raw_input:
# prepare raw input
self.set_out_file()
self.raw_requests.set_caller_name(self.name)
self.raw_requests.set_use_queue()
if self.max_queue_size:
# Reset incoming message queue.
self.raw_requests.set_max_queue_size(self.max_queue_size)
# start receiver thread or process
self.raw_requests.receiver()
while 1:
self.do_one_request()
# get local time
tm = time.localtime(time.time())
day = tm[2]
if self.test :
min1 = tm[4]
# if test flag is not set reopen log file at midnight
if not self.test :
# check if day has been changed
if day != current_day :
# day changed: close the current log file
self.logfile.close()
if not self.no_debug:
self.debug_logfile.close()
self.close_extra_logs()
self.last_logfile_name = self.logfile_name
current_day = day;
self.index = 1
# and open the new one
fn = '%s%04d-%02d-%02d' % (FILE_PREFIX, tm[0], tm[1], tm[2])
self.logfile_name = self.logfile_dir_path + "/" + fn
self.logfile_name_orig = self.logfile_name
self.open_logfile(self.logfile_name)
# check if current log file is > config specified value.
# if no value in config file, do nothing
elif self.max_log_file_size != NO_MAX_LOG_FILE_SIZE:
# get current file size
size = os.stat(self.logfile_name)[6]
if size >= self.max_log_file_size:
self.logfile.close()
if not self.no_debug:
self.debug_logfile.close()
self.close_extra_logs()
# and open the new one
self.logfile_name = "%s.%s"%(self.logfile_name_orig, self.index)
self.index = self.index + 1
self.open_logfile(self.logfile_name)
else :
# if test flag is set reopen log file every minute
if min1 != current_min :
# minute changed: close the current log file
self.logfile.close()
if not self.no_debug:
self.debug_logfile.close()
current_min = min;
# and open the new one
fn = '%s%04d-%02d-%02d' % (FILE_PREFIX, tm[0], tm[1],
tm[2])
ft = '-%02d-%02d' % (tm[3], tm[4])
fn = fn + ft
self.logfile_name = self.logfile_dir_path + "/" + fn
self.logfile_name_orig = self.logfile_name
self.open_logfile(self.logfile_name)
def serve_tcp_clients_recv(self):
while True:
if hasattr(self, 'rcv_sockets') and len(self.rcv_sockets) != 0:
r, w, ex = select.select(self.rcv_sockets, [], [], 10)
if r:
while len(r) > 0:
s = r.pop(0)
try:
fds, junk, junk = select.select([s], [], [], 0.1)
if s in fds:
data = s.recv(MAX_TCP_MESSAGE_SIZE)
if data:
ticket = cPickle.loads(data)
self.log_message(ticket)
else:
self.rcv_sockets.remove(s)
break
else:
self.rcv_sockets.remove(s)
break
except e_errors.EnstoreError, detail:
print "EXCEPT", detail
self.rcv_sockets.remove(s)
break
def serve_tcp_clients_enstore(self):
while True:
if hasattr(self, 'rcv_sockets') and len(self.rcv_sockets) != 0:
r, w, ex = select.select(self.rcv_sockets, [], [], 10)
if r:
while len(r) > 0:
s = r.pop(0)
try:
ticket = callback.read_tcp_obj_new(s, timeout=.1, exit_on_no_socket=True)
if ticket:
#print "TICKET", ticket
self.log_message(ticket)
else:
self.rcv_sockets.remove(s)
break
except e_errors.EnstoreError, detail:
print "EXCEPT", detail
self.rcv_sockets.remove(s)
break
serve_tcp_clients = serve_tcp_clients_enstore
def tcp_server(self):
print "STARTING TCP SERVER"
address_family = socket.getaddrinfo(self.server_address[0], None)[0][0]
listen_socket = socket.socket(address_family, socket.SOCK_STREAM)
listen_socket.bind(self.server_address)
self.rcv_sockets = []
listen_socket.listen(4)
while True:
s, addr = listen_socket.accept()
flags = fcntl.fcntl(s.fileno(), fcntl.F_GETFL)
fcntl.fcntl(s.fileno(), fcntl.F_SETFL, flags | os.O_NONBLOCK)
if hostaddr.allow(addr):
self.rcv_sockets.append(s)
class LoggerInterface(generic_server.GenericServerInterface):
def __init__(self):
# fill in the defaults for possible options
self.config_file = ""
self.test = 0
generic_server.GenericServerInterface.__init__(self)
def valid_dictionaries(self):
return generic_server.GenericServerInterface.valid_dictionaries(self) \
+ (self.logger_options,)
logger_options = {
option.CONFIG_FILE:{option.HELP_STRING:
"specifies the configuration file to use",
option.VALUE_TYPE:option.STRING,
option.VALUE_USAGE:option.REQUIRED,
option.USER_LEVEL:option.ADMIN
}
}
"""
# define the command line options that are valid
def options(self):
return generic_server.GenericServerInterface.options(self)+\
["config-file=", "test"]
"""
def thread_is_running(thread_name):
"""
check if named thread is running
:type thread_name: :obj:`str`
:arg thread_name: thread name
"""
threads = threading.enumerate()
for thread in threads:
if ((thread.getName() == thread_name) and thread.isAlive()):
return True
else:
return False
if __name__ == "__main__" :
Trace.init(string.upper(MY_NAME))
# get the interface
intf = LoggerInterface()
logserver = Logger((intf.config_host, intf.config_port), intf.test)
logserver.handle_generic_commands(intf)
#logserver._do_print({'levels':range(5, 400)})
while 1:
try:
tn = "log_server_udp"
if not thread_is_running(tn):
print "STARTING", tn
dispatching_worker.run_in_thread(tn, logserver.serve_forever)
tn = "log_server_tcp_connections"
if not thread_is_running(tn):
print "STARTING", tn
dispatching_worker.run_in_thread(tn, logserver.tcp_server)
tn = "log_server_tcp"
if not thread_is_running(tn):
print "STARTING", tn
dispatching_worker.run_in_thread(tn,logserver.serve_tcp_clients)
except SystemExit, exit_code:
sys.exit(exit_code)
except:
logserver.serve_forever_error(logserver.log_name)
continue
time.sleep(10)
|
tabratton/HotelBoxOffice
|
src/main/java/models/Actor.java
|
package models;
import java.time.ZonedDateTime;
public class Actor {
private String id;
private String name;
private String image;
private String bio;
private int viewed;
private ZonedDateTime lastModified;
public Actor() {
this.id = "";
this.name = "";
this.image = "";
this.bio = "";
this.viewed = 0;
this.lastModified = ZonedDateTime.now();
}
public Actor(String id, String name, String image, String bio, int viewed, ZonedDateTime lastModified) {
this.id = id;
this.name = name;
this.image = image;
this.bio = bio;
this.viewed = viewed;
this.lastModified = lastModified;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public Integer getViewed() {
return viewed;
}
public void setViewed(int viewed) {
this.viewed = viewed;
}
public ZonedDateTime getLastModified() {
return lastModified;
}
public void setLastModified(ZonedDateTime lastModified) {
this.lastModified = lastModified;
}
}
|
gilbertguoze/trick
|
trick_source/er7_utils/integration/abm4/include/abm4_first_order_ode_integrator.hh
|
<filename>trick_source/er7_utils/integration/abm4/include/abm4_first_order_ode_integrator.hh
/**
* @if Er7UtilsUseGroups
* @addtogroup Er7Utils
* @{
* @addtogroup Integration
* @{
* @endif
*/
/**
* @file
* Defines the class ABM4FirstOrderODEIntegrator, which integrates a monolithic
* state as a first order ODE.
*/
/*
Purpose: ()
*/
#ifndef ER7_UTILS_ABM4_ONE_STATE_INTEGRATOR_HH
#define ER7_UTILS_ABM4_ONE_STATE_INTEGRATOR_HH
// System includes
// Interface includes
#include "er7_utils/interface/include/er7_class.hh"
// Integration includes
#include "er7_utils/integration/core/include/priming_first_order_ode_integrator.hh"
namespace er7_utils {
class IntegratorConstructor;
/**
* Advance state using the fourth order Adams-Bashforth-Moulton method.
* This includes
* - Initial priming of the recent history of state derivatives,
* - Using the ABM-4 method once primed, and
* - Clearing the history when needed (e.g., time change or state change).
*/
class ABM4FirstOrderODEIntegrator : public PrimingFirstOrderODEIntegrator {
ER7_UTILS_MAKE_SIM_INTERFACES(ABM4FirstOrderODEIntegrator)
public:
// Constructors and destructor.
/**
* ABM4FirstOrderODEIntegrator default constructor.
*/
ABM4FirstOrderODEIntegrator (void);
/**
* ABM4FirstOrderODEIntegrator copy constructor.
* @param[in] src Item to be copied.
*/
ABM4FirstOrderODEIntegrator (
const ABM4FirstOrderODEIntegrator & src);
/**
* ABM4FirstOrderODEIntegrator non-default constructor.
* This is the constructor used by the integrator constructor.
* @param[in] primer_constructor Constructor that creates the primer
* @param[in] size State size
* @param[in,out] controls_in Integration controls
*/
ABM4FirstOrderODEIntegrator (
const IntegratorConstructor & primer_constructor,
unsigned int size,
IntegrationControls & controls_in);
/**
* ABM4FirstOrderODEIntegrator destructor.
*/
virtual ~ABM4FirstOrderODEIntegrator (void);
/**
* ABM4FirstOrderODEIntegrator assignment operator.
* @param src Item to be copied.
*/
ABM4FirstOrderODEIntegrator & operator=(
ABM4FirstOrderODEIntegrator src)
{
swap (src);
return *this;
}
/**
* Create a copy of 'this' ABM4FirstOrderODEIntegrator object.
* @return Clone of 'this'.
*/
virtual ABM4FirstOrderODEIntegrator * create_copy () const;
protected:
// Member functions.
/**
* Non-throwing swap.
* @param other Item with which contents are to be swapped.
*/
void swap (ABM4FirstOrderODEIntegrator & other);
using PrimingFirstOrderODEIntegrator::swap;
/**
* Save derivatives during priming.
* @param[in] countdown The prime_counter data member.
* @param[in] position Generalized position vector.
* @param[in] velocity Generalized velocity vector.
*/
virtual void technique_save_derivatives (
int countdown,
const double * ER7_UTILS_RESTRICT velocity,
const double * ER7_UTILS_RESTRICT position);
/**
* Propagate state via fourth order Adams Bashforth Moulton.
* @param[in] dyn_dt Integration step, in dynamic time seconds.
* @param[in] target_stage The stage of the integration process
* that the integrator should try to attain.
* @param[in] velocity Generalized velocity vector.
* @param[in,out] position Generalized position vector.
*
* @return The status (time advance, pass/fail status) of the integration.
*/
virtual IntegratorResult technique_integrate (
double dyn_dt,
unsigned int target_stage,
const double * ER7_UTILS_RESTRICT velocity,
double * ER7_UTILS_RESTRICT position);
// Member data
double * init_state; /*!< trick_units(--) @n
The state at the start of an integration cycle. */
double * deriv_hist[4]; /*!< trick_units(--) @n
The state derivatives at the start of current and at the starts of the
three previous integration cycles.
This array is rotated so that deriv_hist[0] contains the state derivatives
at the start of the current cycle, deriv_hist[1] the derivatives at the
start of the previous cycle, and so on. */
};
}
#ifdef ER7_UTILS_NEED_AUX_INCLUDES
#include "er7_utils/integration/core/include/integration_controls.hh"
#endif
#endif
/**
* @if Er7UtilsUseGroups
* @}
* @}
* @endif
*/
|
TUsama/Create
|
src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/train/MinecartCouplingHandler.java
|
package com.simibubi.create.content.contraptions.components.structureMovement.train;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.simibubi.create.content.contraptions.components.structureMovement.ContraptionEntity;
import com.simibubi.create.content.contraptions.components.structureMovement.train.MinecartCouplingSerializer.CouplingData;
import com.simibubi.create.foundation.config.AllConfigs;
import com.simibubi.create.foundation.networking.AllPackets;
import com.simibubi.create.foundation.utility.Couple;
import com.simibubi.create.foundation.utility.WorldAttached;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectLists;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.minecart.AbstractMinecartEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.network.PacketDistributor;
/*
*
* Couplings are a directional connection of two Minecart entities
* - ID and Key is the UUID of the main cart
* - They are immediately written to both minecarts' nbt tags upon creation.
* {Main: true, Id: {L: ", M: "}, Length: 5}
*
* Trains are an ordered list of Couplings
* - ID and Key is the UUID of the main coupling
* - Every coupling is part of exactly one train, lonely couplings are still treated as such
* - When two trains are merged, the couplings have to be re-oriented to always point towards the main coupling
*
* Loaded carts are queued to be dealt with on world tick,
* so that the world functions are not accessed during the chunk deserialization
*
* Challenges:
* - Minecarts can only be corrected by changing their motion or their position
* - A Minecarts' motion vector does not represent its actual movement next tick
* - There is no accessible simulation step (can be copied / at'd)
* - It is not always known which cart is ahead/behind
* - If both ends keep a contant momentum, the link stress is not necessarily satisfied
* - Carts cannot be "dragged" directly towards resolving link stress;
* It is not entirely predictable how motions outside of the rail vector get projected
*
*
*
* Day III, couplings still too unstable. Why is that? What causes the instability, is it the general approach or a specific issue
* Explored strategies:
*
* Acellerate against violation diff -> perpetual motion, Jittering, bouncyness
* Brake and correct towards violation diff -> quick loss of momentum
* Move against diff -> de-rails carts on tricky paths
*
* Not yet explored: running an actual simulation step for the minecarts' movement.
*
* - satisfied link
* -- stretched link
* . shortened link
* ? not visible in ctx
* = cart
* => moving cart
*
* Create algorithm to find a tick order which maximizes resolved stress
*
* => ? <= ? = - => (@t)
* ^ tick here first
*
* cart[], motion[], position[]
* Predict through simulation + motion, that without any intervention, this happens:
*
* => ? <= ? = -- => (@t+1)
*
* Decision: Accelerate trailing? (free motion)
* Brake leading? (loss of momentum)
* -> Both?
*
* Soft collisions can always be resolved. Just have to adjust motions accordingly.
* Hard collisions should never be resolved by the soft/motion resolver, as it would generate or void momentum!
*
* Approach: Hard pass then soft pass. two iterations of the coupling list
*
* find starting point of hard resolve: the center of balance
* i from left, j from right
* compare and approach the exact center of the resolved chain.
*
* -3 -2-10v 0
* 0-----0-0-0-0
* 0--0--0--0--0
* 2 1
* 0---0-0---0---0--0--0-0-0-0-0
* 0--0--0--0--0--0--0--0--0--0--0
*
* v
* 0-0-0
* 0--0--0
*
* v
* 0---0---0---0
* 0-0-0-0
*
* -1 0 -1 0
* 0-0---0--0---0-0
* 0--0--0--0--0--0
*
*
*
* iterate both ways from the center and resolve hard collisions.
*
* <HARD Resolve>
* if coupling is NOT ok @t {
* Something unpredictable happened.
* Try to reach soft state asap. every lost cycle in hard will act strangely and render inconsistently
* Using motion to hard resolve is probably a bad idea
*
* if cart on rail -> force move along rail away from collision
* else straight-up push it
* use simulation to test if movements are possible
*
* hard resolves are usually quite tiny. If they go beyond 1m then something really messed up
* }
*
* if coupling could not be fixed {
* clear all motion of the two carts (?)
* A failed hard collision implies that the Minecarts cannot be forced together/apart, might aswell not make things worse
* }
* </HARD Resolve>
*
* Soft collisions only mess with motion values. It is still good to find a good order of iteration-
* that way predictions of earlier couplings in the loop are still accurate
*
* =>>> - = - <= - =>>
*
* left to right
* =>> - = - => - =>
* right to left
* =>> - => - = - =>
*
*
*
*
* if now coupling is ok @t {
* <Soft Resolve>
* Run Prediction I
* if (coupling is ok @t+1)
* my job here is done; return
*
* get required force to resolve (front or back)
* distribute equally over both carts
*
* Run Prediction II
* if (coupling is ok @t+1*)
* looks good; return
*
* re-distribute force to other cart
* all collisions should be fixed at this point. return;
* (in case of sudden changes/ bad predictions, the next cycle can handle the hard resolve)
* </Soft Resolve>
* }
*
*
*
* NEXT STEPS
* 1. normalize diagonal rail vectors and debug all possible rail motion transfers. The required tools have to work properly
* 2. implement a prediction step
* 3. find a suitable hard collision resolver
* 4. find a suitable soft collision order
*
*/
public class MinecartCouplingHandler {
static WorldAttached<Map<UUID, MinecartCoupling>> loadedCouplings = new WorldAttached<>(HashMap::new);
static WorldAttached<Map<UUID, MinecartTrain>> loadedTrains = new WorldAttached<>(HashMap::new);
static WorldAttached<List<AbstractMinecartEntity>> queuedCarts =
new WorldAttached<>(() -> ObjectLists.synchronize(new ObjectArrayList<>()));
public static void connectCarts(@Nullable PlayerEntity player, World world, int cartId1, int cartId2) {
Entity entity1 = world.getEntityByID(cartId1);
Entity entity2 = world.getEntityByID(cartId2);
if (!(entity1 instanceof AbstractMinecartEntity))
return;
if (!(entity2 instanceof AbstractMinecartEntity))
return;
if ((int) entity1.getPositionVec()
.distanceTo(entity2.getPositionVec()) > maxDistance())
return;
AbstractMinecartEntity cart1 = (AbstractMinecartEntity) entity1;
AbstractMinecartEntity cart2 = (AbstractMinecartEntity) entity2;
if (alreadyCoupled(world, cart1, cart2))
return;
addCoupling(world, MinecartCoupling.create(cart1, cart2), false);
if (world.isRemote)
return;
AllPackets.channel.send(PacketDistributor.TRACKING_ENTITY.with(() -> cart1),
new MinecartCouplingSyncPacket(cart1, cart2));
}
@OnlyIn(Dist.CLIENT)
public static void render(MatrixStack ms, IRenderTypeBuffer buffer) {
ClientWorld world = Minecraft.getInstance().world;
if (world == null)
return;
loadedCouplings.get(world)
.values()
.forEach(c -> MinecartCouplingRenderer.renderCoupling(ms, buffer, c));
}
public static void tick(World world) {
initQueuedCarts(world);
removeUnloadedCouplings(world);
loadedTrains.get(world)
.values()
.forEach(t -> t.tickCouplings(world));
}
private static void initQueuedCarts(World world) {
List<AbstractMinecartEntity> queued = queuedCarts.get(world);
if (queued == null)
return;
for (AbstractMinecartEntity minecart : queued)
MinecartCoupling.loadAllAttached(world, minecart)
.forEach(c -> addCoupling(world, c, true));
queued.clear();
}
private static void removeUnloadedCouplings(World world) {
List<UUID> toRemove = new ArrayList<>();
Map<UUID, MinecartCoupling> couplings = loadedCouplings.get(world);
if (couplings == null)
return;
for (Entry<UUID, MinecartCoupling> entry : couplings.entrySet())
if (!entry.getValue()
.areBothEndsPresent())
toRemove.add(entry.getKey());
couplings.keySet()
.removeAll(toRemove);
}
public static void handleAddedMinecart(Entity entity, World world) {
if (!(entity instanceof AbstractMinecartEntity))
return;
if (world.isRemote)
queueLoadedMinecartClient(entity, world);
else
queueLoadedMinecart(entity, world);
}
public static void queueLoadedMinecartClient(Entity entity, World world) {
AllPackets.channel.sendToServer(new PersistantDataPacketRequest(entity));
}
public static void queueLoadedMinecart(Entity entity, World world) {
AbstractMinecartEntity minecart = (AbstractMinecartEntity) entity;
CompoundNBT nbt = minecart.getPersistentData();
if (!nbt.contains("Couplings"))
return;
queuedCarts.get(world)
.add(minecart);
}
static int maxDistance() {
return AllConfigs.SERVER.kinetics.maxCartCouplingLength.get();
}
public static Pair<UUID, Boolean> getTrainIfComplete(World world, AbstractMinecartEntity minecart,
@Nullable UUID ignore) {
AbstractMinecartEntity current = minecart;
UUID trainId = current.getUniqueID();
for (int i = 0; i < 100; i++) {
List<CouplingData> couplingData = MinecartCouplingSerializer.getCouplingData(current);
for (CouplingData data : couplingData) {
if (data.main)
continue;
if (ignore != null && ignore.equals(data.id))
continue;
trainId = data.id;
MinecartCoupling coupling = loadedCouplings.get(world)
.get(trainId);
// Not fully loaded in
if (coupling == null)
return Pair.of(trainId, false);
current = coupling.mainCart.get();
}
}
// Complete
return Pair.of(trainId, true);
}
private static boolean alreadyCoupled(World world, AbstractMinecartEntity cart1, AbstractMinecartEntity cart2) {
Pair<UUID, Boolean> trainOf = getTrainIfComplete(world, cart1, null);
Pair<UUID, Boolean> trainOf2 = getTrainIfComplete(world, cart2, null);
return trainOf.getRight() && trainOf2.getRight() && trainOf.getLeft()
.equals(trainOf2.getLeft());
}
private static void addCoupling(World world, MinecartCoupling coupling, boolean loadedFromChunk) {
MinecartTrain train = new MinecartTrain(coupling);
Pair<UUID, Boolean> trainIdOfMain = getTrainIfComplete(world, coupling.mainCart.get(), null);
Pair<UUID, Boolean> trainIdOfConnected =
getTrainIfComplete(world, coupling.connectedCart.get(), loadedFromChunk ? coupling.getId() : null);
// Something is not loaded
if (!loadedFromChunk && !(trainIdOfMain.getValue() && trainIdOfConnected.getValue()))
return;
// Coupling was already loaded in
if (loadedFromChunk && loadedCouplings.get(world)
.containsKey(coupling.getId()))
return;
if (!world.isRemote) {
Map<UUID, MinecartTrain> trains = loadedTrains.get(world);
MinecartTrain trainOfMain = trains.get(trainIdOfMain.getKey());
MinecartTrain trainOfConnected = trains.get(trainIdOfConnected.getKey());
// Connected cart is part of a train, merge it onto the newly created one
if (trainOfConnected != null)
trains.remove(trainIdOfConnected.getKey())
.mergeOnto(world, train);
// Main cart is part of a train, merge the newly created one onto it
boolean mainCartHasTrain = trainOfMain != null && trainIdOfMain.getKey()
.equals(coupling.getId());
if (trainOfMain != null) {
if (mainCartHasTrain && !loadedFromChunk)
flipTrain(world, trainOfMain);
train.mergeOnto(world, trainOfMain);
train = null;
}
// ...add the new train otherwise
if (train != null)
trains.put(train.getId(), train);
}
loadedCouplings.get(world)
.put(coupling.getId(), coupling);
if (!loadedFromChunk)
coupling.writeToCarts();
}
public static void flipTrain(World world, MinecartTrain train) {
Map<UUID, MinecartTrain> map = loadedTrains.get(world);
map.remove(train.getId());
train.flip(world);
map.put(train.getId(), train);
}
public static MinecartCoupling getCoupling(World world, UUID id) {
Map<UUID, MinecartCoupling> map = loadedCouplings.get(world);
return map.get(id);
}
public static void flipCoupling(World world, MinecartCoupling coupling) {
Map<UUID, MinecartCoupling> map = loadedCouplings.get(world);
map.remove(coupling.getId());
if (coupling.areBothEndsPresent()) {
Couple<AbstractMinecartEntity> carts = coupling.asCouple();
Couple<UUID> ids = carts.map(Entity::getUniqueID);
carts.map(c -> c.isBeingRidden() ? c.getPassengers()
.get(0) : null)
.map(c -> c instanceof ContraptionEntity ? (ContraptionEntity) c : null)
.forEachWithContext((contraption, current) -> {
if (contraption == null || contraption.getCouplingId() == null)
return;
boolean switchTo = contraption.getCouplingId()
.equals(ids.get(current)) ? !current : current;
if (!carts.get(switchTo).getUniqueID().equals(contraption.getCoupledCart()))
return;
contraption.setCouplingId(ids.get(switchTo));
contraption.setCoupledCart(ids.get(!switchTo));
});
}
coupling.flip();
map.put(coupling.getId(), coupling);
}
}
|
epedropaulo/MyPython
|
03 - Estruturas Compostas/ex082.py
|
valores = []
impares = []
pares = []
while True:
valor = int(input('Digite um número: '))
valores.append(valor)
continuar = str(input('Deseja continuar? [S/N] ')).upper()[0]
while continuar not in 'SN':
continuar = str(input('Tente novamente! Deseja continuar? [S/N]')).upper()[0]
if continuar in 'N':
break
for v in valores:
if v % 2 == 0:
pares.append(v)
else:
impares.append(v)
print('-=' * 30)
print(f'Todos os valores são: {valores}')
print(f'Os pares são: {pares}')
print(f'Os ímpares são: {impares}')
|
SyllogismRXS/opencv-workbench
|
src/wb/Blob.cpp
|
#include <iostream>
#include "Blob.h"
using std::cout;
using std::endl;
namespace wb {
Blob::Blob()
{
set_id(-1);
}
Blob::Blob(int id)
{
set_id(id);
}
}
|
moraispgsi/3linha
|
Milestone1/src/TADInterfaces/Comparador.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package TADInterfaces;
/**
* O Comparador descreve a maneira como são ordenados os dados de um
* certo tipo de elementos.
*
* @author <NAME>
* @param <E> Tipo de elemento a ordenar
*/
public interface Comparador<E> {
/**
* Diz se estão ordenados de acordo com este tipo de ordenação
*
* @param esquerdo elemento do lado esquerdo
* @param direito elemento do lado direito
* @return true se os elementos devem ser trocados e false senão
*
*/
public boolean comparar(E esquerdo,E direito);
}
|
erezhasson/RSE
|
src/logic/src/exceptions/symbol/SymbolException.java
|
package exceptions.symbol;
public class SymbolException extends Exception {
protected final String symbol;
public SymbolException(String symbol) {
this.symbol = symbol;
}
@Override
public String getMessage() {
return "Something went wrong with " + symbol;
}
}
|
tiger0132/code-backup
|
Codeforces/1000~1999/1199/D.cpp
|
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <set>
const int N = 2e5 + 52;
extern struct node _[];
int cnt;
struct node {
int l, r, mid, lc, rc, t, v;
void put(int x) {
if (l == r) v = std::max(v, x);
t = std::max(t, x);
}
void pd() { lc[_].put(t), rc[_].put(t), t = 0; }
void build(int L, int R) {
l = L, r = R, mid = (l + r) / 2, t = 0;
if (L == R) return void(scanf("%d", &v));
_[lc = ++cnt].build(L, mid);
_[rc = ++cnt].build(mid + 1, R);
}
void upd(int id, int x) {
pd();
if (l == r) return void(v = x);
if (id <= mid) return lc[_].upd(id, x);
rc[_].upd(id, x);
}
void prt() {
pd();
if (l == r) return (void)printf("%d ", v);
lc[_].prt(), rc[_].prt();
}
} _[N << 2];
int n, a[222222], q, op, x, y;
int main() {
scanf("%d", &n);
_[++cnt].build(1, n);
for (scanf("%d", &q); q--;) {
scanf("%d%d", &op, &x);
if (op == 1)
scanf("%d", &y), _[1].upd(x, y);
else
_[1].put(x);
}
_[1].prt();
}
|
npocmaka/Windows-Server-2003
|
admin/darwin/src/msitools/msiregmv/msiregmv.h
|
//+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 2000
//
// File: msiregmv.h
//
//--------------------------------------------------------------------------
#pragma once
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include "msiquery.h"
// based off on values from winnt.h
const int cbMaxSID = sizeof(SID) + SID_MAX_SUB_AUTHORITIES*sizeof(DWORD);
const int cchMaxSID = 256;
const int cchGUIDPacked = 32;
const int cchGUID = 38;
////
// miscellaneous functions
bool CanonicalizeAndVerifyPackedGuid(LPTSTR szString);
bool PackGUID(const TCHAR* szGUID, TCHAR rgchPackedGUID[cchGUIDPacked+1]);
bool UnpackGUID(const TCHAR rgchPackedGUID[cchGUIDPacked+1], TCHAR* szGUID);
bool CheckWinVersion();
////
// security functions
bool FIsKeyLocalSystemOrAdminOwned(HKEY hKey);
DWORD GetCurrentUserStringSID(TCHAR* szSID);
DWORD GetSecureSecurityDescriptor(char** pSecurityDescriptor);
DWORD GetEveryoneUpdateSecurityDescriptor(char** pSecurityDescriptor);
DWORD GenerateSecureTempFile(TCHAR* szDirectory, const TCHAR rgchExtension[5],
SECURITY_ATTRIBUTES *pSA, TCHAR rgchFilename[13], HANDLE &hFile);
bool DeleteRegKeyAndSubKeys(HKEY hKey, const TCHAR *szSubKey);
BOOL CopyOpenedFile(HANDLE hSourceFile, HANDLE hDestFile);
DWORD CreateSecureRegKey(HKEY hParent, LPCTSTR szNewKey, SECURITY_ATTRIBUTES *sa, HKEY* hResKey);
void AcquireTakeOwnershipPriv();
void AcquireBackupPriv();
// enum for managed attribute
enum eManagedType
{
emtNonManaged = 0,
emtUserManaged = 1,
emtMachineManaged = 2,
};
////
// debug information
void DebugOut(bool fDebugOut, LPCTSTR str, ...);
#ifdef DEBUG
#define DEBUGMSG(x) DebugOut(true, TEXT(x))
#define DEBUGMSG1(x,a) DebugOut(true, TEXT(x),a)
#define DEBUGMSG2(x,a,b) DebugOut(true, TEXT(x),a,b)
#define DEBUGMSG3(x,a,b,c) DebugOut(true, TEXT(x),a,b,c)
#define DEBUGMSG4(x,a,b,c,d) DebugOut(true, TEXT(x),a,b,c,d)
// basically just printf, but can easily be changed to write to
// debug output by passing "true". Used for "notification"
// messages that shouldn't be part of debug spooge.
#define NOTEMSG(x) DebugOut(false, TEXT(x))
#define NOTEMSG1(x,a) DebugOut(false, TEXT(x),a)
// all resizable buffers start out at this size in debug builds.
// set this to a small number to force reallocations
#define MEMORY_DEBUG(x) 10
#else
#define DEBUGMSG(x)
#define DEBUGMSG1(x,a)
#define DEBUGMSG2(x,a,b)
#define DEBUGMSG3(x,a,b,c)
#define DEBUGMSG4(x,a,b,c,d)
#define NOTEMSG(x)
#define NOTEMSG1(x,a)
#define MEMORY_DEBUG(x) x
#endif
DWORD ReadProductRegistrationDataIntoDatabase(TCHAR* szDatabase, MSIHANDLE& hDatabase, bool fReadHKCUAsSystem);
DWORD WriteProductRegistrationDataFromDatabase(MSIHANDLE hDatabase, bool fMigrateSharedDLL, bool fMigratePatches);
DWORD UpdateSharedDLLRefCounts(MSIHANDLE hDatabase);
DWORD ReadComponentRegistrationDataIntoDatabase(MSIHANDLE hDatabase);
DWORD MigrateUserOnlyComponentData(MSIHANDLE hDatabase);
extern bool g_fWin9X;
////
// cached data functions
DWORD MigrateCachedDataFromWin9X(MSIHANDLE hDatabase, HKEY hUserHKCUKey, HKEY hUserDataKey, LPCTSTR szUser);
////
// patch functions
DWORD AddProductPatchesToPatchList(MSIHANDLE hDatabase, HKEY hProductListKey, LPCTSTR szUser, TCHAR rgchProduct[cchGUIDPacked+1], eManagedType eManaged);
DWORD MigrateUnknownProductPatches(MSIHANDLE hDatabase, HKEY hProductKey, LPCTSTR szUser, TCHAR rgchProduct[cchGUIDPacked+1]);
DWORD MigrateUserPatches(MSIHANDLE hDatabase, LPCTSTR szUser, HKEY hNewPatchesKey, bool fCopyCachedPatches);
DWORD ScanCachedPatchesForProducts(MSIHANDLE hDatabase);
DWORD AddPerUserPossiblePatchesToPatchList(MSIHANDLE hDatabase);
////
// cleanup functions
void CleanupOnFailure(MSIHANDLE hDatabase);
void CleanupOnSuccess(MSIHANDLE hDatabase);
const TCHAR szLocalSystemSID[] = TEXT("S-1-5-18");
const TCHAR szCommonUserSID[] = TEXT("CommonUser");
const TCHAR szLocalPackagesKeyName[] = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\LocalPackages");
const TCHAR szManagedPackageKeyEnd[] = TEXT("(Managed)");
const DWORD cchManagedPackageKeyEnd = sizeof(szManagedPackageKeyEnd)/sizeof(TCHAR);
////
// product source registry keys
const TCHAR szPerMachineInstallKeyName[] = TEXT("Software\\Classes\\Installer\\Products");
const TCHAR szPerUserInstallKeyName[] = TEXT("Software\\Microsoft\\Installer\\Products");
const TCHAR szPerUserManagedInstallKeyName[] = TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed");
const TCHAR szPerUserManagedInstallSubKeyName[] = TEXT("\\Installer\\Products");
const int cchPerUserManagedInstallKeyName = sizeof(szPerUserManagedInstallKeyName)/sizeof(TCHAR);
const DWORD cchPerUserManagedInstallSubKeyName = sizeof(szPerUserManagedInstallSubKeyName)/sizeof(TCHAR);
const TCHAR szNewProductSubKeyName[] = TEXT("Products");
////
// some generic paths used in multiple places
const TCHAR szNewInstallPropertiesSubKeyName[] = TEXT("InstallProperties");
const TCHAR szInstallerDir[] = TEXT("\\Installer\\");
const TCHAR szNewPatchesSubKeyName[] = TEXT("Patches");
const TCHAR szTransformsValueName[] = TEXT("Transforms");
|
yuriy-litvinenko/job4j
|
01_trainee/trainee_chapter_02/src/main/java/ru/job4j/coffee/CoffeeMachine.java
|
<reponame>yuriy-litvinenko/job4j<filename>01_trainee/trainee_chapter_02/src/main/java/ru/job4j/coffee/CoffeeMachine.java
package ru.job4j.coffee;
class CoffeeMachine {
int[] changes(int value, int price) {
int change = value - price;
int[] coins = {10, 5, 2, 1};
int[] buffer = new int[change];
int coinsCnt = 0;
for (int coin : coins) {
while (change >= coin) {
change -= coin;
buffer[coinsCnt++] = coin;
}
}
int[] result = new int[coinsCnt];
System.arraycopy(buffer, 0, result, 0, result.length);
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.