text stringlengths 1 1.05M |
|---|
#!/bin/sh
make -C /Users/michaelli/Documents/sdc/t2/p2/CarND-Unscented-Kalman-Filter-Project/ide_profiles/xcode -f /Users/michaelli/Documents/sdc/t2/p2/CarND-Unscented-Kalman-Filter-Project/ide_profiles/xcode/CMakeScripts/ZERO_CHECK_cmakeRulesBuildPhase.make$CONFIGURATION all
|
<reponame>shaunakpp/voices-of-consent
require 'rails_helper'
RSpec.describe "locations/index", type: :view do
before(:each) do
assign(:locations, [
Location.create!(
:name => "Name",
:street_address => "Street Address",
:city => "City",
:state => "State",
:zip => "Zip",
:type => 2
),
Location.create!(
:name => "Name",
:street_address => "Street Address",
:city => "City",
:state => "State",
:zip => "Zip",
:type => 2
)
])
end
it "renders a list of locations" do
render
assert_select "tr>td", :text => "Name".to_s, :count => 2
assert_select "tr>td", :text => "Street Address".to_s, :count => 2
assert_select "tr>td", :text => "City".to_s, :count => 2
assert_select "tr>td", :text => "State".to_s, :count => 2
assert_select "tr>td", :text => "Zip".to_s, :count => 2
assert_select "tr>td", :text => 2.to_s, :count => 2
end
end
|
<reponame>smagill/opensphere-desktop<gh_stars>10-100
package io.opensphere.core.animation.impl;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import io.opensphere.core.animation.AnimationPlan;
import io.opensphere.core.animation.AnimationPlan.EndBehavior;
import io.opensphere.core.animation.AnimationState;
import io.opensphere.core.animation.AnimationState.Direction;
import io.opensphere.core.animation.ContinuousAnimationPlan;
import io.opensphere.core.model.time.TimeSpan;
import io.opensphere.core.units.duration.Duration;
import io.opensphere.core.units.duration.Milliseconds;
import io.opensphere.core.units.duration.Minutes;
import io.opensphere.core.units.duration.Seconds;
/** Test for {@link DefaultContinuousAnimationPlan}. */
public class DefaultContinuousAnimationPlanTest
{
/**
* Test constructor.
*/
@SuppressWarnings("unused")
@Test
public void testDefaultContinuousAnimationPlan()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
Duration window = Minutes.ONE;
Duration advance = new Seconds(10);
EndBehavior endBehavior = EndBehavior.STOP;
TimeSpan limit = null;
Duration fade = null;
new DefaultContinuousAnimationPlan(sequence, window, advance, endBehavior, limit);
}
/**
* Test constructor with bad input.
*/
@SuppressWarnings("unused")
@Test
public void testDefaultContinuousAnimationPlanEmptySequence()
{
List<? extends TimeSpan> sequence = Collections.emptyList();
Duration window = Minutes.ONE;
Duration advance = new Seconds(10);
EndBehavior endBehavior = EndBehavior.STOP;
TimeSpan limit = null;
Duration fade = null;
new DefaultContinuousAnimationPlan(sequence, window, advance, endBehavior, limit);
}
/**
* Test constructor with bad input.
*/
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void testDefaultContinuousAnimationPlanNullAdvance()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
Duration window = Minutes.ONE;
Duration advance = null;
EndBehavior endBehavior = EndBehavior.STOP;
TimeSpan limit = null;
Duration fade = null;
new DefaultContinuousAnimationPlan(sequence, window, advance, endBehavior, limit);
}
/**
* Test constructor with bad input.
*/
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void testDefaultContinuousAnimationPlanNullEndBehavior()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
Duration window = Minutes.ONE;
Duration advance = new Seconds(10);
EndBehavior endBehavior = null;
TimeSpan limit = null;
Duration fade = null;
new DefaultContinuousAnimationPlan(sequence, window, advance, endBehavior, limit);
}
/**
* Test constructor with bad input.
*/
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void testDefaultContinuousAnimationPlanNullSequence()
{
List<? extends TimeSpan> sequence = null;
Duration window = Minutes.ONE;
Duration advance = new Seconds(10);
EndBehavior endBehavior = EndBehavior.STOP;
TimeSpan limit = null;
Duration fade = null;
new DefaultContinuousAnimationPlan(sequence, window, advance, endBehavior, limit);
}
/**
* Test constructor with bad input.
*/
@SuppressWarnings("unused")
@Test(expected = IllegalArgumentException.class)
public void testDefaultContinuousAnimationPlanNullWindow()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
Duration window = null;
Duration advance = new Seconds(10);
EndBehavior endBehavior = EndBehavior.STOP;
TimeSpan limit = null;
Duration fade = null;
new DefaultContinuousAnimationPlan(sequence, window, advance, endBehavior, limit);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(io.opensphere.core.animation.AnimationState)}
* with bad input.
*/
@Test(expected = IllegalArgumentException.class)
public void testDetermineNextStateBadState1()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
plan.determineNextState(new DefaultContinuousAnimationState(2, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(io.opensphere.core.animation.AnimationState)}
* with bad input.
*/
@Test(expected = IllegalArgumentException.class)
public void testDetermineNextStateBadState2()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
plan.determineNextState(new DefaultContinuousAnimationState(1, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#BOUNCE} end behavior.
*/
@Test
public void testDetermineNextStateBounceAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.BOUNCE, null);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
testDetermineNextStateCommon1(plan);
DefaultContinuousAnimationState result7 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7130000L, 7190000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result7);
DefaultContinuousAnimationState result8 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected8 = new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected8, result8);
testDetermineNextStateCommon2(plan);
DefaultContinuousAnimationState result13 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected13 = new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected13, result13);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#BOUNCE} end behavior and a limit window.
*/
@Test
public void testDetermineNextStateBounceAtEndLimited()
{
TimeSpan limit = TimeSpan.get(1800000L, 4800000L);
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.BOUNCE, limit);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(1810000L, 1870000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
testDetermineNextStateCommon1(plan);
DefaultContinuousAnimationState result7 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4730000L, 4790000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result7);
DefaultContinuousAnimationState result8 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected8 = new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected8, result8);
testDetermineNextStateCommon3(plan);
DefaultContinuousAnimationState result13 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected13 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected13, result13);
DefaultContinuousAnimationState result14 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected14 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected14, result14);
DefaultContinuousAnimationState result15 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected15 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected15, result15);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#BOUNCE} end behavior and a single span in the
* sequence.
*/
@Test
public void testDetermineNextStateSingleSpanSequenceBounceAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.BOUNCE, null);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
DefaultContinuousAnimationState result2 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3530000L, 3590000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected2 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected2, result2);
DefaultContinuousAnimationState result3 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected3 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected3, result3);
DefaultContinuousAnimationState result4 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected4 = new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected4, result4);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#STOP} end behavior and a single span in the sequence.
*/
@Test
public void testDetermineNextStateSingleSpanSequenceStopAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
DefaultContinuousAnimationState result2 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3530000L, 3590000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected2 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected2, result2);
DefaultContinuousAnimationState result3 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L), AnimationState.Direction.FORWARD));
Assert.assertNull(result3);
DefaultContinuousAnimationState result4 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), AnimationState.Direction.BACKWARD));
Assert.assertNull(result4);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#WRAP} end behavior and a single span in the sequence.
*/
@Test
public void testDetermineNextStateSingleSpanSequenceWrapAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.WRAP, null);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
DefaultContinuousAnimationState result2 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3530000L, 3590000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected2 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected2, result2);
DefaultContinuousAnimationState result3 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected3 = new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected3, result3);
DefaultContinuousAnimationState result4 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected4 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected4, result4);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#STOP} end behavior.
*/
@Test
public void testDetermineNextStateStopAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
testDetermineNextStateCommon1(plan);
DefaultContinuousAnimationState result7 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7130000L, 7190000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result7);
DefaultContinuousAnimationState result8 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7180000L, 7200000L), AnimationState.Direction.FORWARD));
Assert.assertNull(result8);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#STOP} end behavior and a limit window.
*/
@Test
public void testDetermineNextStateStopAtEndLimited()
{
TimeSpan limit = TimeSpan.get(1800000L, 4800000L);
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3000000L), TimeSpan.get(3000000L, 4000000L),
TimeSpan.get(4000000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, limit);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1810000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(1810000L, 1870000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
DefaultContinuousAnimationState result2 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(2940000L, 3000000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected2 = new DefaultContinuousAnimationState(1, TimeSpan.get(3000000L, 3060000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected2, result2);
DefaultContinuousAnimationState result3 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(2930000L, 2990000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected3 = new DefaultContinuousAnimationState(0, TimeSpan.get(2940000L, 3000000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected3, result3);
DefaultContinuousAnimationState result4 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(2940000L, 3000000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected4 = new DefaultContinuousAnimationState(1, TimeSpan.get(3000000L, 3060000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected4, result4);
DefaultContinuousAnimationState result5 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3000000L, 3060000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected5 = new DefaultContinuousAnimationState(1, TimeSpan.get(3010000L, 3070000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected5, result5);
DefaultContinuousAnimationState result7 = plan.determineNextState(
new DefaultContinuousAnimationState(2, TimeSpan.get(4730000L, 4790000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(2, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result7);
DefaultContinuousAnimationState result8 = plan.determineNextState(
new DefaultContinuousAnimationState(2, TimeSpan.get(4780000L, 4800000L), AnimationState.Direction.FORWARD));
Assert.assertNull(result8);
DefaultContinuousAnimationState result14 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected14 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected14, result14);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#WRAP} end behavior.
*/
@Test
public void testDetermineNextStateWrapAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.WRAP, null);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
testDetermineNextStateCommon1(plan);
DefaultContinuousAnimationState result7 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7130000L, 7190000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result7);
DefaultContinuousAnimationState result8 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected8 = new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected8, result8);
testDetermineNextStateCommon2(plan);
DefaultContinuousAnimationState result13 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected13 = new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected13, result13);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determineNextState(AnimationState)} with
* {@link EndBehavior#WRAP} end behavior and a limit window.
*/
@Test
public void testDetermineNextStateWrapAtEndLimited()
{
TimeSpan limit = TimeSpan.get(1800000L, 4800000L);
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.WRAP, limit);
DefaultContinuousAnimationState result1 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1800001L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(1810000L, 1870000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
testDetermineNextStateCommon1(plan);
DefaultContinuousAnimationState result7 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4730000L, 4790000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result7);
DefaultContinuousAnimationState result8 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected8 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected8, result8);
testDetermineNextStateCommon3(plan);
DefaultContinuousAnimationState result13 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected13 = new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected13, result13);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with bad input.
*/
@Test(expected = IllegalArgumentException.class)
public void testDeterminePreviousStateBadState1()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
plan.determinePreviousState(
new DefaultContinuousAnimationState(2, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with bad input.
*/
@Test(expected = IllegalArgumentException.class)
public void testDeterminePreviousStateBadState2()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(0L, 1L), AnimationState.Direction.FORWARD));
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with {@link EndBehavior#BOUNCE} end behavior.
*/
@Test
public void testDeterminePreviousStateBounceAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.BOUNCE, null);
DefaultContinuousAnimationState result1 = plan.determinePreviousState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected1, result1);
testDeterminePreviousStateCommon2(plan);
DefaultContinuousAnimationState result8 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected9 = new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected9, result8);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with {@link EndBehavior#BOUNCE} end behavior and a limit window.
*/
@Test
public void testDeterminePreviousStateBounceAtEndLimited()
{
TimeSpan limit = TimeSpan.get(1800000L, 4800000L);
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.BOUNCE, limit);
DefaultContinuousAnimationState result1 = plan.determinePreviousState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected1, result1);
testDeterminePreviousStateCommon1(plan);
DefaultContinuousAnimationState result8 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected9 = new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected9, result8);
DefaultContinuousAnimationState result14 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected14 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected14, result14);
DefaultContinuousAnimationState result15 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected15 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected15, result15);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with {@link EndBehavior#STOP} end behavior.
*/
@Test
public void testDeterminePreviousStateStopAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
DefaultContinuousAnimationState result1 = plan.determinePreviousState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 10000L), AnimationState.Direction.FORWARD));
Assert.assertNull(result1);
testDeterminePreviousStateCommon2(plan);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with {@link EndBehavior#STOP} end behavior and a limit window.
*/
@Test
public void testDeterminePreviousStateStopAtEndLimited()
{
TimeSpan limit = TimeSpan.get(1800000L, 4800000L);
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 4800000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, limit);
DefaultContinuousAnimationState result1 = plan.determinePreviousState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1810000L), AnimationState.Direction.FORWARD));
Assert.assertNull(result1);
testDeterminePreviousStateCommon1(plan);
DefaultContinuousAnimationState result14 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected14 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected14, result14);
DefaultContinuousAnimationState result15 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.BACKWARD));
Assert.assertNull(result15);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with {@link EndBehavior#WRAP} end behavior.
*/
@Test
public void testDeterminePreviousStateWrapAtEnd()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.WRAP, null);
DefaultContinuousAnimationState result1 = plan.determinePreviousState(
new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 10000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
testDeterminePreviousStateCommon2(plan);
DefaultContinuousAnimationState result8 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected9 = new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected9, result8);
}
/**
* Test for
* {@link ContinuousAnimationPlan#determinePreviousState(io.opensphere.core.animation.AnimationState)}
* with {@link EndBehavior#WRAP} end behavior and a limit window.
*/
@Test
public void testDeterminePreviousStateWrapAtEndLimited()
{
TimeSpan limit = TimeSpan.get(1800000L, 4800000L);
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 4800000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.WRAP, limit);
DefaultContinuousAnimationState result1 = plan.determinePreviousState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1810000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected1 = new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected1, result1);
testDeterminePreviousStateCommon1(plan);
DefaultContinuousAnimationState result8 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected9 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected9, result8);
DefaultContinuousAnimationState result14 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected14 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected14, result14);
DefaultContinuousAnimationState result15 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1700000L, 1760000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected15 = new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected15, result15);
}
/**
* Test for
* {@link ContinuousAnimationPlan#findState(java.util.Date, io.opensphere.core.animation.AnimationState.Direction)}
* .
*/
@Test
public void testFindStateDateDirection()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.FORWARD),
plan.findState(new Date(0L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L), Direction.FORWARD),
plan.findState(new Date(10000L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), Direction.FORWARD),
plan.findState(new Date(3600000L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.BACKWARD),
plan.findState(new Date(60000L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L), Direction.BACKWARD),
plan.findState(new Date(70000L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), Direction.BACKWARD),
plan.findState(new Date(3660000L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.FORWARD),
plan.findState(new Date(-1L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.BACKWARD),
plan.findState(new Date(-1L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), Direction.FORWARD),
plan.findState(new Date(7200000L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), Direction.BACKWARD),
plan.findState(new Date(7200000L), Direction.BACKWARD));
}
/**
* Test for {@link AnimationPlan#findState(TimeSpan, Direction)} .
*/
@Test
public void testFindStateTimeSpanDirection()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L), TimeSpan.get(3600000L, 7200000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, Minutes.ONE, new Seconds(10),
EndBehavior.STOP, null);
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.FORWARD),
plan.findState(TimeSpan.get(0L, 50000L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L), Direction.FORWARD),
plan.findState(TimeSpan.get(10000L, 60000L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), Direction.FORWARD),
plan.findState(TimeSpan.get(3600000L, 3650000L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.BACKWARD),
plan.findState(TimeSpan.get(1L, 60000L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L), Direction.BACKWARD),
plan.findState(TimeSpan.get(10001L, 70000L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), Direction.BACKWARD),
plan.findState(TimeSpan.get(3601000L, 3660000L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.FORWARD),
plan.findState(TimeSpan.get(0L, 1L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.BACKWARD),
plan.findState(TimeSpan.get(0L, 1L), Direction.BACKWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), Direction.FORWARD),
plan.findState(TimeSpan.get(7140000L, 7150000L), Direction.FORWARD));
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), Direction.BACKWARD),
plan.findState(TimeSpan.get(7140001L, 7200000L), Direction.BACKWARD));
}
/**
* Test for {@link ContinuousAnimationPlan#getInitialState()} .
*/
@Test
public void testGetInitialState()
{
DefaultContinuousAnimationPlan plan = createPlan();
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.FORWARD),
plan.getInitialState());
}
/**
* Test for {@link ContinuousAnimationPlan#getFinalState()} .
*/
@Test
public void testGetFinalState()
{
DefaultContinuousAnimationPlan plan = createPlan();
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L), Direction.FORWARD),
plan.getFinalState());
}
/**
* Test for {@link ContinuousAnimationPlan#getFinalState(AnimationState)} .
*/
@Test
public void testGetFinalStateAnimationState()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 1000L), TimeSpan.get(1000L, 2000L));
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, new Milliseconds(500L),
new Milliseconds(15L), EndBehavior.WRAP, null);
DefaultContinuousAnimationState start;
start = new DefaultContinuousAnimationState(0, TimeSpan.get(500L, 1000L), Direction.FORWARD);
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(1495L, 1995L), Direction.FORWARD),
plan.getFinalState(start));
start = new DefaultContinuousAnimationState(1, TimeSpan.get(1005L, 1505L), Direction.FORWARD);
Assert.assertEquals(new DefaultContinuousAnimationState(1, TimeSpan.get(1500L, 2000L), Direction.FORWARD),
plan.getFinalState(start));
// go backwards
start = new DefaultContinuousAnimationState(1, TimeSpan.get(1000L, 1500L), Direction.BACKWARD);
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(5L, 505L), Direction.BACKWARD),
plan.getFinalState(start));
start = new DefaultContinuousAnimationState(0, TimeSpan.get(490L, 990L), Direction.BACKWARD);
Assert.assertEquals(new DefaultContinuousAnimationState(0, TimeSpan.get(10L, 510L), Direction.BACKWARD),
plan.getFinalState(start));
}
/**
* Test for
* {@link ContinuousAnimationPlan#getTimeSpanForState(io.opensphere.core.animation.AnimationState)}
* .
*/
@Test
public void testGetTimeSpanForState()
{
Assert.assertEquals(TimeSpan.get(0L, 60000L), createPlan()
.getTimeSpanForState(new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L), Direction.FORWARD)));
}
/**
* Test for
* {@link ContinuousAnimationPlan#getTimeSpanForState(io.opensphere.core.animation.AnimationState)}
* with bad input.
*/
@Test(expected = IllegalArgumentException.class)
public void testGetTimeSpanForStateBadState()
{
createPlan().getTimeSpanForState(null);
}
/**
* Helper that creates a plan.
*
* @return The plan.
*/
protected DefaultContinuousAnimationPlan createPlan()
{
List<? extends TimeSpan> sequence = Arrays.asList(TimeSpan.get(0L, 3600000L));
Duration window = Minutes.ONE;
Duration advance = new Seconds(10);
EndBehavior endBehavior = EndBehavior.STOP;
TimeSpan limit = null;
DefaultContinuousAnimationPlan plan = new DefaultContinuousAnimationPlan(sequence, window, advance, endBehavior, limit);
return plan;
}
/**
* Test some
* {@link DefaultContinuousAnimationPlan#determineNextState(DefaultContinuousAnimationState)}
* results that are common amongst some different end behaviors.
*
* @param plan The plan.
*/
private void testDetermineNextStateCommon1(DefaultContinuousAnimationPlan plan)
{
DefaultContinuousAnimationState result2 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected2 = new DefaultContinuousAnimationState(1, TimeSpan.get(3610000L, 3670000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected2, result2);
DefaultContinuousAnimationState result3 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3530000L, 3590000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected3 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected3, result3);
DefaultContinuousAnimationState result4 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected4 = new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected4, result4);
DefaultContinuousAnimationState result5 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected5 = new DefaultContinuousAnimationState(1, TimeSpan.get(3610000L, 3670000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected5, result5);
}
/**
* Test some
* {@link DefaultContinuousAnimationPlan#determineNextState(DefaultContinuousAnimationState)}
* results that are common amongst some different end behaviors.
*
* @param plan The plan.
*/
private void testDetermineNextStateCommon2(DefaultContinuousAnimationPlan plan)
{
DefaultContinuousAnimationState result9 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected9 = new DefaultContinuousAnimationState(1, TimeSpan.get(7130000L, 7190000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected9, result9);
DefaultContinuousAnimationState result10 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3610000L, 3670000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected10 = new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected10, result10);
DefaultContinuousAnimationState result11 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected11 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected11, result11);
DefaultContinuousAnimationState result12 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(10000L, 70000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected12 = new DefaultContinuousAnimationState(0, TimeSpan.get(0L, 60000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected12, result12);
}
/**
* Test some
* {@link DefaultContinuousAnimationPlan#determineNextState(DefaultContinuousAnimationState)}
* results that are common amongst some different end behaviors.
*
* @param plan The plan.
*/
private void testDetermineNextStateCommon3(DefaultContinuousAnimationPlan plan)
{
DefaultContinuousAnimationState result9 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected9 = new DefaultContinuousAnimationState(1, TimeSpan.get(4730000L, 4790000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected9, result9);
DefaultContinuousAnimationState result10 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3610000L, 3670000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected10 = new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected10, result10);
DefaultContinuousAnimationState result11 = plan.determineNextState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected11 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected11, result11);
DefaultContinuousAnimationState result12 = plan.determineNextState(
new DefaultContinuousAnimationState(0, TimeSpan.get(1810000L, 1870000L), AnimationState.Direction.BACKWARD));
DefaultAnimationState expected12 = new DefaultContinuousAnimationState(0, TimeSpan.get(1800000L, 1860000L),
AnimationState.Direction.BACKWARD);
Assert.assertEquals(expected12, result12);
}
/**
* Test some
* {@link DefaultContinuousAnimationPlan#determinePreviousState(DefaultContinuousAnimationState)}
* results that are common amongst some different end behaviors.
*
* @param plan The plan.
*/
private void testDeterminePreviousStateCommon(DefaultContinuousAnimationPlan plan)
{
DefaultContinuousAnimationState result2 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected2 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected2, result2);
DefaultContinuousAnimationState result3 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3610000L, 3670000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected3 = new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected3, result3);
DefaultContinuousAnimationState result4 = plan.determinePreviousState(
new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected4 = new DefaultContinuousAnimationState(0, TimeSpan.get(3530000L, 3590000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected4, result4);
DefaultContinuousAnimationState result5 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(3600000L, 3660000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected5 = new DefaultContinuousAnimationState(0, TimeSpan.get(3540000L, 3600000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected5, result5);
}
/**
* Test some
* {@link DefaultContinuousAnimationPlan#determinePreviousState(DefaultContinuousAnimationState)}
* results that are common amongst some different end behaviors.
*
* @param plan The plan.
*/
private void testDeterminePreviousStateCommon1(DefaultContinuousAnimationPlan plan)
{
testDeterminePreviousStateCommon(plan);
DefaultContinuousAnimationState result6 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4730000L, 4790000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(1, TimeSpan.get(4720000L, 4780000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result6);
DefaultContinuousAnimationState result7 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(4740000L, 4800000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected8 = new DefaultContinuousAnimationState(1, TimeSpan.get(4730000L, 4790000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected8, result7);
}
/**
* Test some
* {@link DefaultContinuousAnimationPlan#determinePreviousState(DefaultContinuousAnimationState)}
* results that are common amongst some different end behaviors.
*
* @param plan The plan.
*/
private void testDeterminePreviousStateCommon2(DefaultContinuousAnimationPlan plan)
{
testDeterminePreviousStateCommon(plan);
DefaultContinuousAnimationState result6 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7130000L, 7190000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected7 = new DefaultContinuousAnimationState(1, TimeSpan.get(7120000L, 7180000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected7, result6);
DefaultContinuousAnimationState result7 = plan.determinePreviousState(
new DefaultContinuousAnimationState(1, TimeSpan.get(7140000L, 7200000L), AnimationState.Direction.FORWARD));
DefaultAnimationState expected8 = new DefaultContinuousAnimationState(1, TimeSpan.get(7130000L, 7190000L),
AnimationState.Direction.FORWARD);
Assert.assertEquals(expected8, result7);
}
}
|
#Load required packages
library("caret")
#Load dataset
data <- read.csv("data.csv")
#Define training control
train_control <- trainControl(method="cv", number=10)
#Build the model
model <- train(target ~., data=data, method="glm",
trControl=train_control, family="binomial")
#Print the model
print(model) |
function maxOfThree(a, b, c) {
let max = Math.max(a, b, c);
return max;
} |
xcrun stapler staple "Effekseer.dmg" |
#!/bin/bash
xsp --port 8088 --applications /MainsoftWebApp:./ --nonstop & |
#!/usr/bin/env bash
#
# This script installs a go project.
# The project also contains a checklist to adapt it to your need.
# Launch the script a second time to delete unnecessary files.
#
# This script should be called updated, please read it before you launch it !
# $ curl -sSL github.com/bytemare/gotemplate/ ... | sh [name of your project]
#
# Verify options and mode
# - project name
# - was this script used in default mode or being launched in already downloaded directory
# Define requirements
required_programs="git go"
required_min_go_version="1.11"
template="gotemplate"
new_project=$1
# Check arguments
check_args() {
echo "> Verifying arguments ..."
if [ -z "$new_project" ]; then
echo "Error : no name given for new project."
exit 1
fi
}
# Verify if required programs are installed
# - git, go
check_progs() {
echo "> Verifying required programs ..."
for req in $required_programs; do
if ! [ -x "$(command -v git)" ]; then
printf 'Error : %s is not installed.\n' "$req"
exit 1
fi
done
}
# Verify go environment
check_go_env() {
echo "> Verifying environment ..."
if [ -x "$(command -v go)" ]; then
# Check if GOPATH is set
if [ -z "${GOPATH}" ]; then
printf 'Error : Go is installed but GOPATH is not set.\n'
exit 1
fi
# Check if min version is installed by default
current_version=$(go version | cut -d ' ' -f3 | cut -c 3-)
if ! [ "$(printf '%s\n' "$required_min_go_version" "$current_version" | sort -V | head -n1)" = "$required_min_go_version" ]; then
printf 'Error : minimal required Go version is %s (go command is %s)\n' "%required_min_go_version" "%current_version"
exit 1
fi
else
echo 'Error: go is not installed.' >&2
exit 1
fi
}
# Download template
download_template() {
echo "> Cloning template ..."
git clone --depth=1 https://github.com/bytemare/gotemplate.git "$new_project" 2>/dev/null
}
# Delete existing .git folder
delete_git() {
rm -rf .git 2>/dev/null || true
}
# Insert project name where due
inject_project_name() {
echo "> Inject Project name ..."
find . -type f -exec sed -i "s/$template/$new_project/g" {} +
}
# Insert username where due
inject_username() {
echo "todo : inject username where necessary"
}
# Inject new script and delete self
inject_username() {
echo "todo : ask for git username"
}
# Delete unnecessary files
cleanup() {
echo "> Cleaning up ..."
files="gotemplate.go gotemplate_test.go go.mod go.sum LICENSE"
for file in $files; do
rm "$file" 2>/dev/null || true
done
}
# Initialise go modules
init_go_mod() {
go mod init 2>/dev/null
}
# Initialise a new repo
new_git() {
echo "> Setting up new git ..."
git init 1>/dev/null
git add -A 1>/dev/null
git commit -m "initial setup" 1>/dev/null
}
err() {
echo "Aborting."
exit 1
}
trap 'err' ERR
# Bring everything together
main() {
# Check stuff
check_args && check_progs && check_go_env || err
# Download stuff
download_template || err
# Move into project
cd "$new_project" || err
# Adapt stuff
delete_git
inject_project_name
# Clean up stuff
cleanup
# Set up stuff
echo "> Setup new project ..."
init_go_mod
# new_git
# Close
echo "> Success."
}
main |
<filename>tests/ext/plugins/Patcher Test/index.js
module.exports = (Plugin, Api, Vendor) => {
const { Logger, ReactComponents, Patcher, monkeyPatch } = Api;
return class extends Plugin {
onStart() {
this.patchMessage();
return true;
}
async patchMessage() {
const Message = await ReactComponents.getComponent('Message');
monkeyPatch(Message.component.prototype).after('render', e => {
Logger.log('MESSAGE RENDER!', e);
});
}
onStop() {
// The automatic unpatcher is not there yet
Patcher.unpatchAll();
return true;
}
}
};
|
'use strict';
var util = require('../util/util');
var Evented = require('../util/evented');
var Source = require('./source');
var normalizeURL = require('../util/mapbox').normalizeTileURL;
module.exports = VectorTileSource;
function VectorTileSource(options) {
util.extend(this, util.pick(options, ['url', 'tileSize']));
this._options = util.extend({ type: 'vector' }, options);
if (this.tileSize !== 512) {
throw new Error('vector tile sources must have a tileSize of 512');
}
Source._loadTileJSON.call(this, options);
}
VectorTileSource.prototype = util.inherit(Evented, {
minzoom: 0,
maxzoom: 22,
tileSize: 512,
reparseOverscaled: true,
_loaded: false,
isTileClipped: true,
onAdd: function(map) {
this.map = map;
},
loaded: function() {
return this._pyramid && this._pyramid.loaded();
},
update: function(transform) {
if (this._pyramid) {
this._pyramid.update(this.used, transform);
}
},
reload: function() {
if (this._pyramid) {
this._pyramid.reload();
}
},
serialize: function() {
return util.extend({}, this._options);
},
getVisibleCoordinates: Source._getVisibleCoordinates,
getTile: Source._getTile,
queryRenderedFeatures: Source._queryRenderedVectorFeatures,
querySourceFeatures: Source._querySourceFeatures,
_loadTile: function(tile) {
var overscaling = tile.coord.z > this.maxzoom ? Math.pow(2, tile.coord.z - this.maxzoom) : 1;
var params = {
url: normalizeURL(tile.coord.url(this.tiles, this.maxzoom), this.url),
uid: tile.uid,
coord: tile.coord,
zoom: tile.coord.z,
tileSize: this.tileSize * overscaling,
source: this.id,
overscaling: overscaling,
angle: this.map.transform.angle,
pitch: this.map.transform.pitch,
showCollisionBoxes: this.map.showCollisionBoxes
};
if (tile.workerID) {
params.rawTileData = tile.rawTileData;
this.dispatcher.send('reload tile', params, this._tileLoaded.bind(this, tile), tile.workerID);
} else {
tile.workerID = this.dispatcher.send('load tile', params, this._tileLoaded.bind(this, tile));
}
},
_tileLoaded: function(tile, err, data) {
if (tile.aborted)
return;
if (err) {
tile.errored = true;
this.fire('tile.error', {tile: tile, error: err});
return;
}
tile.loadVectorData(data, this.map.style);
if (tile.redoWhenDone) {
tile.redoWhenDone = false;
tile.redoPlacement(this);
}
this.fire('tile.load', {tile: tile});
this.fire('tile.stats', data.bucketStats);
},
_abortTile: function(tile) {
tile.aborted = true;
this.dispatcher.send('abort tile', { uid: tile.uid, source: this.id }, null, tile.workerID);
},
_addTile: function(tile) {
this.fire('tile.add', {tile: tile});
},
_removeTile: function(tile) {
this.fire('tile.remove', {tile: tile});
},
_unloadTile: function(tile) {
tile.unloadVectorData(this.map.painter);
this.dispatcher.send('remove tile', { uid: tile.uid, source: this.id }, null, tile.workerID);
},
redoPlacement: Source.redoPlacement,
_redoTilePlacement: function(tile) {
tile.redoPlacement(this);
}
});
|
const BaseEmbed = require("../../modules/BaseEmbed");
const { getGuildById, parseMessage } = require("../../utils/functions");
module.exports = {
name: "guildMemberAdd",
async execute(bot, member) {
if (!member.guild.me.hasPermission("MANAGE_WEBHOOKS")) return;
const guild = await getGuildById(member.guild.id);
const welcomeData = guild?.welcome_data;
if (!welcomeData.enabled) return;
if (welcomeData.channel_id) {
if (!member.guild.channels.cache.find((ch) => ch.id === welcomeData.channel_id)) return;
const avatar = member.user.displayAvatarURL({ dynamic: true });
const embed = new BaseEmbed({ author: member.user })
.setTitle(`Welcome to **${member.guild.name}**`)
.setThumbnail(avatar)
.setDescription(
parseMessage(guild.welcome_message, member.user, {
author: member.user,
guild: member.guild,
})
);
bot.channels.cache.get(welcomeData.channel_id).send(embed);
}
if (welcomeData.role_id) {
if (!member.guild.me.hasPermission("MANAGE_ROLES")) return;
member.roles.add(welcomeData.role_id);
}
},
};
|
<filename>db/migrate/20170204005149_move_user_website_to_profile_link_site.rb
class MoveUserWebsiteToProfileLinkSite < ActiveRecord::Migration
def change
User.where.not(website: nil).find_each do |user|
ProfileLink.create(
url: user.website.split(' ').first,
profile_link_site_id: 29,
user_id: user.id
)
end
remove_column :users, :website
end
end
|
<filename>src/lib/wifi_telemetry_source_wpa.cxx
#include <iostream>
#include <sstream>
#include <stdexcept>
#include "wifi-telemetry/wifi/wifi_80211_format_mac.hpp"
#include "wifi-telemetry/wifi_telemetry_source_wpa.hpp"
#include "wifi-telemetry/wpa/wpa_commands.hpp"
#include "wifi_telemetry_trace_dpp.hpp"
#include "wifi_telemetry_trace_station.hpp"
WifiTelemetrySourceWpa::WifiTelemetrySourceWpa(const std::optional<WifiInterfaceConfiguration>& interface) :
WifiTelemetrySource(interface, "wpa")
{
if (!interface.has_value())
throw new std::invalid_argument("WifiTelemetrySourceWpa requires interface configuration, but none was supplied");
}
WifiTelemetrySourceWpa::~WifiTelemetrySourceWpa(void)
{
if (m_controller) {
m_controller->unregister_for_events(m_event_token);
m_controller = nullptr;
}
}
int
WifiTelemetrySourceWpa::activate(const std::shared_ptr<WifiTelemetrySourceActivationArgs> /* args */)
{
WpaType type = WpaInterfaceInfo::TypeFromOperationalMode(m_interface->operational_mode);
m_controller = std::make_unique<WpaController>(m_interface->name, type);
m_event_token = m_controller->register_for_events(weak_from_this());
return 0;
}
void
WifiTelemetrySourceWpa::deactivate(void)
{
m_controller = nullptr;
}
bool
WifiTelemetrySourceWpa::trace_station(void) const
{
return (m_interface->operational_mode == WifiOperationalMode::Station);
}
bool
WifiTelemetrySourceWpa::trace_ap(void) const
{
return (m_interface->operational_mode == WifiOperationalMode::AccessPoint);
}
bool
WifiTelemetrySourceWpa::trace_dpp_enrollee(void) const
{
// right now, assume all enrollees are wifi stations.
return trace_station();
}
bool
WifiTelemetrySourceWpa::trace_dpp_configurator(void) const
{
// right now, assume all configurators are wifi access points.
return trace_ap();
}
bool
WifiTelemetrySourceWpa::trace_dpp(void) const
{
return trace_dpp_enrollee() || trace_dpp_configurator();
}
bool
WifiTelemetrySourceWpa::is_dpp_exchange_in_progress(void) const
{
return (m_dpp_exchange != nullptr);
}
void
WifiTelemetrySourceWpa::on_disconnected(const WpaEventArgs<WpaEventDisconnected>& args)
{
if (!trace_station())
return;
const auto& event = args.data();
std::string bssid = wifi_80211_mac_to_string(event.bssid);
trace_station_connection_drop(
m_interface->name.c_str(),
bssid.c_str(),
uint16_t(event.reason_code),
event.locally_generated);
}
void
WifiTelemetrySourceWpa::complete_connection_attempt(const WifiTelemetryInputStationConnectionAttempt& input)
{
trace_station_connection_attempt(m_interface->name.c_str(), &input);
}
void
WifiTelemetrySourceWpa::on_connected(const WpaEventArgs<WpaEventConnected>& args)
{
if (!trace_station())
return;
const auto& event = args.data();
struct WpaCommandSignalPoll signal_poll{};
auto response_signal_poll = m_controller->send_command<WpaCommandSignalPollResponse>(signal_poll);
if (!response_signal_poll) {
std::cerr << "unable to obtain signal poll data" << std::endl;
return;
}
struct WpaCommandStatus command_status{};
auto response_status = m_controller->send_command<WpaCommandStatusResponse>(command_status);
if (!response_status) {
std::cerr << "unable to obtain interface status data" << std::endl;
return;
}
auto connection_attempt_data = WifiTelemetryInputStationConnectionAttempt::succeeded(
event.bssid,
response_signal_poll,
response_status);
complete_connection_attempt(connection_attempt_data);
}
void
WifiTelemetrySourceWpa::on_association_rejected(const WpaEventArgs<WpaEventAssociationRejected>& args)
{
if (!trace_station())
return;
const auto& event = args.data();
auto connection_attempt_data = WifiTelemetryInputStationConnectionAttempt::association_rejected(
event.bssid,
event.status_code);
complete_connection_attempt(connection_attempt_data);
}
void
WifiTelemetrySourceWpa::on_authentication_rejected(const WpaEventArgs<WpaEventAuthenticationRejected>& args)
{
if (!trace_station())
return;
const auto& event = args.data();
auto connection_attempt_data = WifiTelemetryInputStationConnectionAttempt::authentication_rejected(
event.bssid,
event.status_code,
event.authentication_type);
complete_connection_attempt(connection_attempt_data);
}
void
WifiTelemetrySourceWpa::on_network_not_found(const WpaEventArgs<WpaEventNetworkNotFound>& /* args */)
{
if (!trace_station())
return;
auto connection_attempt_data = WifiTelemetryInputStationConnectionAttempt::network_not_found();
complete_connection_attempt(connection_attempt_data);
}
void
WifiTelemetrySourceWpa::complete_dpp_exchange_enrollee(std::shared_ptr<WifiDppExchangeEnrollee>& enrollee)
{
enrollee->stop();
std::vector<uint32_t> chirp_frequencies(enrollee->chirp_frequencies.begin(), enrollee->chirp_frequencies.end());
uint64_t duration_milliseconds = enrollee->duration.has_value()
? static_cast<uint64_t>(enrollee->duration->count())
: 0;
trace_dpp_exchange_enrollee(
m_interface->name.c_str(),
WifiDppRoleToString(enrollee->role),
WifiDppExchangeEnrolleeStateToString(enrollee->state),
duration_milliseconds,
chirp_frequencies.size(),
chirp_frequencies.data(),
WifiDppFailureTypeToString(enrollee->failure_type),
enrollee->failure_details.value_or("").c_str());
m_dpp_exchange.reset();
}
void
WifiTelemetrySourceWpa::complete_dpp_exchange_configurator(std::shared_ptr<WifiDppExchangeConfigurator>& configurator)
{
configurator->stop();
std::string bssid = wifi_80211_mac_to_string(configurator->peer_bssid);
uint64_t duration_milliseconds = configurator->duration.has_value()
? static_cast<uint64_t>(configurator->duration->count())
: 0;
trace_dpp_exchange_configurator(
m_interface->name.c_str(),
WifiDppRoleToString(configurator->role),
WifiDppExchangeConfiguratorStateToString(configurator->state),
duration_milliseconds,
bssid.c_str(),
configurator->frequency,
WifiDppFailureTypeToString(configurator->failure_type),
configurator->failure_details.value_or("").c_str());
m_dpp_exchange.reset();
}
void
WifiTelemetrySourceWpa::on_dpp_chirp_received(const WpaEventArgs<WpaEventDppChirpReceived>& args)
{
if (!trace_dpp_configurator())
return;
const auto& event = args.data();
// configurator doesn't know about this device yet (id == -1), or another exchange in progress.
if (event.id == -1 || is_dpp_exchange_in_progress())
return;
m_dpp_exchange = std::make_shared<WifiDppExchangeConfigurator>(event.id, event.bssid, event.frequency, WifiDppRole::Initiator);
}
void
WifiTelemetrySourceWpa::on_dpp_authentication_init_failure(const WpaEventArgs<WpaEventDppAuthenticationInitFailure>& args)
{
if (!trace_dpp() || !is_dpp_exchange_in_progress())
return;
const auto& event = args.data();
m_dpp_exchange->failure_type = event.failure_type;
m_dpp_exchange->failure_details = event.failure_details;
switch (m_dpp_exchange->device_role) {
case WifiDppDeviceRole::Enrollee: {
auto enrollee = resolve_dpp_exchange<WifiDppExchangeEnrollee>();
enrollee->state = WifiDppExchangeEnrolleeState::Terminated;
complete_dpp_exchange_enrollee(enrollee);
break;
}
case WifiDppDeviceRole::Configurator: {
auto configurator = resolve_dpp_exchange<WifiDppExchangeConfigurator>();
configurator->state = WifiDppExchangeConfiguratorState::Terminated;
complete_dpp_exchange_configurator(configurator);
break;
}
default:
return;
}
}
void
WifiTelemetrySourceWpa::on_dpp_authentication_succeeded(const WpaEventArgs<WpaEventDppAuthenticationSucceeded>& /* args */)
{
if (!trace_dpp() || !is_dpp_exchange_in_progress())
return;
switch (m_dpp_exchange->device_role) {
case WifiDppDeviceRole::Enrollee: {
auto enrollee = resolve_dpp_exchange<WifiDppExchangeEnrollee>();
enrollee->state = WifiDppExchangeEnrolleeState::Authenticated;
break;
}
case WifiDppDeviceRole::Configurator: {
auto configurator = resolve_dpp_exchange<WifiDppExchangeConfigurator>();
configurator->state = WifiDppExchangeConfiguratorState::Authenticated;
break;
}
default:
return;
}
}
void
WifiTelemetrySourceWpa::on_dpp_configuration_received(const WpaEventArgs<WpaEventDppConfigurationReceived>& /* args */)
{
if (!trace_dpp_enrollee() || !is_dpp_exchange_in_progress())
return;
if (m_dpp_exchange->device_role != WifiDppDeviceRole::Enrollee)
return;
auto enrollee = resolve_dpp_exchange<WifiDppExchangeEnrollee>();
enrollee->state = WifiDppExchangeEnrolleeState::Provisioned;
complete_dpp_exchange_enrollee(enrollee);
}
void
WifiTelemetrySourceWpa::on_dpp_configuration_sent(const WpaEventArgs<WpaEventDppConfigurationSent>& /* args */)
{
if (!trace_dpp_configurator() || !is_dpp_exchange_in_progress())
return;
if (m_dpp_exchange->device_role != WifiDppDeviceRole::Configurator)
return;
auto configurator = resolve_dpp_exchange<WifiDppExchangeConfigurator>();
configurator->state = WifiDppExchangeConfiguratorState::Finished;
complete_dpp_exchange_configurator(configurator);
}
void
WifiTelemetrySourceWpa::on_dpp_failure(const WpaEventArgs<WpaEventDppFailure>& args)
{
if (!trace_dpp() || !is_dpp_exchange_in_progress())
return;
const auto& event = args.data();
m_dpp_exchange->failure_type = event.failure_type;
m_dpp_exchange->failure_details = event.failure_details;
switch (m_dpp_exchange->device_role) {
case WifiDppDeviceRole::Enrollee: {
auto enrollee = resolve_dpp_exchange<WifiDppExchangeEnrollee>();
enrollee->state = WifiDppExchangeEnrolleeState::Terminated;
complete_dpp_exchange_enrollee(enrollee);
break;
}
case WifiDppDeviceRole::Configurator: {
auto configurator = resolve_dpp_exchange<WifiDppExchangeConfigurator>();
configurator->state = WifiDppExchangeConfiguratorState::Terminated;
complete_dpp_exchange_configurator(configurator);
break;
}
default:
return;
}
}
void
WifiTelemetrySourceWpa::on_dpp_frame_transmit_status(const WpaEventArgs<WpaEventDppFrameTransmitStatus>& args)
{
if (!trace_dpp_enrollee())
return;
const auto& event = args.data();
bool is_success = (event.status == "SUCCESS");
bool is_broadcast = is_wifi80211_broadcast_address(event.destination_bssid);
if (is_broadcast) { // this indicates a chirp
if (!is_dpp_exchange_in_progress())
m_dpp_exchange = std::make_shared<WifiDppExchangeEnrollee>(WifiDppRole::Responder);
auto enrollee = resolve_dpp_exchange<WifiDppExchangeEnrollee>();
if (is_success)
enrollee->chirp_frequencies.insert(event.frequency);
}
}
|
<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : api.py
# @Author : cgDeepLearn
# @Create Date : 2020/11/16-3:40 下午
import datetime
import random
class TestApi(object):
def __init__(self, req_data):
self.req_data = req_data
def process(self):
"""
处理返回
"""
results = [-1, 0, 1]
res = {
'timestamp': datetime.datetime.now().timestamp(),
'result': random.choice(results)
}
return res
|
<gh_stars>1-10
exports.User = require('./user.model'); |
<filename>src/org/hadatac/hasneto/loader/MetadataContext.java
package org.hadatac.hasneto.loader;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class MetadataContext {
String username = null;
String password = <PASSWORD>;
String kbURL = null;
// For local use:
// - http://localhost:7574/solr
// For remote use:
// - http://jeffersontest.tw.rpi.edu/solr4
boolean verbose = false;
public MetadataContext(String un, String pwd, String kb, boolean ver) {
System.out.println("Metadata management set for knowledge base at " + kb);
username = un;
password = <PASSWORD>;
kbURL = kb;
verbose = ver;
}
private String executeQuery(String query) throws IllegalStateException, IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
//Scanner in = null;
try {
HttpClient client = new DefaultHttpClient();
//System.out.println("Query: <" + kbURL + "/store/sparql?q=" + query + ">");
HttpGet request = new HttpGet(kbURL + "/store/sparql?q=" + URLEncoder.encode(query, "UTF-8"));
request.setHeader("Accept", "application/sparql-results+xml");
HttpResponse response = client.execute(request);
StringWriter writer = new StringWriter();
IOUtils.copy(response.getEntity().getContent(), writer, "utf-8");
return writer.toString();
} finally
{
//in.close();
//request.close();
}
}// /executeQuery()
public Long totalTriples() {
String query = "SELECT (COUNT(*) as ?tot) WHERE { ?s ?p ?o . }";
try {
String result = executeQuery(query);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(result));
Document doc = builder.parse(is);
//System.out.println(result);
return Long.valueOf(doc.getElementsByTagName("literal").item(0).getTextContent()).longValue();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return (long) -1;
}
}
private void executeCommand(String[] command) {
try {
Runtime rt = Runtime.getRuntime();
Process proc1 = rt.exec(command);
InputStream stderr = proc1.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
//System.out.println("<ERROR>");
if (verbose) {
while ( (line = br.readLine()) != null)
System.out.println(line);
}
//System.out.println("</ERROR>");
int exitVal = proc1.waitFor();
System.out.print(" exit value: [" + exitVal + "] ");
//System.out.println(" Process: [" + command[0] + "] exitValue: [" + exitVal + "]");
} catch (Throwable t) {
t.printStackTrace();
}
}
public void clean() {
System.out.println(" Triples before [clean]: " + totalTriples());
// ATTENTION: For now, it erases entirely the content of the metadata collection
String query1 = "<delete><query>*:*</query></delete>";
String query2 = "<commit/>";
String url1;
String url2;
try {
url1 = kbURL + "/store/update?stream.body=" + URLEncoder.encode(query1, "UTF-8");
url2 = kbURL + "/store/update?stream.body=" + URLEncoder.encode(query2, "UTF-8");
//Runtime.getRuntime().exec("curl -v " + url1);
//Runtime.getRuntime().exec("curl -v " + url2);
String[] cmd1 = {"curl", "-v", url1};
System.out.print(" Erasing triples... ");
executeCommand(cmd1);
System.out.println("");
System.out.print(" Committing... ");
String[] cmd2 = {"curl", "-v", url2};
executeCommand(cmd2);
System.out.println("");
System.out.println(" Triples after [clean]: " + totalTriples());
} catch (UnsupportedEncodingException e) {
System.out.println("[MetadataManagement] - ERROR conding URLs");
//e.printStackTrace();
}
}
/*
* contentType correspond to the mime type required for curl to process the data provided. For example, application/rdf+xml is
* used to process rdf/xml content.
*
*/
public Long loadLocalFile(String filePath, String contentType) {
//System.out.println("File: " + filePath + " Content Type: " + contentType);
Long total = totalTriples();
if (verbose) {
System.out.println("curl -v " + kbURL + "/store/update/bulk?commit=true -H \"Content-Type: " + contentType + "\" --data-binary @" + filePath);
}
String[] cmd = {"curl", "-v", kbURL + "/store/update/bulk?commit=true","-H", "Content-Type: " + contentType, "--data-binary", "@" + filePath};
executeCommand(cmd);
Long newTotal = totalTriples();
return (newTotal - total);
}
public void loadOntologies() {
Long total = totalTriples();
System.out.println(" Triples before [loadOntologies]: " + total);
NameSpaces.getInstance().copyNameSpacesLocally();
for (Map.Entry<String, NameSpace> entry : NameSpaces.table.entrySet()) {
String abbrev = entry.getKey().toString();
String nsURL = entry.getValue().getURL();
if ((abbrev != null) && (nsURL != null) && (entry.getValue().getType() != null) && !nsURL.equals("")) {
String filePath = "copy" + "-" + abbrev.replace(":","");
System.out.print(" Uploading " + filePath);
for (int i = filePath.length(); i < 30; i++) {
System.out.print(" ");
}
loadLocalFile(filePath, entry.getValue().getType());
Long newTotal = totalTriples();
System.out.println(" Added " + (newTotal - total) + " triples.");
total = newTotal;
}
}
System.out.println(" Triples after [loadOntologies]: " + totalTriples());
}
}
|
def dump_person(person, rel_map, member_cache, dumped_people, person_file)
p_id = person.id.to_s
if !person.authority_member.blank?
if !dumped_people.include?(p_id)
dumped_people << p_id
auth_member = person.authority_member
mem_ids = person.members.map(&:hbx_member_id)
json_data = {
:id => person.id.to_s,
:hbx_id => auth_member.hbx_member_id,
:first_name => person.name_first,
:last_name => person.name_last,
:dob => auth_member.dob,
:gender => auth_member.gender,
:addresses => [],
:phones => [],
:emails => [],
:person_relationships => []
}
if !person.name_pfx.blank?
json_data[:name_pfx] = person.name_pfx
end
if !person.name_sfx.blank?
json_data[:name_sfx] = person.name_sfx
end
if !person.name_middle.blank?
json_data[:middle_name] = person.name_middle
end
if !(["999999999", "000000000"].include?(auth_member.ssn))
if !auth_member.ssn.blank?
json_data[:ssn] = auth_member.ssn
end
end
person.emails.each do |email|
json_data[:emails] << {
:kind => email.email_type,
:address => email.email_address
}
end
person.phones.each do |phone|
if !phone.phone_number.blank?
if (phone.phone_number.length == 10)
json_data[:phones] << {
:kind => phone.phone_type,
:full_phone_number => phone.phone_number
}
end
end
end
person.addresses.each do |address|
address_data = {
:kind => address.address_type,
:address_1 => address.address_1,
:city => address.city,
:state => address.state,
:zip => address.zip
}
if !address.address_2.blank?
address_data[:address_2] = address.address_2
end
json_data[:addresses] << address_data
end
relationships = []
mem_ids.each do |m_id|
rel_map[m_id].each do |rel|
member_rel_id = member_cache.lookup(rel[:member_id]).id.to_s
relationships << {
:kind => rel[:kind],
:relative_id => member_rel_id
}
end
end
relationships.uniq.each do |rel|
json_data[:person_relationships] << rel
end
person_file.puts JSON.dump(json_data)
person_file.puts ","
end
end
end
policy_blacklist = [
"200247",
"65835",
"44481",
"49278"
]
pols = Policy.where("$or" => [{
:enrollees => {"$elemMatch" => {
:rel_code => "self",
:coverage_start => {"$gt" => Date.new(2014,12,31)}
}}, :employer_id => nil},
{:enrollees => {"$elemMatch" => {
:rel_code => "self",
:coverage_start => {"$gt" => Date.new(2014,6,30)}
}}, :employer_id => {"$ne" => nil}}
])
member_ids = []
relationship_map = Hash.new do |hash,key|
hash[key] = Array.new
end
all_subscribers = []
pols.each do |pol|
if !policy_blacklist.include?(pol.eg_id)
if !pol.canceled?
sub_id = pol.subscriber.m_id
all_subscribers << sub_id
pol.enrollees.each do |en|
if !en.canceled?
member_ids << en.m_id
if (en.m_id != sub_id)
if !en.canceled?
relationship_map[sub_id] << {
:kind => en.rel_code,
:member_id => en.m_id
}
end
end
end
end
end
end
end
# raise relationship_map.inspect
people_file = File.open("people.json", 'w')
families_file = File.open("heads_of_families.json", 'w')
member_ids.uniq!
m_cache = Caches::MemberIdPerson.new(member_ids)
people = Person.find_for_members(member_ids)
dumped_peeps = []
people_file.puts "["
people.each do |person|
dump_person(person, relationship_map, m_cache, dumped_peeps, people_file)
end
families_file.puts(
JSON.dump(all_subscribers.map do |sub_id|
m_cache.lookup(sub_id).id.to_s
end)
)
families_file.close
people_file.close
|
<gh_stars>0
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { datafeedsProvider } from './datafeeds';
import { jobsProvider } from './jobs';
import { groupsProvider } from './groups';
import { newJobCapsProvider } from './new_job_caps';
import { newJobChartsProvider, categorizationExamplesProvider } from './new_job';
export function jobServiceProvider(callWithRequest, request) {
return {
...datafeedsProvider(callWithRequest),
...jobsProvider(callWithRequest),
...groupsProvider(callWithRequest),
...newJobCapsProvider(callWithRequest, request),
...newJobChartsProvider(callWithRequest, request),
...categorizationExamplesProvider(callWithRequest, request),
};
}
|
#!/bin/bash
echo "angry"
time ./svm_learn_directory.sh ../Data/Tweet-New-Data/06-24/Obamney-Labeled-Polarities/angry.mat/part-00000 ../Data/Twitter/Processed/Polarity ../Data/Twitter/Learned_Labels/matlab_out_angry
echo "happy"
time ./svm_learn_directory.sh ../Data/Tweet-New-Data/06-24/Obamney-Labeled-Polarities/happy.mat/part-00000 ../Data/Twitter/Processed/Polarity ../Data/Twitter/Learned_Labels/matlab_out_happy
echo "sad"
time ./svm_learn_directory.sh ../Data/Tweet-New-Data/06-24/Obamney-Labeled-Polarities/sad.mat/part-00000 ../Data/Twitter/Processed/Polarity ../Data/Twitter/Learned_Labels/matlab_out_sad
echo "mocking"
time ./svm_learn_directory.sh ../Data/Tweet-New-Data/06-24/Obamney-Labeled-Polarities/mocking.mat/part-00000 ../Data/Twitter/Processed/Polarity ../Data/Twitter/Learned_Labels/matlab_out_mocking
echo "none"
time ./svm_learn_directory.sh ../Data/Tweet-New-Data/06-24/Obamney-Labeled-Polarities/none.mat/part-00000 ../Data/Twitter/Processed/Polarity ../Data/Twitter/Learned_Labels/matlab_out_none
echo "hopeful"
time ./svm_learn_directory.sh ../Data/Tweet-New-Data/06-24/Obamney-Labeled-Polarities/hopeful.mat/part-00000 ../Data/Twitter/Processed/Polarity ../Data/Twitter/Learned_Labels/matlab_out_hopeful
echo "funny"
time ./svm_learn_directory.sh ../Data/Tweet-New-Data/06-24/Obamney-Labeled-Polarities/funny.mat/part-00000 ../Data/Twitter/Processed/Polarity ../Data/Twitter/Learned_Labels/matlab_out_funny
|
#!/bin/bash
echo ============================================================================
echo Deploying fabric8 website
echo ============================================================================
cd website && \
npm install -g gitbook-cli && \
npm install && \
mvn clean && \
mkdir -p target && \
cd target && \
git clone -b gh-pages git@github.com:fabric8io/fabric8.git sitegen && \
cd .. && \
mvn scalate:sitegen && \
mkdir -p target/sitegen/guide && \
gitbook install ../docs && \
gitbook build ../docs && \
echo "copying generated gitbook"
cp -rv ../docs/_book/* target/sitegen/guide && \
cd target/sitegen && \
git add * guide/* && \
git commit -m "generated website" && \
git push
#gitbook install ../docs --output=target/sitegen/guide && \
echo ============================================================================
echo Deployed fabric8 website
echo ============================================================================
|
<gh_stars>0
import React from 'react'
import * as DC from '../Constants'
function changesCell(CNodeId, sessionId, changeItem) {
return <li key={"ci" + sessionId + '_' + CNodeId.toString() + "_" + changeItem.type}>
<span><b>{changeItem.type}</b>
{(changeItem.label !== '') ? ': ' : ''}<font color="#d8d8d8"> {changeItem.label}</font></span>
</li>
}
function resultCell(CNodeId, sessionId, cnodeState, adminSessions) {
var changes = [];
var combineId, combineCatId, moveCatId;
if (cnodeState.correction === DC.CORRECTION_DELETE) {
changes.push({
type: DC.CORRECTION_DELETE_TXT,
label: ''
});
return <td className="delphi-diagnosis-results-table"><ul>
{changes.map(c => changesCell(CNodeId, sessionId, c))}
</ul></td>
}
if (cnodeState.corrcombine !== 0) {
combineId = cnodeState.corrcombine;
combineCatId = Math.floor(combineId / 10000);
if ((combineId in global.DM_LEVELCNODES) && (combineCatId in global.DM_LEVELBFULLNAMES)) {
changes.push({
type: DC.CORRECTION_COMBINE_TXT,
label: global.DM_LEVELBFULLNAMES[combineCatId] + ' - ' + global.DM_LEVELCNODES[combineId].name
});
} else {
changes.push({
type: DC.CORRECTION_COMBINE_TXT,
label: DC.CORRECTION_COMBINE_USER_DEFINED_TXT
});
}
return <td className="delphi-diagnosis-results-table"><ul>
{changes.map(c => changesCell(CNodeId, sessionId, c))}
</ul></td>
}
if (cnodeState.corrnewname !== '') {
changes.push({
type: DC.CORRECTION_NEWNAME_TXT,
label: cnodeState.corrnewname
});
} else {
if (cnodeState.corrspelling !== '') {
changes.push({
type: DC.CORRECTION_SPELLING_TXT,
label: cnodeState.corrspelling
});
}
}
if ((cnodeState.correction === DC.CORRECTION_DELBOTH) ||
(cnodeState.correction === DC.CORRECTION_DELSYNS)) {
changes.push({
type: DC.CORRECTION_DELSYNS_TXT,
label: ''
});
}
if (cnodeState.correditsyns !== '') {
changes.push({
type: DC.CORRECTION_EDITSYNS_TXT,
label: cnodeState.correditsyns.split(';').join(', ')
});
}
if (cnodeState.corrnewsyns !== '') {
changes.push({
type: DC.CORRECTION_NEWSYNS_TXT,
label: cnodeState.corrnewsyns.split(';').join(', ')
});
}
if ((cnodeState.correction === DC.CORRECTION_DELBOTH) ||
(cnodeState.correction === DC.CORRECTION_DELMODS)) {
changes.push({
type: DC.CORRECTION_DELMODS_TXT,
label: ''
});
}
if (cnodeState.correditmods !== '') {
changes.push({
type: DC.CORRECTION_EDITMODS_TXT,
label: cnodeState.correditmods.split(';').join(', ')
});
}
if (cnodeState.corrnewmods !== '') {
changes.push({
type: DC.CORRECTION_NEWMODS_TXT,
label: cnodeState.corrnewmods.split(';').join(', ')
});
}
if (cnodeState.corrmoveto !== 0) {
moveCatId = cnodeState.corrmoveto;
if (moveCatId in global.DM_LEVELBFULLNAMES) {
changes.push({
type: DC.CORRECTION_MOVECAT_TXT,
label: global.DM_LEVELBFULLNAMES[moveCatId]
});
} else {
var moveCatA = '', moveCatB = '', cc;
if (sessionId in adminSessions) {
const adminSession = adminSessions[sessionId];
for (cc = 0; cc < adminSession['newBs'].length; cc++) {
if (adminSession['newBs'][cc]['id'] === moveCatId) {
moveCatB = adminSession['newBs'][cc]['name'];
if (moveCatId < 300) {
moveCatA = global.DM_LEVELANAMES[Math.floor(moveCatId / 100)]
} else {
var moveSCatId = Math.floor(moveCatId / 100);
for (cc = 0; cc < adminSession['newAs'].length; cc++) {
if (adminSession['newAs'][cc]['id'] === moveSCatId) {
moveCatA = adminSession['newAs'][cc]['name'];
break;
}
}
}
if (moveCatA === '') {
moveCatA = DC.CORRECTION_MOVECAT_SCAT_UNKNOWN;
}
break;
}
}
} else {
moveCatA = DC.CORRECTION_MOVECAT_SCAT_UNKNOWN;
moveCatB = DC.CORRECTION_MOVECAT_USER;
}
changes.push({
type: DC.CORRECTION_MOVECAT_TXT,
label: moveCatA + ' - ' + moveCatB + DC.CORRECTION_MOVECAT_USER
});
}
}
if (cnodeState.corrother !== '') {
changes.push({
type: DC.CORRECTION_OTHER_TXT,
label: cnodeState.corrother
});
}
return <td className="delphi-diagnosis-results-table"><ul>
{changes.map(c => changesCell(CNodeId, sessionId, c))}
</ul></td>
}
function resultRow(CNodeId, adminSubBlock, adminSessions) {
var sessionId = adminSubBlock.sessionId;
if (!(CNodeId in adminSubBlock.block)) {
return <tr className="delphi-diagnosis-results-table" key={'cr' + adminSubBlock.sessionId + '_' + CNodeId.toString()}>
<td className="delphi-diagnosis-results-table">{adminSubBlock.sessionId}</td>
<td className="delphi-diagnosis-results-table">{DC.TXT_RESULTS_PENDING}</td>
<td></td>
</tr>
}
const cnodeState = adminSubBlock.block[CNodeId];
return <tr className="delphi-diagnosis-results-table" key={'cr' + adminSubBlock.sessionId + '_' + CNodeId.toString()}>
<td className="delphi-diagnosis-results-table">{adminSubBlock.sessionId}</td>
<td className="delphi-diagnosis-results-table">{(!!cnodeState.correct) ? DC.TXT_RESULTS_APPROVE :
(cnodeState.correction === DC.CORRECTION_NONE) ? DC.TXT_RESULTS_PENDING :
DC.TXT_RESULTS_CORRECTED}</td>
{(!cnodeState.correct && cnodeState.correction !== DC.CORRECTION_NONE) ?
resultCell(CNodeId, sessionId, cnodeState, adminSessions) : <td></td>}
</tr>
}
// this function performs a series of mangling steps
export default function DiagnosisResults(CNodeId, adminBlock, adminSessions) {
if (adminBlock === null || adminBlock === undefined || adminBlock.length === 0) {
return <div className="delphi-diagnosis-results">{DC.TXT_RESULTS_NORESULTS}</div>
}
return <div className="delphi-diagnosis-results">
<table className="delphi-diagnosis-results-table"><tbody>
<tr className="delphi-diagnosis-results-table" key="000000">
<td className="delphi-diagnosis-results-table" colSpan="3">{adminBlock.length.toString() + DC.TXT_RESULTS_NUMRATERS}</td>
</tr>
<tr className="delphi-diagnosis-results-table" key="000001">
<th className="delphi-diagnosis-results-table">{DC.TXT_RESULTS_RATERID}</th>
<th className="delphi-diagnosis-results-table">{DC.TXT_RESULTS_STATUS}</th>
<th className="delphi-diagnosis-results-table" width="320">{DC.TXT_RESULTS_CORRECTIONS}</th>
</tr>
{adminBlock.map(b => resultRow(CNodeId, b, adminSessions))}
</tbody></table>
</div>;
}
|
/*
*
*/
package net.community.chest.ui.helpers.label;
import net.community.chest.awt.CursorTypeValueStringInstantiator;
import net.community.chest.convert.ValueStringInstantiator;
import net.community.chest.swing.component.label.JLabelReflectiveProxy;
/**
* <P>Copyright 2008 as per GPLv2</P>
*
* @param <H> The reflected {@link JHyperlink} instance
* @author <NAME>.
* @since Nov 12, 2008 1:17:01 PM
*/
public class JHyperlinkReflectiveProxy<H extends JHyperlink> extends JLabelReflectiveProxy<H> {
public JHyperlinkReflectiveProxy (Class<H> objClass) throws IllegalArgumentException
{
this(objClass, false);
}
protected JHyperlinkReflectiveProxy (Class<H> objClass, boolean registerAsDefault)
throws IllegalArgumentException, IllegalStateException
{
super(objClass, registerAsDefault);
}
/*
* @see net.community.chest.swing.component.label.JLabelReflectiveProxy#resolveAttributeInstantiator(java.lang.String, java.lang.Class)
*/
@SuppressWarnings("unchecked")
@Override
protected <C> ValueStringInstantiator<C> resolveAttributeInstantiator (String name, Class<C> type) throws Exception
{
if ("HoverCursorType".equalsIgnoreCase(name))
return (ValueStringInstantiator<C>) CursorTypeValueStringInstantiator.DEFAULT;
return super.resolveAttributeInstantiator(name, type);
}
public static final JHyperlinkReflectiveProxy<JHyperlink> HYPERLINK=
new JHyperlinkReflectiveProxy<JHyperlink>(JHyperlink.class, true);
}
|
package org.synaptra.mlib;
public class BootstrapAggregation {
}
|
package net.sansa_stack.query.spark.ontop
import java.nio.file.{Files, Path}
import com.twitter.chill.{KryoBase, KryoPool, ScalaKryoInstantiator}
import net.sansa_stack.rdf.common.partition.core.RdfPartitionStateDefault
/**
* @author <NAME>
*/
object PartitionSerDe {
val kryo: KryoBase = {
val instantiator = new ScalaKryoInstantiator()
instantiator.setRegistrationRequired(true)
instantiator.newKryo
}
kryo.register(classOf[RdfPartitionStateDefault])
kryo.register(classOf[scala.collection.immutable.Set[_]])
kryo.register(classOf[scala.collection.immutable.Set[RdfPartitionStateDefault]])
val pool: KryoPool = KryoPool.withByteArrayOutputStream(4, new ScalaKryoInstantiator())
// val kryo = new Kryo
//
// kryo.setRegistrationRequired(false)
// kryo.setInstantiatorStrategy(new StdInstantiatorStrategy());
// kryo.register(classOf[RdfPartitionDefault])
// kryo.register(classOf[scala.collection.immutable.Set[_]])
// kryo.register(classOf[scala.collection.immutable.Set[RdfPartitionDefault]])
def serialize[T](t: T): Array[Byte] =
ScalaKryoInstantiator.defaultPool.toBytesWithClass(t)
def deserialize[T](bytes: Array[Byte]): T =
ScalaKryoInstantiator.defaultPool.fromBytes(bytes).asInstanceOf[T]
def rt[T](t: T): T = deserialize(serialize(t))
def serializeTo(partitions: Set[RdfPartitionStateDefault], path: Path): Unit = {
val bytes = serialize(partitions)
Files.write(path, bytes)
}
def deserializeFrom(path: Path): Set[RdfPartitionStateDefault] = {
val bytes = Files.readAllBytes(path)
deserialize(bytes)
}
}
|
#!/usr/bin/env bash
#
# Copyright (c) 2019-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
export LC_ALL=C.UTF-8
# The root dir.
# The ci system copies this folder.
# This is where the depends build is done.
BASE_ROOT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )"/../../ >/dev/null 2>&1 && pwd )
export BASE_ROOT_DIR
echo "Setting specific values in env"
if [ -n "${FILE_ENV}" ]; then
set -o errexit;
# shellcheck disable=SC1090
source "${FILE_ENV}"
fi
echo "Fallback to default values in env (if not yet set)"
# The number of parallel jobs to pass down to make and test_runner.py
export MAKEJOBS=${MAKEJOBS:--j4}
# A folder for the ci system to put temporary files (ccache, datadirs for tests, ...)
# This folder only exists on the ci host.
export BASE_SCRATCH_DIR=${BASE_SCRATCH_DIR:-$BASE_ROOT_DIR/ci/scratch}
# What host to compile for. See also ./depends/README.md
# Tests that need cross-compilation export the appropriate HOST.
# Tests that run natively guess the host
export HOST=${HOST:-$("$BASE_ROOT_DIR/depends/config.guess")}
# Whether to prefer BusyBox over GNU utilities
export USE_BUSY_BOX=${USE_BUSY_BOX:-false}
export RUN_UNIT_TESTS=${RUN_UNIT_TESTS:-true}
export RUN_FUNCTIONAL_TESTS=${RUN_FUNCTIONAL_TESTS:-true}
export DOCKER_NAME_TAG=${DOCKER_NAME_TAG:-ubuntu:18.04}
# Randomize test order.
# See https://www.boost.org/doc/libs/1_71_0/libs/test/doc/html/boost_test/utf_reference/rt_param_reference/random.html
export BOOST_TEST_RANDOM=${BOOST_TEST_RANDOM:-1}
export CCACHE_TEMPDIR=${CCACHE_TEMPDIR:-/tmp/.ccache-temp}
export CCACHE_COMPRESS=${CCACHE_COMPRESS:-1}
# The cache dir.
# This folder exists on the ci host and ci guest. Changes are propagated back and forth.
export CCACHE_DIR=${CCACHE_DIR:-$BASE_SCRATCH_DIR/.ccache}
# The depends dir.
# This folder exists on the ci host and ci guest. Changes are propagated back and forth.
export DEPENDS_DIR=${DEPENDS_DIR:-$BASE_ROOT_DIR/depends}
# Folder where the build result is put (bin and lib).
export BASE_OUTDIR=${BASE_OUTDIR:-$BASE_SCRATCH_DIR/out/$HOST}
# Folder where the build is done (dist and out-of-tree build).
export BASE_BUILD_DIR=${BASE_BUILD_DIR:-$BASE_SCRATCH_DIR/build}
export PREVIOUS_RELEASES_DIR=${PREVIOUS_RELEASES_DIR:-$BASE_ROOT_DIR/releases/$HOST}
export DOCKER_PACKAGES=${DOCKER_PACKAGES:-build-essential libtool autotools-dev automake pkg-config bsdmainutils curl ca-certificates ccache python3 rsync git}
export GOAL=${GOAL:-install}
export PATH=${BASE_ROOT_DIR}/ci/retry:$PATH
export CI_RETRY_EXE=${CI_RETRY_EXE:retry}
export NO_DEPENDS=${NO_DEPENDS:-1}
export NO_WERROR=${NO_WERROR:-1}
export ARTIFACT_NAME=${ARTIFACT_NAME:-""}
export RELEASE_ARTIFACT_NAME=${RELEASE_ARTIFACT_NAME:-""}
|
package main
import "testing"
func TestServe(t *testing.T) {
want := "<NAME>"
if got := Serve(); got != want {
t.Errorf("Hello() = %q, want %q", got, want)
}
}
|
def merge(list1, list2):
mergedList = []
i = 0
j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
mergedList.append(list1[i])
i += 1
else:
mergedList.append(list2[j])
j += 1
mergedList += list1[i:]
mergedList += list2[j:]
return mergedList
# Driver Code
list1 = [1, 3, 5]
list2 = [2, 4, 6]
print(merge(list1, list2)) |
#!/usr/bin/env bash
BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
for file in vimrc zshrc tmux.conf; do
ln -s "${BASEDIR}/$file" ~/.$file
done
ln -s "${BASEDIR}/vscode/keybindings.json" ~/.config/Code/User/keybindings.json
ln -s "${BASEDIR}/vscode/settings.json" ~/.config/Code/User/settings.json
git clone --depth 1 https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
git clone --depth 1 https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
|
<reponame>nehararora/dotdotdot
# -*- coding: utf-8 -*-
"""
config: Load application configuration and return an object representation.
Allows accessing configuration using "dot-notation" for supported configuration
file formats.
Supported formats are:
* yml
* TODO: ini
* TODO: json
"""
import yaml
# from enum import Enum
# Formats = Enum('Formats', names=[('yml', 1), ('ini', 2)])
def repr_fx(self):
"""
Object representation. Function gets added as a method
to generated classes.
:return: string object representation
"""
return yaml.dump(self)
def str_fx(self):
"""
String representation. Function gets added as a method
to generated classes.
:return: string object representation
"""
return yaml.dump(self, default_flow_style=False)
def get_fx(self, key, default=None):
"""
Allow for c.get(foo) invocation.
:param self: Config object
:param key: config key to look for
:param default: value if key is missing
:return:
"""
key_exists = hasattr(self, key)
if key_exists:
return get_item_fx(self, key)
elif default:
return default
else:
raise KeyError
def get_item_fx(self, key):
"""
Function to implement __getitem__
:param self:
:param key:
:return:
"""
if hasattr(self, key):
return getattr(self, key)
else:
raise KeyError
def __validate():
"""
Hook to validate config.
:return:
"""
# TODO: implement
def __determine_config_type():
"""
Find out the type of the configuration file.
:return:
"""
class Config(object):
"""
The configuration object that will be populated.
"""
pass
Config.__repr__ = repr_fx
Config.__str__ = str_fx
Config.__getitem__ = get_item_fx
Config.get = get_fx
def __construct(config, yml):
"""
Recursive function to construct an object corresponding to given value.
Adds elements from the input yaml to the configuration object in the first
argument. For complex value types recursively instantiates new objects and
attaches them into the configuration tree.
The intent is to be able to access the yaml config using dot notation -
e.g. config.a.b.c.
:param config: The config object to populate.
:param yml: The yaml corresponding to the conf parameter.
"""
for key in yml:
if type(yml[key]) == dict:
# create an object for the subsection
klass = type(key, (), {})
klass.__repr__ = repr_fx
klass.__str__ = str_fx
klass.__getitem__ = get_item_fx
klass.get = get_fx
obj = klass()
__construct(obj, yml[key])
setattr(config, key, obj)
else:
# just set simple value
setattr(config, key, yml[key])
def load(paths):
"""
Entry point for the config module.
Load yml config files at specified path and convert to a config object.
Merges the yaml files specified by the paths parameter - keys in a file
later in the list override earlier keys.
:param paths: List of complete paths of config files.
:return Config object with member properties
"""
if not paths:
raise ConfigException(message='No configuration file specified',
reason=paths)
yaml_dict = {}
if type(paths) == str:
paths = [paths]
# for every filename in list...
for path in paths:
# read config file...
with open(path) as f:
# get config as dict...
y = yaml.safe_load(f)
# and merge into a single yaml dict.
yaml_dict.update(y)
config = Config()
# get object for each key and set on the config object
__construct(config, yaml_dict)
return config
class ConfigException(Exception):
def __init__(self, message, reason):
self.message = message
self.reason = reason
def __str__(self):
return repr(self.message)
|
#!/bin/bash
cd ../../
if [ "$1" == "--clean" ]
then
echo "Running clean..."
flutter clean
else
echo "Skipping clean..."
fi
if [ "$1" == "--apk" ]
then
echo "Building APK..."
flutter build apk --release
else
echo "Building AAB..."
flutter build appbundle --release
fi |
const jsonString = '{"name": "John","age": 30,"password": "123456"}';
const parsed = JSON.parse(jsonString);
console.log(parsed);
// {name: "John", age: 30, password: "123456"} |
<filename>files/tests/managers/test_nfs.py<gh_stars>100-1000
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import os
from mock import MagicMock
from django.test import TestCase
from files.managers.nfs import HostNFSManager
from files.exceptions import InvalidOperationError
class HostNFSManagerTestCase(TestCase):
def setUp(self):
self.location = "location_token"
self.server_location = "/server_location_token"
def test_init(self):
manager = HostNFSManager(location=self.location, server_location=self.server_location)
self.assertEqual(manager.location, self.location)
self.assertEqual(manager.server_location, self.server_location)
def test_save__with_shims(self):
manager = HostNFSManager(location=self.location, server_location=self.server_location)
file_name = "file_name_token"
content = "content_token"
shims = "shims_token"
uid = "uid_token"
ip = "1.1.1.1"
manager._uniqid = MagicMock(return_value=uid)
manager._get_host_ip = MagicMock(return_value=ip)
manager.storage = MagicMock()
tag = manager.save(name=file_name, content=content, shims=shims)
manager.storage.save.assert_called_once_with(
name=os.path.join(manager.location, shims, uid, file_name), content=content, max_length=None
)
self.assertEqual(tag, {"type": "host_nfs", "tags": {"uid": uid, "shims": shims, "name": file_name}})
def test_save__without_shims(self):
manager = HostNFSManager(location=self.location, server_location=self.server_location)
file_name = "file_name_token"
content = "content_token"
uid = "uid_token"
ip = "1.1.1.1"
manager._uniqid = MagicMock(return_value=uid)
manager._get_host_ip = MagicMock(return_value=ip)
manager.storage = MagicMock()
tag = manager.save(name=file_name, content=content)
manager.storage.save.assert_called_once_with(
name=os.path.join(manager.location, uid, file_name), content=content, max_length=None
)
self.assertEqual(tag, {"type": "host_nfs", "tags": {"uid": uid, "shims": None, "name": file_name}})
def test_push_files_to_ips__success_with_callback_url(self):
bk_biz_id = "bk_biz_id_token"
file_tags = [
{"type": "host_nfs", "tags": {"uid": "uid_1", "shims": "shims_1", "name": "file_1"}},
{"type": "host_nfs", "tags": {"uid": "uid_2", "shims": "shims_2", "name": "file_2"}},
{"type": "host_nfs", "tags": {"uid": "uid_3", "shims": "shims_3", "name": "file_3"}},
]
target_path = "/user/data"
ips = "ips_token"
account = "account_token"
callback_url = "callback_url_token"
host_ip = "1.1.1.1"
job_id = "12345"
esb_client = MagicMock()
esb_client.job.fast_push_file = MagicMock(return_value={"result": True, "data": {"job_instance_id": job_id}})
manager = HostNFSManager(location=self.location, server_location=self.server_location)
manager._get_host_ip = MagicMock(return_value=host_ip)
result = manager.push_files_to_ips(
esb_client=esb_client,
bk_biz_id=bk_biz_id,
file_tags=file_tags,
target_path=target_path,
ips=ips,
account=account,
callback_url=callback_url,
)
esb_client.job.fast_push_file.assert_called_once_with(
{
"bk_biz_id": bk_biz_id,
"account": account,
"file_target_path": target_path,
"file_source": [
{
"files": [
os.path.join("/server_location_token", "shims_1", "uid_1", "file_1"),
os.path.join("/server_location_token", "shims_2", "uid_2", "file_2"),
os.path.join("/server_location_token", "shims_3", "uid_3", "file_3"),
],
"account": "root",
"ip_list": [{"bk_cloud_id": 0, "ip": host_ip}],
}
],
"ip_list": ips,
"bk_callback_url": callback_url,
}
)
self.assertEqual(result, {"result": True, "data": {"job_id": job_id}})
def test_push_files_to_ips__success_no_callback_url(self):
bk_biz_id = "bk_biz_id_token"
file_tags = [
{"type": "host_nfs", "tags": {"uid": "uid_1", "shims": "shims_1", "name": "file_1"}},
{"type": "host_nfs", "tags": {"uid": "uid_2", "shims": "shims_2", "name": "file_2"}},
{"type": "host_nfs", "tags": {"uid": "uid_3", "shims": "shims_3", "name": "file_3"}},
]
target_path = "/user/data"
ips = "ips_token"
account = "account_token"
host_ip = "1.1.1.1"
job_id = "12345"
esb_client = MagicMock()
esb_client.job.fast_push_file = MagicMock(return_value={"result": True, "data": {"job_instance_id": job_id}})
manager = HostNFSManager(location=self.location, server_location=self.server_location)
manager._get_host_ip = MagicMock(return_value=host_ip)
result = manager.push_files_to_ips(
esb_client=esb_client,
bk_biz_id=bk_biz_id,
file_tags=file_tags,
target_path=target_path,
ips=ips,
account=account,
)
esb_client.job.fast_push_file.assert_called_once_with(
{
"bk_biz_id": bk_biz_id,
"account": account,
"file_target_path": target_path,
"file_source": [
{
"files": [
os.path.join("/server_location_token", "shims_1", "uid_1", "file_1"),
os.path.join("/server_location_token", "shims_2", "uid_2", "file_2"),
os.path.join("/server_location_token", "shims_3", "uid_3", "file_3"),
],
"account": "root",
"ip_list": [{"bk_cloud_id": 0, "ip": host_ip}],
}
],
"ip_list": ips,
}
)
self.assertEqual(result, {"result": True, "data": {"job_id": job_id}})
def test_push_files_to_ips__with_different_tags(self):
bk_biz_id = "bk_biz_id_token"
file_tags = [
{"type": "host_nfs", "tags": {"uid": "uid_1", "shims": "shims_1", "name": "file_1"}},
{"type": "s3", "tags": {"uid": "uid_2", "shims": "shims_2", "name": "file_2"}},
]
target_path = "/user/data"
ips = "ips_token"
account = "account_token"
esb_client = "esb_client"
manager = HostNFSManager(location=self.location, server_location=self.server_location)
self.assertRaises(
InvalidOperationError,
manager.push_files_to_ips,
esb_client=esb_client,
bk_biz_id=bk_biz_id,
file_tags=file_tags,
target_path=target_path,
ips=ips,
account=account,
)
def test_push_files_to_ips__fail(self):
bk_biz_id = "bk_biz_id_token"
file_tags = [
{"type": "host_nfs", "tags": {"uid": "uid_1", "shims": "shims_1", "name": "file_1"}},
{"type": "host_nfs", "tags": {"uid": "uid_2", "shims": "shims_2", "name": "file_2"}},
{"type": "host_nfs", "tags": {"uid": "uid_3", "shims": "shims_3", "name": "file_3"}},
]
target_path = "/user/data"
ips = "ips_token"
account = "account_token"
host_ip = "1.1.1.1"
esb_client = MagicMock()
esb_client.job.fast_push_file = MagicMock(return_value={"result": False, "message": "msg token"})
manager = HostNFSManager(location=self.location, server_location=self.server_location)
manager._get_host_ip = MagicMock(return_value=host_ip)
result = manager.push_files_to_ips(
esb_client=esb_client,
bk_biz_id=bk_biz_id,
file_tags=file_tags,
target_path=target_path,
ips=ips,
account=account,
)
job_kwargs = {
"bk_biz_id": bk_biz_id,
"account": account,
"file_target_path": target_path,
"file_source": [
{
"files": [
os.path.join("/server_location_token", "shims_1", "uid_1", "file_1"),
os.path.join("/server_location_token", "shims_2", "uid_2", "file_2"),
os.path.join("/server_location_token", "shims_3", "uid_3", "file_3"),
],
"account": "root",
"ip_list": [{"bk_cloud_id": 0, "ip": host_ip}],
}
],
"ip_list": ips,
}
esb_client.job.fast_push_file.assert_called_once_with(job_kwargs)
self.assertEqual(
result,
{
"result": False,
"message": "msg token",
"kwargs": job_kwargs,
"response": {"result": False, "message": "msg token"},
"job_api": "job.fast_push_file",
},
)
|
<reponame>NoMan2000/sql_func_and_procs
SELECT employee_id,customers_for_rep(employee_id)
FROM employees
WHERE customers_for_rep(employee_id)>10
ORDER BY customers_for_rep(employee_id) desc
|
#!/bin/bash
echo 'Starting sentence application as a stack'
# DOCKER_REGISTRY=localhost:5000
# my-registry e my-swarm sono degli alias per swarm-1
DOCKER_SWARM=tcp://my-swarm:2376
# inserisco le chiavi e il certificato dello swarm-1
docker --host ${DOCKER_SWARM} --tlsverify --tlscacert /home/vagrant/.docker/ca.pem --tlscert /home/vagrant/.docker/cert.pem --tlskey /home/vagrant/.docker/key.pem stack deploy --compose-file docker-stack-sentence.yml sentence |
#basedir = '/fastscratch/snarayan/genarrays/v_deepgen_3/'
#figsdir = '/home/snarayan/public_html/figs/deepgen/v3/'
export BASEDIR="/data/t3serv014/snarayan/deep/v_deepgen_4_0p02_small/"
export FIGSDIR='/home/snarayan/public_html/figs/deepgen/v4_grid_compare/'
export MODELDIR="models/"
|
#!/bin/bash
TAG="${TAG:-quay.io/microshift/microshift-aio:$(date +%Y-%m-%d-%H-%M)}"
for img in "registry.access.redhat.com/ubi8/ubi-init:8.4" "docker.io/nvidia/cuda:11.4.2-base-ubi8"; do
echo "build microshift aio image using base image "${i}
tag=$(echo ${img} |awk -F"/" '{print $NF}'| sed -e 's/:/-/g')
echo ${tag}
for host in "rhel7" "rhel8"; do
host_tag=""
[ "${host}" == "rhel7" ] && host_tag="-rhel7"
podman build --build-arg IMAGE_NAME=${img} --build-arg HOST=${host} -t ${TAG}-${tag}${host_tag} .
done
done
|
# -----------------------------------------------------------------------------
#
# Package : middie
# Version : 4.1.0
# Source repo : https://github.com/fastify/middleman
# Tested on : RHEL 8.3
# Script License: Apache License, Version 2 or later
# Maintainer : BulkPackageSearch Automation <sethp@us.ibm.com>
#
# Disclaimer: This script has been tested in root mode on given
# ========== platform using the mentioned version of the package.
# It may not work as expected with newer versions of the
# package and/or distribution. In such case, please
# contact "Maintainer" of this script.
#
# ----------------------------------------------------------------------------
PACKAGE_NAME=middie
PACKAGE_VERSION=4.1.0
PACKAGE_URL=https://github.com/fastify/middleman
yum -y update && yum install -y yum-utils nodejs nodejs-devel nodejs-packaging npm python38 python38-devel ncurses git gcc gcc-c++ libffi libffi-devel ncurses git jq make cmake
yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/8.3Server/ppc64le/appstream/
yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/8.3Server/ppc64le/baseos/
yum-config-manager --add-repo http://rhn.pbm.ihost.com/rhn/latest/7Server/ppc64le/optional/
yum install -y firefox liberation-fonts xdg-utils && npm install n -g && n latest && npm install -g npm@latest && export PATH="$PATH" && npm install --global yarn grunt-bump xo testem acorn
OS_NAME=`python3 -c "os_file_data=open('/etc/os-release').readlines();os_info = [i.replace('PRETTY_NAME=','').strip() for i in os_file_data if i.startswith('PRETTY_NAME')];print(os_info[0])"`
HOME_DIR=`pwd`
if ! git clone $PACKAGE_URL $PACKAGE_NAME; then
echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
echo "$PACKAGE_URL $PACKAGE_NAME" > /home/tester/output/clone_fails
echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Clone_Fails" > /home/tester/output/version_tracker
exit 0
fi
cd $HOME_DIR/$PACKAGE_NAME
git checkout $PACKAGE_VERSION
PACKAGE_VERSION=$(jq -r ".version" package.json)
# run the test command from test.sh
if ! npm install && npm audit fix && npm audit fix --force; then
echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
echo "$PACKAGE_URL $PACKAGE_NAME"
echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Install_Fails"
exit 0
fi
cd $HOME_DIR/$PACKAGE_NAME
if ! npm test; then
echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
echo "$PACKAGE_URL $PACKAGE_NAME"
echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail | Install_success_but_test_Fails"
exit 0
else
echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
echo "$PACKAGE_URL $PACKAGE_NAME"
echo "$PACKAGE_NAME | $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Pass | Both_Install_and_Test_Success"
exit 0
fi |
<filename>private-class-data/src/main/java/com/iluwatar/privateclassdata/Stew.java
package com.iluwatar.privateclassdata;
/**
*
* Mutable stew class
*
*/
public class Stew {
private int numPotatoes;
private int numCarrots;
private int numMeat;
private int numPeppers;
public Stew(int numPotatoes, int numCarrots, int numMeat, int numPeppers) {
this.numPotatoes = numPotatoes;
this.numCarrots = numCarrots;
this.numMeat = numMeat;
this.numPeppers = numPeppers;
}
public void mix() {
System.out.println(String.format(
"Mixing the stew we find: %d potatoes, %d carrots, %d meat and %d peppers", numPotatoes,
numCarrots, numMeat, numPeppers));
}
public void taste() {
System.out.println("Tasting the stew");
if (numPotatoes > 0) {
numPotatoes--;
}
if (numCarrots > 0) {
numCarrots--;
}
if (numMeat > 0) {
numMeat--;
}
if (numPeppers > 0) {
numPeppers--;
}
}
}
|
<gh_stars>0
const isString = require('./../../validator/isString');
function isFileName(val) {
return isString(val) && val.length > 4 && val.length < 250;
}
module.exports = isFileName; |
/*
* For more infos check:
* https://wiki.delphigl.com/index.php/Dual_Quaternion
*/
function DualQuaternion(r, d) {
if(r instanceof Quaternion)
r.normalizeApply();
this.r = r; // Real part
this.d = d; // Dual part
}
DualQuaternion.prototype.fromArray = function(arr) {
this.r = arr[0].normalize();
this.d = arr[1];
return this;
};
DualQuaternion.prototype.asArray = function() {
var arr = [];
arr[0] = this.r;
arr[1] = this.d;
return arr;
};
DualQuaternion.prototype.applyToVector = function(v) {
var p = new DualQuaternion(
new Quaternion(1, 0, 0, 0),
new Quaternion(0, v[0], v[1], v[2])
);
// qpq*
var q = this.normalize();
var q_1 = this.conjugate();
var result = q.multiply(p).multiply(q_1);
v[0] = result.d.i;
v[1] = result.d.j;
v[2] = result.d.k;
return v;
};
// Applies it to the context quaternion
DualQuaternion.prototype.multiplyApply = function(dq) {
var ndq = this._multiply(this, dq);
return this.fromArray(ndq);
};
DualQuaternion.prototype.addApply = function(dq) {
var ndq = this._add(this, dq);
return this.fromArray(ndq);
};
DualQuaternion.prototype.multiply = function(dq) {
var ndq = this._multiply(this, dq);
return (new DualQuaternion()).fromArray(ndq);
};
DualQuaternion.prototype.add = function(dq) {
var ndq = this._add(this, dq);
return (new DualQuaternion()).fromArray(ndq);
};
DualQuaternion.prototype.subtract = function(dq) {
var ndq = this._subtract(this, dq);
return (new DualQuaternion()).fromArray(ndq);
};
DualQuaternion.prototype.conjugate = function() {
var c = this._conjugate(this);
return (new DualQuaternion()).fromArray(c);
};
DualQuaternion.prototype.normalize = function() {
var n = this._normalize(this);
return (new DualQuaternion()).fromArray(n);
};
DualQuaternion.prototype.normalizeApply = function() {
var ndq = this._normalize(this);
return this.fromArray(ndq);
};
DualQuaternion.prototype.isUnit = function() {
// Unshure if correct
var n = this.r.conjugate().multiply(this.d).add(this.d.conjugate().multiply(this.r));
n.normalize();
if(n.a + n.i + n.j + n.k == 0)
return true;
return false;
};
DualQuaternion.prototype.isPure = function() {
};
DualQuaternion.prototype._add = function(dq1, dq2) {
return [
dq1.r.add(dq2.r),
dq1.d.add(dq2.d)
];
};
DualQuaternion.prototype._subtract = function(dq1, dq2) {
return [
dq1.r.subtract(dq2.r),
dq1.d.subtract(dq2.d)
];
};
DualQuaternion.prototype._multiply = function(dq1, dq2) {
return [
dq1.r.multiply(dq2.r),
dq1.r.multiply(dq2.d).add(dq1.d.multiply(dq2.r))
];
};
// Check: http://stackoverflow.com/questions/23174899/properly-normalizing-a-dual-quaternion
DualQuaternion.prototype._normalize = function(dq) {
var magnitude = dq.r.magnitude();
return [
dq.r.multiplyScalar(1 / magnitude),
dq.d.multiplyScalar(1 / magnitude)
]
};
// Check: http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/other/dualQuaternion/functions/index.htm
// Important to take the third conjugate!
DualQuaternion.prototype._conjugate = function(dq) {
return [
dq.r.conjugate(),
dq.d.conjugate().multiplyScalar(-1)
]
}; |
/*
* Copyright 2009-2012 The MyBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.jdbc;
import java.util.ArrayList;
import java.util.List;
public class SelectBuilder {
private static final String AND = ") \nAND (";
private static final String OR = ") \nOR (";
private static final ThreadLocal<SelectSQL> localSQL = new ThreadLocal<SelectSQL>();
public static void BEGIN() {
RESET();
}
public static void RESET() {
localSQL.set(new SelectSQL());
}
public static void SELECT(String columns) {
sql().select.add(columns);
}
public static void SELECT_DISTINCT(String columns) {
sql().distinct = true;
SELECT(columns);
}
public static void FROM(String table) {
sql().from.add(table);
}
public static void JOIN(String join) {
sql().join.add(join);
}
public static void INNER_JOIN(String join) {
sql().innerJoin.add(join);
}
public static void LEFT_OUTER_JOIN(String join) {
sql().leftOuterJoin.add(join);
}
public static void RIGHT_OUTER_JOIN(String join) {
sql().rightOuterJoin.add(join);
}
public static void OUTER_JOIN(String join) {
sql().outerJoin.add(join);
}
public static void WHERE(String conditions) {
sql().where.add(conditions);
sql().lastList = sql().where;
}
public static void OR() {
sql().lastList.add(OR);
}
public static void AND() {
sql().lastList.add(AND);
}
public static void GROUP_BY(String columns) {
sql().groupBy.add(columns);
}
public static void HAVING(String conditions) {
sql().having.add(conditions);
sql().lastList = sql().having;
}
public static void ORDER_BY(String columns) {
sql().orderBy.add(columns);
}
public static String SQL() {
try {
StringBuilder builder = new StringBuilder();
if (sql().distinct) {
selectClause(builder, "SELECT DISTINCT", sql().select, "", "", ", ");
} else {
selectClause(builder, "SELECT", sql().select, "", "", ", ");
}
selectClause(builder, "FROM", sql().from, "", "", ", ");
selectClause(builder, "JOIN", sql().join, "", "", "\nJOIN ");
selectClause(builder, "INNER JOIN", sql().innerJoin, "", "", "\nINNER JOIN ");
selectClause(builder, "OUTER JOIN", sql().outerJoin, "", "", "\nOUTER JOIN ");
selectClause(builder, "LEFT OUTER JOIN", sql().leftOuterJoin, "", "", "\nLEFT OUTER JOIN ");
selectClause(builder, "RIGHT OUTER JOIN", sql().rightOuterJoin, "", "", "\nRIGHT OUTER JOIN ");
selectClause(builder, "WHERE", sql().where, "(", ")", " AND ");
selectClause(builder, "GROUP BY", sql().groupBy, "", "", ", ");
selectClause(builder, "HAVING", sql().having, "(", ")", " AND ");
selectClause(builder, "ORDER BY", sql().orderBy, "", "", ", ");
return builder.toString();
} finally {
RESET();
}
}
private static void selectClause(StringBuilder builder, String keyword, List<String> parts, String open, String close, String conjunction) {
if (!parts.isEmpty()) {
if (builder.length() > 0) builder.append("\n");
builder.append(keyword);
builder.append(" ");
builder.append(open);
String last = "________";
for (int i = 0, n = parts.size(); i < n; i++) {
String part = parts.get(i);
if (i > 0 && !part.equals(AND) && !part.equals(OR) && !last.equals(AND) && !last.equals(OR)) {
builder.append(conjunction);
}
builder.append(part);
last = part;
}
builder.append(close);
}
}
private static SelectSQL sql() {
SelectSQL selectSQL = localSQL.get();
if (selectSQL == null) {
RESET();
selectSQL = localSQL.get();
}
return selectSQL;
}
private static class SelectSQL {
List<String> select = new ArrayList<String>();
List<String> from = new ArrayList<String>();
List<String> join = new ArrayList<String>();
List<String> innerJoin = new ArrayList<String>();
List<String> outerJoin = new ArrayList<String>();
List<String> leftOuterJoin = new ArrayList<String>();
List<String> rightOuterJoin = new ArrayList<String>();
List<String> where = new ArrayList<String>();
List<String> having = new ArrayList<String>();
List<String> groupBy = new ArrayList<String>();
List<String> orderBy = new ArrayList<String>();
List<String> lastList = new ArrayList<String>();
boolean distinct;
}
}
|
function Group(canvas, svg) {
this.svg = svg;
this.canvas = canvas;
if (!this.svg.getAttribute("id")) {
var uuid = Util.newUUID();
this.svg.setAttribute("id", uuid);
}
this.id = this.svg.getAttribute("id");
this.targets = [];
var thiz = this;
Dom.workOn("./svg:g[@p:type]", this.svg, function (node) {
var controller = thiz.canvas.createControllerFor(node);
thiz.targets.push(controller);
});
var propertyGroup = new PropertyGroup();
propertyGroup.name = Util.getMessage("shape.properties.label");
var firstGroups = this.targets[0].getPropertyGroups();
for (g in firstGroups) {
for (p in firstGroups[g].properties) {
var propDef = firstGroups[g].properties[p];
var ok = true;
for (var i = 1; i < this.targets.length; i++) {
var target = this.targets[i];
var propGroups = target.getPropertyGroups();
var found = false;
for (g1 in propGroups) {
for (p1 in propGroups[g1].properties) {
var def = propGroups[g1].properties[p1];
if (propDef.isSimilarTo(def)) {
found = true;
break;
}
}
if (found) break;
}
if (!found) {
ok = false;
break;
}
}
if (!ok) continue;
propertyGroup.properties.push(propDef);
}
}
this.propertyGroup = propertyGroup;
//this.dockingManager = new DockingManager(this);
}
Group.prototype.getName = function () {
return "Group";
};
Group.prototype.isFor = function (svg) {
return this.svg == svg;
};
Group.prototype.getProperties = function () {
var properties = {};
for (var p in this.propertyGroup.properties) {
var name = this.propertyGroup.properties[p].name;
properties[name] = this.getProperty(name);
}
return properties;
};
Group.prototype.getPropertyGroups = function () {
return [this.propertyGroup];
};
Group.prototype.setProperty = function (name, value) {
for (t in this.targets) {
this.targets[t].setProperty(name, value);
}
};
Group.prototype.getProperty = function (name) {
if (name == "box") return null;
var firstValue = this.targets[0].getProperty(name);
//TODO: add additonal info to indicate sameness
return firstValue;
// if (!firstValue) return null;
// var same = true;
// for (var i = 1; i < this.targets.length; i ++) {
// var target = this.targets[i];
// var value = target.getProperty(name);
//
// if (value == null) return null;
// if (firstValue.toString() != value.toString()) {
// same = false;
// break;
// }
// }
//
// return same ? firstValue : null;
};
Group.prototype.setMetadata = function (name, value) {
return Util.setNodeMetadata(this.svg, name, value);
};
Group.prototype.getMetadata = function (name) {
return Util.getNodeMetadata(this.svg, name);
};
//new imple for geometry editing
Group.prototype.moveBy = function (dx, dy, targetSet, moving) {
var matrix = this.svg.ownerSVGElement.createSVGTransform().matrix;
matrix = matrix.translate(dx, dy);
var ctm = this.svg.getTransformToElement(this.svg.parentNode);
matrix = matrix.multiply(ctm);
Svg.ensureCTM(this.svg, matrix);
//if (Config.get("docking.enabled")) {
// this.dockingManager.handleMoveBy(dx, dy, targetSet, moving);
//}
};
Group.getSizingOriginalInfo = function (node) {
return {
gw0: Util.getCustomNumberProperty(node, "sizing-gow", 1),
gh0: Util.getCustomNumberProperty(node, "sizing-goh", 1),
w0: Util.getCustomNumberProperty(node, "sizing-ow", 1),
h0: Util.getCustomNumberProperty(node, "sizing-oh", 1),
x0: Util.getCustomNumberProperty(node, "sizing-ox", 0),
y0: Util.getCustomNumberProperty(node, "sizing-oy", 0)
};
};
Group.prototype.scaleTo_noPolicy = function (nw, nh, group) {
var geo = this.getGeometry();
var dw = nw / geo.dim.w;
var dh = nh / geo.dim.h;
for (t in this.targets) {
var target = this.targets[t];
var bounding = target.getBounding(this.svg);
var newX = bounding.x * dw;
var newY = bounding.y * dh;
var targetGeo = target.getGeometry();
var newW = targetGeo.dim.w * dw;
var newH = targetGeo.dim.h * dh;
bounding = target.getBounding(this.svg);
target.moveBy(newX - bounding.x, newY - bounding.y, true);
target.scaleTo(newW, newH, true);
}
//if (Config.get("docking.enabled")) {
// this.dockingManager.handleScaleTo(nw, nh, geo.dim.w, geo.dim.h, group);
//}
};
Group.calculateLayout = function (ePos0, eSize0, gSize0, posPolicy, sizePolicy, size, eSize) {
var layout = {};
if (sizePolicy == "relative") {
layout.size = eSize0 * size / gSize0;
} else if (sizePolicy == "start-end") {
var d = gSize0 - ePos0 - eSize0;
layout.size = size - d - ePos0;
} else {
layout.size = eSize;
}
if (posPolicy == "start") {
layout.pos = ePos0;
} else if (posPolicy == "middle") {
layout.pos = (size - layout.size) / 2;
} else if (posPolicy == "relative") {
layout.pos = ePos0 * size / gSize0;
} else {
var d = gSize0 - ePos0 - eSize0;
layout.pos = size - d - layout.size;
}
return layout;
};
Group.prototype.scaleTo = function (nw, nh, group) {
if (!this.svg.getAttributeNS(PencilNamespaces.p, "sizing-gow")) {
this.scaleTo_noPolicy(nw, nh, group);
return;
}
var gi = Group.getSizingOriginalInfo(this.svg);
var geo = this.getGeometry();
for (t in this.targets) {
var target = this.targets[t];
var ei = Group.getSizingOriginalInfo(target.svg);
var policy = Group.getSizingPolicy(target);
var bounding = target.getBounding(this.svg);
var egeo = target.getGeometry();
if (egeo && egeo.dim) {
bounding.width = egeo.dim.w;
bounding.height = egeo.dim.h;
}
var hLayout = Group.calculateLayout(ei.x0, ei.w0, gi.gw0, policy.xPolicy, policy.wPolicy, nw, bounding.width);
var vLayout = Group.calculateLayout(ei.y0, ei.h0, gi.gh0, policy.yPolicy, policy.hPolicy, nh, bounding.height);
target.moveBy(Math.round(hLayout.pos - bounding.x), Math.round(vLayout.pos - bounding.y), true);
target.scaleTo(Math.round(hLayout.size), Math.round(vLayout.size), true);
}
};
Group.prototype.layoutChildren = function () {
var geo = this.getGeometry();
this.scaleTo(geo.dim.w, geo.dim.h);
};
Group.prototype.rotateBy = function (da) {
debug("rotateBy: " + da);
var ctm = this.svg.getTransformToElement(this.svg.parentNode);
var bbox = this.svg.getBBox();
var x = bbox.x + bbox.width / 2;
var y = bbox.y + bbox.height / 2;
center = Svg.pointInCTM(x, y, ctm);
ctm = ctm.translate(x, y);
ctm = ctm.rotate(da);
ctm = ctm.translate(0 - x, 0 - y);
Svg.ensureCTM(this.svg, ctm);
this.invalidateInboundConnections();
this.invalidateOutboundConnections();
//if (Config.get("docking.enabled")) {
// this.dockingManager.handleRotateBy(da);
//}
};
Group.prototype.getBounding = function (to) {
var context = to ? to : this.canvas.drawingLayer;
var ctm = this.svg.getTransformToElement(context);
var bbox = this.svg.getBBox();
var p = Svg.pointInCTM(bbox.x, bbox.y, ctm);
var rect = {
x: p.x,
y: p.y,
width: 0,
height: 0
};
Svg.expandRectTo(rect, Svg.pointInCTM(bbox.x + bbox.width, bbox.y, ctm));
Svg.expandRectTo(rect, Svg.pointInCTM(bbox.x + bbox.width, bbox.y + bbox.height, ctm));
Svg.expandRectTo(rect, Svg.pointInCTM(bbox.x, bbox.y + bbox.height, ctm));
return rect;
};
Group.prototype.supportScaling = function () {
return true;
};
Group.prototype.ungroup = function () {
var nodes = [];
for (t in this.targets) {
var target = this.targets[t];
var node = target.svg;
var ctm = target.svg.getTransformToElement(this.canvas.drawingLayer);
node.parentNode.removeChild(node);
this.canvas.drawingLayer.appendChild(node);
Svg.ensureCTM(node, ctm);
nodes.push(node);
}
this.canvas.drawingLayer.removeChild(this.svg);
return nodes;
};
//~new impl
Group.TRANSLATE_REGEX = /^translate\(([\-0-9]+)\,([\-0-9]+)\)$/
Group.prototype.getGeometry = function () {
var geo = new Geometry();
geo.ctm = this.svg.getTransformToElement(this.canvas.drawingLayer);
geo.dim = {};
var bbox = this.svg.getBBox();
geo.dim.w = bbox.width;
geo.dim.h = bbox.height;
geo.loc = {x: bbox.x, y: bbox.y};
return geo;
};
Group.prototype.getBoundingRect = function () {
var rect = null;
var thiz = this;
for (t in this.targets) {
var childRect = this.targets[t].getBoundingRect();
rect = rect ? Svg.joinRect(rect, childRect) : childRect;
}
return rect;
};
Group.prototype.setGeometry = function (geo) {
var thiz = this;
for (t in this.targets) {
var childRect = this.targets[t].getBoundingRect();
//TODO: impl. this
}
};
Group.prototype.moveByx = function (x, y, zoomAware) {
var thiz = this;
for (t in this.targets) {
this.targets[t].moveBy(x, y, zoomAware ? true : false);
}
};
Group.prototype.setPositionSnapshot = function () {
/*
var ctm = this.svg.getTransformToElement(this.canvas.drawingLayer);
this.svg.transform.baseVal.consolidate();
var translate = this.svg.ownerSVGElement.createSVGMatrix();
translate.e = 0;
translate.f = 0;
translate = this.svg.transform.baseVal.createSVGTransformFromMatrix(translate);
this.svg.transform.baseVal.appendItem(translate);
*/
this._pSnapshot = {lastDX: 0, lastDY: 0};
};
Group.prototype.moveFromSnapshot = function (dx, dy, dontNormalize, targetSet) {
/*
var v = Svg.vectorInCTM({x: dx, y: dy},
this._pSnapshot.ctm,
true);
var snap = Config.get("edit.snap.grid", true);
if (!dontNormalize && snap) {
var grid = Pencil.getGridSize();
newX = Util.gridNormalize(v.x + this._pSnapshot.x, grid.w);
newY = Util.gridNormalize(v.y + this._pSnapshot.y, grid.h);
v.x = newX - this._pSnapshot.x;
v.y = newY - this._pSnapshot.y;
}
this._pSnapshot.translate.matrix.e = v.x;
this._pSnapshot.translate.matrix.f = v.y;
*/
this.moveBy(dx - this._pSnapshot.lastDX, dy - this._pSnapshot.lastDY, targetSet);
this._pSnapshot.lastDX = dx;
this._pSnapshot.lastDY = dy;
};
Group.prototype.clearPositionSnapshot = function () {
/*
delete this._pSnapshot;
this._pSnapshot = null;
this.svg.transform.baseVal.consolidate();
*/
this._pSnapshot = {lastDX: 0, lastDY: 0};
};
Group.prototype.deleteTarget = function () {
this.canvas.snappingHelper.updateSnappingGuide(this, true);
//this.dockingManager.deleteTarget();
this.svg.parentNode.removeChild(this.svg);
};
Group.prototype.bringForward = function () {
try {
var next = this.svg.nextSibling;
if (next) {
var parentNode = this.svg.parentNode;
parentNode.removeChild(this.svg);
var next2 = next.nextSibling;
if (next2) {
parentNode.insertBefore(this.svg, next2);
} else {
parentNode.appendChild(this.svg);
}
//this.dockingManager.invalidateChildTargets();
}
} catch (e) { alert(e); }
};
Group.prototype.bringToFront = function () {
try {
var next = this.svg.nextSibling;
if (next) {
var parentNode = this.svg.parentNode;
parentNode.removeChild(this.svg);
parentNode.appendChild(this.svg);
//this.dockingManager.invalidateChildTargets();
}
} catch (e) { alert(e); }
};
Group.prototype.sendBackward = function () {
try {
var previous = this.svg.previousSibling;
if (previous) {
var parentNode = this.svg.parentNode;
parentNode.removeChild(this.svg);
parentNode.insertBefore(this.svg, previous);
//this.dockingManager.invalidateChildTargets();
}
} catch (e) { alert(e); }
};
Group.prototype.sendToBack = function () {
try {
var previous = this.svg.previousSibling;
if (previous) {
var parentNode = this.svg.parentNode;
parentNode.removeChild(this.svg);
parentNode.insertBefore(this.svg, parentNode.firstChild);
//this.dockingManager.invalidateChildTargets();
}
} catch (e) { alert(e); }
};
Group.prototype.getTextEditingInfo = function () {
var info = null;
return info;
};
Group.prototype.createTransferableData = function () {
return {type: ShapeXferHelper.MIME_TYPE,
isSVG: true,
dataNode: this.svg.cloneNode(true)
};
};
Group.prototype.lock = function () {
this.svg.setAttributeNS(PencilNamespaces.p, "p:locked", "true");
};
Group.prototype.markAsMoving = function (moving) {
//this.dockingManager.moving = moving;
Svg.optimizeSpeed(this.svg, moving);
};
Group.prototype.getSnappingGuide = function () {
var b = this.getBounding();
var vertical = [];
var horizontal = [];
vertical.push(new SnappingData("Left", b.x, "Left", true, this.id, false, b.y, b.y + b.height));
vertical.push(new SnappingData("VCenter", b.x + b.width/2, "VCenter", true, this.id, false, b.y, b.y + b.height));
vertical.push(new SnappingData("Right", b.x + b.width, "Right", true, this.id, false, b.y, b.y + b.height));
horizontal.push(new SnappingData("Top", b.y, "Top", false, this.id, false, b.x, b.x + b.width));
horizontal.push(new SnappingData("HCenter", b.y + b.height/2, "HCenter", false, this.id, false, b.x, b.x + b.width));
horizontal.push(new SnappingData("Bottom", b.y + b.height, "Bottom", false, this.id, false, b.x, b.x + b.width));
return {
vertical: vertical, horizontal: horizontal
};
};
Group.prototype.invalidateInboundConnections = function () {
for (t in this.targets) {
this.targets[t].invalidateInboundConnections();
}
};
Group.prototype.invalidateOutboundConnections = function () {
for (t in this.targets) {
var target = this.targets[t];
target.invalidateOutboundConnections();
}
};
Group.prototype.processNewGroup = function () {
var geo = this.getGeometry();
Util.setCustomProperty(this.svg, "sizing-gow", geo.dim.w);
Util.setCustomProperty(this.svg, "sizing-goh", geo.dim.h);
for (t in this.targets) {
var target = this.targets[t];
var bounding = target.getBounding(this.svg);
Util.setCustomProperty(target.svg, "sizing-ox", bounding.x);
Util.setCustomProperty(target.svg, "sizing-oy", bounding.y);
var targetGeo = target.getGeometry();
Util.setCustomProperty(target.svg, "sizing-ow", targetGeo.dim.w);
Util.setCustomProperty(target.svg, "sizing-oh", targetGeo.dim.h);
}
};
Group.getSizingPolicy = function (target) {
return {
xPolicy: Util.getCustomProperty(target.svg, "sizing-x-policy", "relative"),
yPolicy: Util.getCustomProperty(target.svg, "sizing-y-policy", "relative"),
wPolicy: Util.getCustomProperty(target.svg, "sizing-w-policy", "relative"),
hPolicy: Util.getCustomProperty(target.svg, "sizing-h-policy", "relative")
}
};
Group.openSizingPolicyDialog = function (target) {
var holder = {
input: Group.getSizingPolicy(target)
};
var dialog = new SizingPolicyDialog();
dialog.open({
holder : holder,
callback: function (valueHolder) {
if (!valueHolder.output) return;
Util.setCustomProperty(target.svg, "sizing-x-policy", valueHolder.output.xPolicy);
Util.setCustomProperty(target.svg, "sizing-y-policy", valueHolder.output.yPolicy);
Util.setCustomProperty(target.svg, "sizing-w-policy", valueHolder.output.wPolicy);
Util.setCustomProperty(target.svg, "sizing-h-policy", valueHolder.output.hPolicy);
}
});
};
|
# ----------------------------------------------------------------------------
#
# Package : pd
# Version : rc3
# Source repo : https://github.com/pingcap/pd
# Tested on : rhel_7.3
# Script License: Apache License, Version 2 or later
# Maintainer : Priya Seth <sethp@us.ibm.com>
#
# Disclaimer: This script has been tested in non-root mode on given
# ========== platform using the mentioned version of the package.
# It may not work as expected with newer versions of the
# package and/or distribution. In such case, please
# contact "Maintainer" of this script.
#
# ----------------------------------------------------------------------------
#!/bin/bash
export GOPATH=$HOME/pd
export PATH=$GOPATH/bin:$PATH
#Install dependency, golang
wget https://storage.googleapis.com/golang/go1.8.1.linux-ppc64le.tar.gz
sudo tar -C /usr/local -xzf go1.8.1.linux-ppc64le.tar.gz
export PATH=$PATH:/usr/local/go/bin
#Clone/get the source
cd $HOME
git clone https://github.com/pingcap/pd.git
cd pd
go get github.com/pingcap/pd
#Build and test
cd $GOPATH/src/github.com/pingcap/pd && make && \
rm -rf vendor && ln -s _vendor/vendor vendor && \
make check && go test $(go list ./...| grep -vE 'vendor|pd-server')
|
module.exports = {
tables: [
{
TableName: `Users`,
KeySchema: [{ AttributeName: "username", KeyType: "HASH" }],
AttributeDefinitions: [
{ AttributeName: "username", AttributeType: "S" }
],
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
},
{
TableName: `Messages`,
KeySchema: [
{ AttributeName: "channelId", KeyType: "HASH" },
{ AttributeName: "insertTime", KeyType: "RANGE" }
],
AttributeDefinitions: [
{ AttributeName: "channelId", AttributeType: "S" },
{ AttributeName: "insertTime", AttributeType: "N" }
],
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
},
{
TableName: `Channel`,
KeySchema: [
{ AttributeName: "channelId", KeyType: "HASH" },
{ AttributeName: "channelName", KeyType: "RANGE" }
],
AttributeDefinitions: [
{ AttributeName: "channelId", AttributeType: "S" },
{ AttributeName: "channelName", AttributeType: "S" }
],
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
},
{
TableName: `UserChannel`,
KeySchema: [
{ AttributeName: "username", KeyType: "HASH" },
{ AttributeName: "channelId", KeyType: "RANGE" }
],
AttributeDefinitions: [
{ AttributeName: "username", AttributeType: "S" },
{ AttributeName: "channelId", AttributeType: "S" }
],
GlobalSecondaryIndexes: [
{
IndexName: "channelId-username-index",
KeySchema: [
{ AttributeName: "channelId", KeyType: "HASH" },
{ AttributeName: "username", KeyType: "RANGE" }
],
Projection: {
ProjectionType: "ALL"
},
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
}
],
ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10 }
},
{
TableName: `Profiles`,
KeySchema: [
{ AttributeName: "username", KeyType: "HASH" }
],
AttributeDefinitions: [
{ AttributeName: "username", AttributeType: "S" }
],
ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10 }
},
{
TableName: `Settings`,
KeySchema: [
{ AttributeName: "username", KeyType: "HASH" }
],
AttributeDefinitions: [
{ AttributeName: "username", AttributeType: "S" }
],
ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10 }
},
{
TableName: `Notifications`,
KeySchema: [
{ AttributeName: "notificationId", KeyType: "HASH" },
{ AttributeName: "insertedTime", KeyType: "RANGE" }
],
AttributeDefinitions: [
{ AttributeName: "notificationId", AttributeType: "S" },
{ AttributeName: "insertedTime", AttributeType: "N" },
{ AttributeName: "channelId", AttributeType: "S" },
{ AttributeName: "username", AttributeType: "S" },
{ AttributeName: "fromFriend", AttributeType: "S" }
],
GlobalSecondaryIndexes: [
{
IndexName: "channelId-insertedTime-index",
KeySchema: [
{ AttributeName: "channelId", KeyType: "HASH" },
{ AttributeName: "insertedTime", KeyType: "RANGE" }
],
Projection: {
ProjectionType: "ALL"
},
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
},
{
IndexName: "username-insertedTime-index",
KeySchema: [
{ AttributeName: "username", KeyType: "HASH" },
{ AttributeName: "insertedTime", KeyType: "RANGE" }
],
Projection: {
ProjectionType: "ALL"
},
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
},
{
IndexName: "fromFriend-index",
KeySchema: [
{ AttributeName: "fromFriend", KeyType: "HASH" }
],
Projection: {
ProjectionType: "ALL"
},
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
}
],
ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 10 }
},
{
TableName: `Reactions`,
KeySchema: [
{ AttributeName: "messageId", KeyType: "HASH" },
{ AttributeName: "insertTime", KeyType: "RANGE" }
],
AttributeDefinitions: [
{ AttributeName: "messageId", AttributeType: "S" },
{ AttributeName: "insertTime", AttributeType: "N" }
],
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
}
]
};
|
import numpy as np
def split_data(input, output, validation_percentage=0.1):
num_sets = output.shape[0]
num_validation = int(num_sets * validation_percentage)
training_input, validation_input = input[:-num_validation], input[-num_validation:]
training_output, validation_output = output[:-num_validation], output[-num_validation:]
return (training_input, training_output), (validation_input, validation_output) |
#!/bin/bash
IN=${IN:-$PASH_TOP/evaluation/benchmarks/for-loops/input/node_modules}
MIR_BIN=${MIR_BIN:-$PASH_TOP/evaluation/benchmarks/for-loops/input/mir-sa/.bin/mir-sa}
OUT=${OUT:-$PASH_TOP/evaluation/benchmarks/for-loops/input/output/mir}
mkdir -p ${OUT}/
pkg_count=0
run_tests() {
cd $1;
${MIR_BIN} -p 2>>${OUT}/error.log
}
export -f run_tests
for item in ${IN}/*;
do
pkg_count=$((pkg_count + 1));
run_tests $item > ${OUT}/$pkg_count.log
done
echo 'done';
|
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void NewCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
txtEditor.Document = new FlowDocument();
}
private void OpenCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
// write your code here
}
private void SaveCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
// write your code here
}
private void PrintCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
// write your code here
}
} |
/*
* 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 javax.swing;
import java.awt.Color;
import java.awt.Component;
/**
*
* @author <NAME> (d120041) <<EMAIL>>
*/
public class JListCellRendererLabel extends JLabel implements ListCellRenderer<Object> {
private final static int unselected = 0;
private final static int selected = 1;
private final static int current = 2;
private int state = 0;
public JListCellRendererLabel() {
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList<?> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
setText(value.toString());
// check if this cell represents the current DnD drop location
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
state = current;
currentDnD();
// check if this cell is selected
} else if (isSelected) {
state = selected;
selected();
// unselected, and not the DnD drop location
} else {
state = unselected;
unselected();
}
return this;
}
public void stateBack() {
switch(state) {
case current:
currentDnD();
break;
case selected:
selected();
break;
case unselected:
unselected();
break;
}
}
void currentDnD() {
setBackground(Color.BLUE);
setForeground(Color.WHITE);
}
void selected() {
setBackground(Color.RED);
setForeground(Color.WHITE);
}
void unselected() {
setBackground(Color.WHITE);
setForeground(Color.BLACK);
}
}
|
/*
* AddNewBook.sql
* Chapter 8, Oracle10g PL/SQL Programming
* by <NAME>, <NAME>, and <NAME>
*
* This procedure will insert a new book into the books table.
* It also demonstrates default parameters.
*/
CREATE OR REPLACE PROCEDURE AddNewBook(
p_ISBN IN books.ISBN%TYPE,
p_Category IN books.category%TYPE := 'Oracle Server',
p_Title IN books.title%TYPE,
p_NumPages IN books.num_pages%TYPE,
p_Price IN books.price%TYPE,
p_Copyright IN books.copyright%TYPE DEFAULT
TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')),
p_Author1 IN books.author1%TYPE,
p_Author2 IN books.author2%TYPE := NULL,
p_Author3 IN books.author3%TYPE := NULL) AS
BEGIN
-- Insert a new row into the table using the supplied
-- parameters.
INSERT INTO books (isbn, category, title, num_pages, price,
copyright, author1, author2, author3)
VALUES (p_ISBN, p_Category, p_Title, p_NumPages, p_Price,
p_Copyright, p_Author1, p_Author2, p_Author3);
END AddNewBook;
/
-- We can avoid passing author2 and author3 since they have
-- default values:
BEGIN
AddNewBook('0000000000', 'Oracle Basics', 'A Really Nifty Book',
500, 34.99, 2004, 1);
END;
/
ROLLBACK;
-- The same example, using named notation:
BEGIN
AddNewBook(p_ISBN => '0000000000',
p_Category => 'Oracle Basics',
p_Title => 'A Really Nifty Book',
p_NumPages => 500,
p_Price => 34.99,
p_Copyright => 2004,
p_Author1 => 1);
END;
/
ROLLBACK;
-- Using all the default values:
BEGIN
AddNewBook(p_ISBN => '0000000000',
p_Title => 'A Really Nifty Book',
p_NumPages => 500,
p_Price => 34.99,
p_Author1 => 1);
END;
/
ROLLBACK;
|
<gh_stars>0
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
@Injectable()
export class ApiUserService {
domain: string = '/api/user';
constructor(private http: HttpClient) { }
getUser(id: string) {
return this.http.get(`${this.domain}/${id}`, httpOptions)
.map(res => res);
}
getUsers() {
return this.http.get(`${this.domain}`, httpOptions)
.map(res => res);
}
saveUser(newUser) {
return this.http.post(`${this.domain}`, newUser, httpOptions)
.map(res => res);
}
updateUser(_id, nid, name, email, address) {
const updUser = {
_id, nid, name, email, address
};
return this.http.put(`${this.domain}/${_id}`, updUser, httpOptions)
.map(res => res);
}
deleteUser(id: string) {
return this.http.delete(`${this.domain}/${id}`, httpOptions)
.map(res => res);
}
}
|
<filename>trunklucator/base/dto.py<gh_stars>10-100
from collections import OrderedDict
from datetime import datetime
def namedtuple_asdict(obj):
if hasattr(obj, "_asdict"): # detect namedtuple
return OrderedDict(zip(obj._fields, (namedtuple_asdict(item) for item in obj)))
elif isinstance(obj, str): # iterables - strings
return obj
elif isinstance(obj, datetime):
return obj.isoformat()
elif hasattr(obj, "keys"): # iterables - mapping
return OrderedDict(zip(obj.keys(), (namedtuple_asdict(item) for item in obj.values())))
elif hasattr(obj, "__iter__"): # iterables - sequence
return type(obj)((namedtuple_asdict(item) for item in obj))
else: # non-iterable cannot contain namedtuples
return obj
class AsDict():
def to_dict(self):
return namedtuple_asdict(self)
|
// Descrição: Arquivo responsável pela lógica das rotas das variacoes
const mongoose = require('mongoose')
const Variacao = mongoose.model('Variacao')
const Produto = mongoose.model('Produto')
class VariacaoController {
// ----------------------------------------------------------- CLIENTES/VISITANTES -----------------------------------------------------------
// GET /
async index(req, res, next) {
const { loja, produto } = req.query
try {
const variacoes = await Variacao.find({ loja, produto })
return res.send({ variacoes })
} catch (e) {
next(e)
}
}
// GET /:id
async show(req, res, next) {
const { loja, produto } = req.query
const { id: _id } = req.params
try {
const variacao = await Variacao.findOne({ _id, loja, produto })
return res.send({ variacao })
} catch (e) {
next(e)
}
}
// -------------------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------ ADMIN -------------------------------------------------------------
// POST /
async store(req, res, next) {
const { codigo, nome, preco, promocao, entrega, quantidade } = req.body;
const { loja, produto } = req.query;
try {
const variacao = new Variacao({
codigo, nome, preco, promocao, entrega, quantidade, loja, produto
});
const _produto = await Produto.findById(produto);
if (!_produto) return res.status(400).send({ error: "Produto não encontrado." });
_produto.variacoes.push(variacao._id);
await _produto.save();
await variacao.save();
return res.send({ variacao });
} catch (e) {
next(e);
}
}
// PUT /:id
async update(req, res, next) {
const { codigo, fotos, nome, preco, promocao, entrega, quantidade } = req.body;
const { loja, produto } = req.query;
const { id: _id } = req.params;
try {
const variacao = await Variacao.findOne({ loja, produto, _id });
if (!variacao) return res.status(400).send({ error: "Variação não encontrada" });
if (codigo) variacao.codigo = codigo;
if (nome) variacao.nome = nome;
if (preco) variacao.preco = preco;
if (promocao) variacao.promocao = promocao;
if (entrega) variacao.entrega = entrega;
if (quantidade) variacao.quantidade = quantidade;
if (fotos) variacao.fotos = fotos;
await variacao.save();
return res.send({ variacao });
} catch (e) {
next(e);
}
}
// PUT /images/:id
async updateImages(req, res, next) {
const { loja, produto } = req.query;
const { id: _id } = req.params;
try {
const variacao = await Variacao.findOne({ loja, produto, _id });
if (!variacao) return res.status(400).send({ error: "Variação não encontrada" });
const novasImagens = req.files.map(item => item.filename);
variacao.fotos = variacao.fotos.filter(item => item).concat(novasImagens);
await variacao.save();
return res.send({ variacao });
} catch (e) {
next(e);
}
}
// DELETE /:id
async remove(req, res, next) {
const { loja, produto } = req.query;
const { id: _id } = req.params;
try {
const variacao = await Variacao.findOne({ loja, produto, _id });
if (!variacao) return res.status(400).send({ error: "Variação não encontrada" });
const _produto = await Produto.findById(variacao.produto);
_produto.variacoes = _produto.variacoes.filter(item => item.toString() !== variacao._id.toString());
await _produto.save();
await variacao.remove();
return res.send({ deletado: true });
} catch (e) {
next(e);
}
}
// --------------------------------------------------------------------------------------------------------------------------------
}
module.exports = VariacaoController |
package de.unistuttgart.ims.coref.annotator;
class SearchResult {
Span span;
SearchContainer container;
public SearchResult(SearchContainer container, int begin, int end) {
super();
this.container = container;
this.span = new Span(begin, end);
}
public int getBegin() {
return span.begin;
}
public int getEnd() {
return span.end;
}
public Span getSpan() {
return span;
}
@Override
public String toString() {
return this.container.getText().substring(Integer.max(span.begin - this.container.getContexts(), 0),
Integer.min(span.end + this.container.getContexts(), this.container.getText().length() - 1));
}
} |
<filename>src/main/java/com/netcracker/ncstore/service/general/payment/BraintreePaymentService.java
package com.netcracker.ncstore.service.general.payment;
import com.braintreegateway.BraintreeGateway;
import com.braintreegateway.MerchantAccount;
import com.braintreegateway.Result;
import com.braintreegateway.Transaction;
import com.braintreegateway.TransactionRequest;
import com.braintreegateway.ValidationError;
import com.netcracker.ncstore.dto.PaymentProceedDTO;
import com.netcracker.ncstore.exception.PaymentServiceCurrencyNotSupportedException;
import com.netcracker.ncstore.exception.PaymentServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Currency;
import java.util.Iterator;
@Service
@Slf4j
public class BraintreePaymentService implements IPaymentService {
private final BraintreeGateway braintreeGateway;
public BraintreePaymentService(final BraintreeGateway braintreeGateway) {
this.braintreeGateway = braintreeGateway;
}
@Override
public String getPaymentToken() {
return braintreeGateway.clientToken().generate();
}
@Override
public String proceedPaymentInRealMoney(PaymentProceedDTO paymentProceedDTO) {
log.info("Processing payment with amount " + paymentProceedDTO.getAmount() + " in currency with ISO code " + Currency.getInstance(paymentProceedDTO.getRegion()).getCurrencyCode());
String currencyISOCode = Currency.getInstance(paymentProceedDTO.getRegion()).getCurrencyCode();
Iterator<MerchantAccount> merchantAccountIterator = braintreeGateway.merchantAccount().all().iterator();
MerchantAccount paymentMerchantAccount = null;
while (merchantAccountIterator.hasNext()) {
MerchantAccount merchantAccount = merchantAccountIterator.next();
if (merchantAccount.getCurrencyIsoCode().equals(currencyISOCode)) {
paymentMerchantAccount = merchantAccount;
}
}
if (paymentMerchantAccount == null) {
log.error("There was a request to pay in currency" + currencyISOCode + " but payment in that currency is not suppoerted");
throw new PaymentServiceCurrencyNotSupportedException("Currency with code " + currencyISOCode + " not supported");
}
TransactionRequest request = new TransactionRequest()
.amount(paymentProceedDTO.getAmount())
.paymentMethodNonce(paymentProceedDTO.getNonce())
.merchantAccountId(paymentMerchantAccount.getId())
.options()
.submitForSettlement(true)
.done();
Result<Transaction> result = braintreeGateway.transaction().sale(request);
if (result.isSuccess()) {
Transaction transaction = result.getTarget();
return transaction.getId();
} else {
StringBuilder errorStringBuilder = new StringBuilder();
for (ValidationError error : result.getErrors().getAllDeepValidationErrors()) {
errorStringBuilder.append("Error: ").append(error.getCode()).append(": ").append(error.getMessage()).append("\n");
}
log.error("Can not proceed payment due to error");
throw new PaymentServiceException(errorStringBuilder.toString());
}
}
}
|
# debug
magiskpolicy --live "dontaudit system_server system_file file write"
magiskpolicy --live "allow system_server system_file file write"
# context
magiskpolicy --live "type same_process_hal_file"
magiskpolicy --live "type system_lib_file"
magiskpolicy --live "type vendor_file"
magiskpolicy --live "type vendor_configs_file"
magiskpolicy --live "dontaudit vendor_configs_file labeledfs filesystem associate"
magiskpolicy --live "allow vendor_configs_file labeledfs filesystem associate"
magiskpolicy --live "dontaudit init vendor_configs_file dir relabelfrom"
magiskpolicy --live "allow init vendor_configs_file dir relabelfrom"
magiskpolicy --live "dontaudit init vendor_configs_file file relabelfrom"
magiskpolicy --live "allow init vendor_configs_file file relabelfrom"
# dir
magiskpolicy --live "dontaudit { system_app priv_app platform_app untrusted_app_29 untrusted_app_27 untrusted_app } { mcd_data_file sysfs_msm_subsys } dir search
magiskpolicy --live "allow { system_app priv_app platform_app untrusted_app_29 untrusted_app_27 untrusted_app } { mcd_data_file sysfs_msm_subsys } dir search
# additional
magiskpolicy --live "dontaudit { hal_audio_default mtk_hal_audio audioserver } { default_prop boottime_prop } file { read open getattr map }"
magiskpolicy --live "allow { hal_audio_default mtk_hal_audio audioserver } { default_prop boottime_prop } file { read open getattr map }"
magiskpolicy --live "dontaudit { hal_audio_default mtk_hal_audio audioserver } { mnt_vendor_file system_prop } file { read open getattr }"
magiskpolicy --live "allow { hal_audio_default mtk_hal_audio audioserver } { mnt_vendor_file system_prop } file { read open getattr }"
magiskpolicy --live "dontaudit { hal_audio_default mtk_hal_audio audioserver } audio_prop file read"
magiskpolicy --live "allow { hal_audio_default mtk_hal_audio audioserver } audio_prop file read"
magiskpolicy --live "dontaudit { hal_audio_default mtk_hal_audio audioserver } sysfs_wake_lock file { write open }"
magiskpolicy --live "allow { hal_audio_default mtk_hal_audio audioserver } sysfs_wake_lock file { write open }"
magiskpolicy --live "dontaudit { hal_audio_default mtk_hal_audio audioserver } vendor_default_prop file open"
magiskpolicy --live "allow { hal_audio_default mtk_hal_audio audioserver } vendor_default_prop file open"
magiskpolicy --live "dontaudit { hal_audio_default mtk_hal_audio audioserver } sysfs_net dir read"
magiskpolicy --live "allow { hal_audio_default mtk_hal_audio audioserver } sysfs_net dir read"
magiskpolicy --live "dontaudit { hal_audio_default mtk_hal_audio audioserver } { diag_device vendor_diag_device } chr_file { read write open ioctl getattr }"
magiskpolicy --live "allow { hal_audio_default mtk_hal_audio audioserver } { diag_device vendor_diag_device } chr_file { read write open ioctl getattr }"
magiskpolicy --live "dontaudit hal_audio_default hal_audio_default capability2 block_suspend"
magiskpolicy --live "allow hal_audio_default hal_audio_default capability2 block_suspend"
magiskpolicy --live "dontaudit mtk_hal_audio mtk_hal_audio capability2 block_suspend"
magiskpolicy --live "allow mtk_hal_audio mtk_hal_audio capability2 block_suspend"
magiskpolicy --live "dontaudit audioserver audioserver capability2 block_suspend"
magiskpolicy --live "allow audioserver audioserver capability2 block_suspend"
|
<reponame>andromeda/mir
var _;
_ = Promise.length;
_ = Promise.name;
_ = Promise.prototype;
_ = Promise.all;
_ = Promise.race;
_ = Promise.resolve;
_ = Promise.reject;
|
#!/usr/bin/env bash
# Connectivity check to see if NAT Gateway is up
count=0
while true
do
if ping -c 1 -W 5 google.com 1>/dev/null 2>&1
then
echo "Connected!"
break
elif [ $count -le 15 ]
then
echo "Not Connected!"
count=$[$count+1]
else
echo "Giving up"
break
fi
sleep 1
done
#Get IP
local_ipv4="$(curl -s http://169.254.169.254/latest/meta-data/local-ipv4)"
#Utils
sudo apt update
#Install Dockers
sudo snap install docker
sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
#Run nginx
sleep 10
cat << EOF > docker-compose.yml
version: "3.7"
services:
web:
image: nginxdemos/hello
ports:
- "80:80"
restart: always
command: [nginx-debug, '-g', 'daemon off;']
network_mode: "host"
EOF
sudo docker-compose up -d |
#!/bin/bash
get_input() {
xinput | grep "$1" | cut -f2 -d"=" | cut -f1
}
get_output() {
xrandr | grep " conn" | cut -f1 -d" "
}
xrandr --fb 7000x4000 \
--output eDP-1 --scale 0.4x0.4 --pos 0x1200 \
--output DP-1-1 --auto --rotate left --pos 1280x0 \
--output DP-1-2-8 --auto --pos 2360x840
# --output DP-1-2 --auto --pos 1280x840 \
# --output DP-1-1 --auto --rotate normal --pos 1280x720 \
# --output DP-1-2 --auto --rotate normal --pos 3200x720
## set up pointing devices
TOUCHPAD="$(get_input "DLL075B:01 06CB:76AF Touchpad")"
if [ -n "$TOUCHPAD" ]; then
xinput set-prop "$TOUCHPAD" 287 1 # Natural Scrolling
xinput set-prop "$TOUCHPAD" 279 1 # Tapping
fi
MOUSE="$(get_input "GASIA PS2toUSB Adapter Mouse")"
if [ -n "$MOUSE" ]; then
xinput set-prop "$MOUSE" 287 1 # Natural Scrolling
fi
## set up keyboards
KBD_XPS="$(get_input "AT Translated Set 2 keyboard")"
if [ -n "$KBD_XPS" ]; then
setxkbmap -device "$KBD_XPS" \
-layout us,se -option "" -option grp:shifts_toggle -option ctrl:nocaps
fi
KBD_HH="$(get_input "GASIA PS2toUSB Adapter ")"
if [ -n "$KBD_HH" ]; then
setxkbmap -device "$KBD_HH" \
-layout us,se -option "" -option grp:shifts_toggle -option ctrl:nocaps \
-option altwin:swap_lalt_lwin
fi
|
function randomIntFromInterval(min, max) {
// min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
let randomNumber = randomIntFromInterval(1, 10); |
<?php
// Assuming database connection is established and stored in $db variable
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['skill_name']) && isset($_POST['skill_icon'])) {
$skillName = htmlspecialchars($_POST['skill_name']);
$skillIcon = htmlspecialchars($_POST['skill_icon']);
// Validate skill name and icon
if (!empty($skillName) && !empty($skillIcon)) {
// Prepare and execute the SQL query to insert data into 'skills' table
$stmt = $db->prepare("INSERT INTO skills (skill_name, skill_icon) VALUES (?, ?)");
$stmt->bind_param("ss", $skillName, $skillIcon);
$stmt->execute();
// Redirect back to the form with success message
header("Location: add_skill_form.php?success=1");
exit();
} else {
// Redirect back to the form with error message for empty fields
header("Location: add_skill_form.php?error=1");
exit();
}
} else {
// Redirect back to the form with error message for missing fields
header("Location: add_skill_form.php?error=2");
exit();
}
}
?> |
#!/bin/bash
# Step 1: Start the Docker container
docker run -d --rm --net grid --name remote-firefox --link website -e HUB_HOST=selenium-hub -v /dev/shm:/dev/shm selenium/node-firefox:3.141.59-selenium
# Step 2: Execute the shell script to wait for the Selenium Grid
sh wait_for_grid.sh |
from .IWalkIOAdapter import IWalkIOAdapter
try:
import fabric
class IFabricIOAdapter(IWalkIOAdapter):
def __init__(self, host:str = None, port:int = None, user:str = None, pwd:str = None, c:fabric.Connection = None):
if c:
self.__c = c
else:
self.__c = fabric.Connection(host=host, user=user, port=port, connect_kwargs={"password": <PASSWORD>})
self.__sftp = self.__c.sftp()
#
def listdirCallback(self):
return self.__sftp.listdir
#
def lstatCallback(self):
return self.__sftp.lstat
#
#
except Exception as ee:
class IFabricIOAdapter(IWalkIOAdapter):
def __init__(self, **kwargs):
raise Exception("'fabric' is not installed!")
#
#
|
<reponame>centrual/geolocator
let _toString = Object.prototype.toString;
/**
* Simple utility methods; internally used within Geolocator core;
* made publically accessible.
* @type {Object}
* @readonly
*/
const utils = {
noop() {},
// ---------------------------
// Validation
// ---------------------------
/**
* Checks if the type of the given value is `String`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isString(value) {
return typeof value === 'string';
},
isStringSet(value) {
return typeof value === 'string' && value.trim().length > 0;
},
/**
* Checks if the type of the given value is `Number`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isNumber(value) {
return typeof value === 'number';
},
/**
* Checks if the type of the given value is an `Object` or `Function`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isObject(value) {
let type = typeof value;
return Boolean(value) && (type === 'object' || type === 'function');
},
/**
* Checks if the type of the given value is `Function`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isFunction(value) {
return typeof value === 'function';
},
/**
* Checks if the type of the given value is `Array`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isArray(value) {
return Boolean(value) && _toString.call(value) === '[object Array]';
},
/**
* Checks if the given object is a non-empty `Array`.
* @memberof utils
*
* @param {*} array - Object to be checked.
* @returns {Boolean}
*/
isFilledArray(array) {
return utils.isArray(array) && array.length > 0;
},
/**
* Checks if the given value is a plain `Object`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isPlainObject(value) {
return Boolean(value)
&& typeof value === 'object'
&& _toString.call(value) === '[object Object]';
},
/**
* Checks if the given value is a `Date`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isDate(value) {
return Boolean(value) && _toString.call(value) === '[object Date]';
},
/**
* Checks if the given object is a DOM element.
* @memberof utils
*
* @param {Object} object - Object to be checked.
* @returns {Boolean}
*/
isElement(object) {
if (!object) return false;
return object instanceof HTMLElement
|| (typeof object === 'object' && object.nodeType === 1);
},
/**
* Checks if the given object is a DOM node.
* @memberof utils
*
* @param {Object} object - Object to be checked.
* @returns {Boolean}
*/
isNode(object) {
if (!object) return false;
return object instanceof Node
|| (typeof object === 'object' && typeof object.nodeType === 'number');
},
/**
* Checks if the given object is a jQuery instance.
* This will still return `false` if the jQuery instance has no items.
* @memberof utils
*
* @param {Object} object - Object to be checked.
* @returns {Boolean}
*/
isJQueryObject(object) {
if (!object) return false;
return ('jQuery' in window && object instanceof window.jQuery && Boolean(object[0]));
// http://api.jquery.com/jquery-2/
// || (typeof object === 'object' && Boolean(object.jquery));
},
/**
* Checks if the type of the given value is an HTML5 `PositionError`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isPositionError(value) {
return Boolean(value) && _toString.call(value) === '[object PositionError]';
},
/**
* Checks if the given value is an instance of `Error` or HTML5 `PositionError`.
* @memberof utils
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isError(value) {
return (value instanceof Error) || utils.isPositionError(value);
},
// ---------------------------
// String
// ---------------------------
/**
* Removes the query string portion from the given URL string.
* @memberof utils
*
* @param {String} str - String to be processed.
* @returns {String} - Returns the rest of the string.
*/
removeQuery(str) {
return str.replace(/\?.*$/, '');
},
/**
* Removes the protocol portion from the given URL string.
* @memberof utils
*
* @param {String} str - String to be processed.
* @returns {String} - Returns the rest of the string.
*/
removeProtocol(str) {
return str.replace(/^(.*:)?\/\//, '');
},
/**
* Sets the protocol of the given URL.
* @memberof utils
*
* @param {String} url
* The URL to be modified.
* @param {Boolean} [https]
* Specifies whether to set the protocol to HTTPS.
* If omitted, current page protocol will be used.
*
* @returns {String} - The modified URL string.
*/
setProtocol(url, https) {
let p;
if (https === undefined || https === null) {
p = window.location.protocol;
} else {
p = https ? 'https:' : 'http:';
}
url = utils.removeProtocol(url);
return `${p}//${url}`;
},
/**
* Removes both the leading and trailing dots from the given string.
* @memberof utils
*
* @param {String} str - String to be processed.
* @returns {String} - Returns the rest of the string.
*/
trimDots(str) {
return str.replace(/^\.+?(.*?)\.+?$/g, '$1');
},
/**
* URL-Encodes the given string. Note that the encoding is done Google's
* way; that is, spaces are replaced with `+` instead of `%20`.
* @memberof utils
*
* @param {String} str - String to be processed.
* @returns {String} - Returns the encoded string.
*/
encodeURI(str) {
return encodeURIComponent(str).replace(/%20/g, '+');
},
/**
* URL-Decodes the given string. This is the reverse of `utils.encodeURI()`;
* so pluses (`+`) are replaced with spaces.
* @memberof utils
*
* @param {String} str - String to be processed.
* @returns {String} - Returns the decoded string.
*/
decodeURI(str) {
return decodeURIComponent(str.replace(/\+/g, '%20'));
},
/**
* Converts the given value to string.
* `null` and `undefined` converts to empty string.
* If value is a function, it's native `toString()` method is used.
* Otherwise, value is coerced.
* @memberof utils
*
* @param {*} value - String to be converted.
* @returns {String} - Returns the result string.
*/
toString(value) {
if (value === null || value === undefined) return '';
if (value.toString && utils.isFunction(value.toString)) {
return value.toString();
}
return String(value);
},
/**
* Generates a random string with the number of characters.
* @memberof utils
*
* @param {Number} [len=1] - Length of the string.
* @returns {String} - Returns a random string.
*/
randomString(len) {
if (!len || !utils.isNumber(len)) len = 1;
len = -Math.abs(len);
return Math.random().toString(36).slice(len);
},
/**
* Gets the abbreviation of the given phrase.
* @memberof utils
*
* @param {String} str
* String to abbreviate.
* @param {Object} [options]
* Abbreviation options.
* @param {Boolean} [options.upper=true]
* Whether to convert to upper-case.
* @param {Boolean} [options.dots=true]
* Whether to add dots after each abbreviation.
*
* @returns {String} - Returns the abbreviation of the given phrase.
*/
abbr(str, options) {
options = utils.extend({
upper: true,
dots: true
}, options);
let d = options.dots ? '.' : '',
s = str.match(/(\b\w)/gi).join(d) + d;
return options.upper ? s.toUpperCase() : s;
},
/**
* Builds URI parameters from the given object.
* Note: This does not iterate deep objects.
* @memberof utils
*
* @param {Object} obj - Object to be processed.
* @param {Object} options - Parameterize options.
* @param {Boolean} [options.encode=true]
* Whether to encode URI components.
* @param {String} [options.operator="="]
* @param {String} [options.separator="&"]
* @param {Array} [options.include]
* Keys to be included in the output params. If defined,
* `options.exclude` is ignored.
* @param {Array} [options.exclude]
* Keys to be excluded from the output params.
*
* @returns {String} - URI parameters string.
*/
params(obj, options) {
if (!utils.isPlainObject(obj) || Object.keys(obj).length === 0) {
return '';
}
options = utils.extend({
encode: true,
operator: '=',
separator: '&',
include: undefined,
exclude: undefined
}, options);
let params = [],
inc = utils.isArray(options.include) ? options.include : null,
exc = !inc && utils.isArray(options.exclude) ? options.exclude : null;
utils.forIn(obj, (value, key) => {
if ((!inc || inc.indexOf(key) >= 0)
&& (!exc || exc.indexOf(key) < 0)) {
let v = utils.toString(value);
v = options.encode ? utils.encodeURI(v) : v;
let k = options.encode ? utils.encodeURI(key) : key;
params.push(k + options.operator + v);
}
});
return params.join(options.separator);
},
/**
* Gets the object from the given object notation string.
* @private
*
* @param {String} notation - Object notation.
* @returns {*} - Any existing object.
*/
notateGlobalObj(notation) {
notation = utils.trimDots(notation);
let levels = notation.split('.'),
o = window;
if (levels[0] === 'window' || levels[0] === 'document') {
levels.shift();
}
levels.forEach(note => {
o = o[note];
});
return o;
},
// ---------------------------
// Object
// ---------------------------
/**
* Iterates over own properties of an object invoking a callback for each
* property.
* @memberof utils
*
* @param {Object} obj
* Object to be processed.
* @param {Function} callback
* Callback function with the following signature:
* `function (value, key, object) { ... }`.
* Explicitly returning `false` will exit the iteration early.
* @returns {void}
*/
forIn(obj, callback) {
let k;
for (k in obj) {
// if (obj.hasOwnProperty(k)) {} // Do this inside callback if needed.
if (callback(obj[k], k, obj) === false) break;
}
},
/**
* Extends the given object with the specified sources.
* Right most source overwrites the previous.
* NOTE: This is not a full implementation. Use with caution.
* @memberof utils
*
* @param {Object} destination
* Destionation Object that will be extended and holds the default
* values.
* @param {...Object} sources
* Source objects to be merged.
*
* @returns {Object} - Returns the extended object.
*/
extend(destination, ...sources) {
if (!utils.isObject(destination)) return {};
let key, value;
sources.forEach(source => {
for (key in source) { // eslint-disable-line
value = source[key];
if (utils.isArray(value)) {
destination[key] = value.concat();
} else if (utils.isDate(value)) {
destination[key] = new Date(value);
} else if (utils.isFunction(value)) { // should be before object
destination[key] = value;
} else if (utils.isObject(value)) {
destination[key] = utils.extend({}, value);
} else {
destination[key] = value;
}
}
});
return destination;
},
/**
* Clones the given object.
* NOTE: This is not a full implementation. Use with caution.
* @memberof utils
*
* @param {Object} obj
* Target Object to be cloned.
* @param {Object|Array} [options]
* Clone options or array of keys to be cloned.
* @param {Array} [options.keys]
* Keys of the properties to be cloned.
* @param {Boolean} [options.own=true]
* Whether to clone own properties only. This is only effective
* if `keys` is not defined.
*
* @returns {Object} - Returns the cloned object.
*/
clone(obj, options) {
if (!obj) return {};
if (utils.isArray(options)) {
options = { keys: options };
}
options = utils.extend({
keys: null,
own: true
}, options);
let include,
cloned = {};
utils.forIn(obj, (value, key) => {
include = options.keys
? options.keys.indexOf(key) >= 0
: (options.own && obj.hasOwnProperty(key)) || !options.own;
if (include) {
if (utils.isObject(value)) {
cloned[key] = utils.clone(value, options);
} else {
cloned[key] = value;
}
}
});
return cloned;
},
/**
* Maps the values of the given object to a schema to re-structure a new
* object.
* @memberof utils
*
* @param {Object} obj
* Original object to be mapped.
* @param {Object} schema
* Schema to be used to map the object.
*
* @returns {Object} - Mapped object.
*/
mapToSchema(obj, schema) {
let mapped = {};
utils.forIn(schema, (value, key) => {
if (utils.isPlainObject(value)) {
mapped[key] = utils.mapToSchema(obj, value);
} else {
mapped[key] = obj[value];
}
});
return mapped;
},
// ---------------------------
// Misc
// ---------------------------
/**
* Safely parses the given JSON `String` into an `Object`.
* The only difference from `JSON.parse()` is that this method does not
* throw for invalid input. Instead, returns `null`.
* @memberof utils
*
* @param {String} str - JSON string to be parsed
* @returns {Object|null} - Returns the parsed `Object` or `null` if the
* input is invalid.
*/
safeJsonParse(str) {
let o = null;
try {
o = JSON.parse(str);
} catch (e) {}
return o;
},
/**
* Gets a timestamp that is seconds or milliseconds since midnight,
* January 1, 1970 UTC.
* @memberof utils
*
* @param {Boolean} [seconds=false]
* Specifies whether seconds should be returned instead of
* milliseconds.
*
* @returns {Number} - Returns seconds or milliseconds since midnight,
* January 1, 1970 UTC.
*/
time(seconds) {
let ts = Date.now();
return seconds ? parseInt(ts / 1000, 10) : ts;
}
};
export default utils;
|
<reponame>axitdn/keycloak
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.testsuite.arquillian.provider;
import org.jboss.arquillian.container.test.api.OperateOnDeployment;
import org.jboss.arquillian.container.test.impl.enricher.resource.URLResourceProvider;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.logging.Logger;
import org.jboss.logging.Logger.Level;
import org.keycloak.testsuite.arquillian.SuiteContext;
import org.keycloak.testsuite.arquillian.TestContext;
import org.keycloak.testsuite.arquillian.annotation.AppServerBrowserContext;
import org.keycloak.testsuite.arquillian.annotation.AppServerContext;
import org.keycloak.testsuite.arquillian.annotation.AuthServerBrowserContext;
import org.keycloak.testsuite.arquillian.annotation.AuthServerContext;
import java.lang.annotation.Annotation;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.keycloak.testsuite.arquillian.ContainerInfo;
public class URLProvider extends URLResourceProvider {
protected final Logger log = Logger.getLogger(this.getClass());
public static final String BOUND_TO_ALL = "0.0.0.0";
public static final String LOCALHOST_ADDRESS = "127.0.0.1";
public static final String LOCALHOST_HOSTNAME = "localhost";
private final boolean appServerSslRequired = Boolean.parseBoolean(System.getProperty("app.server.ssl.required"));
@Inject
Instance<SuiteContext> suiteContext;
@Inject
Instance<TestContext> testContext;
private static final Set<String> fixedUrls = new HashSet<>();
@Override
public Object doLookup(ArquillianResource resource, Annotation... qualifiers) {
URL url = (URL) super.doLookup(resource, qualifiers);
if (url == null) {
String port = appServerSslRequired ?
System.getProperty("app.server.https.port", "8643") :
System.getProperty("app.server.http.port", "8280");
String protocol = appServerSslRequired ? "https" : "http";
try {
for (Annotation a : qualifiers) {
if (OperateOnDeployment.class.isAssignableFrom(a.annotationType())) {
return new URL(protocol + "://localhost:" + port + "/" + ((OperateOnDeployment) a).value());
}
}
} catch (MalformedURLException ex) {
throw new RuntimeException(ex);
}
}
// fix injected URL
if (url != null) {
try {
url = fixLocalhost(url);
url = fixBoundToAll(url);
url = removeTrailingSlash(url);
if (appServerSslRequired) {
url = fixSsl(url);
}
} catch (MalformedURLException ex) {
log.log(Level.FATAL, null, ex);
}
if (!fixedUrls.contains(url.toString())) {
fixedUrls.add(url.toString());
log.debug("Fixed injected @ArquillianResource URL to: " + url);
}
}
// inject context roots if annotation present
for (Annotation a : qualifiers) {
if (AuthServerContext.class.isAssignableFrom(a.annotationType())) {
return suiteContext.get().getAuthServerInfo().getContextRoot();
}
if (AppServerContext.class.isAssignableFrom(a.annotationType())) {
//standalone
ContainerInfo appServerInfo = testContext.get().getAppServerInfo();
if (appServerInfo != null) return appServerInfo.getContextRoot();
//cluster
List<ContainerInfo> appServerBackendsInfo = testContext.get().getAppServerBackendsInfo();
if (appServerBackendsInfo.isEmpty()) throw new IllegalStateException("Both testContext's appServerInfo and appServerBackendsInfo not set.");
return appServerBackendsInfo.get(0).getContextRoot();
}
if (AuthServerBrowserContext.class.isAssignableFrom(a.annotationType())) {
return suiteContext.get().getAuthServerInfo().getBrowserContextRoot();
}
if (AppServerBrowserContext.class.isAssignableFrom(a.annotationType())) {
//standalone
ContainerInfo appServerInfo = testContext.get().getAppServerInfo();
if (appServerInfo != null) return appServerInfo.getBrowserContextRoot();
//cluster
List<ContainerInfo> appServerBackendsInfo = testContext.get().getAppServerBackendsInfo();
if (appServerBackendsInfo.isEmpty()) throw new IllegalStateException("Both testContext's appServerInfo and appServerBackendsInfo not set.");
return appServerBackendsInfo.get(0).getBrowserContextRoot();
}
}
return url;
}
public URL fixBoundToAll(URL url) throws MalformedURLException {
URL fixedUrl = url;
if (url.getHost().contains(BOUND_TO_ALL)) {
fixedUrl = new URL(fixedUrl.toExternalForm().replace(BOUND_TO_ALL, LOCALHOST_HOSTNAME));
}
return fixedUrl;
}
public URL fixLocalhost(URL url) throws MalformedURLException {
URL fixedUrl = url;
if (url.getHost().contains(LOCALHOST_ADDRESS)) {
fixedUrl = new URL(fixedUrl.toExternalForm().replace(LOCALHOST_ADDRESS, LOCALHOST_HOSTNAME));
}
return fixedUrl;
}
public URL fixSsl(URL url) throws MalformedURLException {
URL fixedUrl = url;
String urlString = fixedUrl.toExternalForm().replace("http", "https").replace(System.getProperty("app.server.http.port", "8280"), System.getProperty("app.server.https.port", "8643"));
return new URL(urlString);
}
public URL removeTrailingSlash(URL url) throws MalformedURLException {
URL urlWithoutSlash = url;
String urlS = url.toExternalForm();
if (urlS.endsWith("/")) {
urlWithoutSlash = new URL(urlS.substring(0, urlS.length() - 1));
}
return urlWithoutSlash;
}
}
|
#!/usr/bin/env sh
. ./mturk_init.sh
exec "$MTURK_CMD_HOME"/bin/invoke.sh GetResults -successfile $OUR_DIR/$OUR_NAME.success -outputfile $OUR_DIR/$OUR_NAME.results
|
package com.prt2121.githubsdk.model.response.events.payload;
import com.prt2121.githubsdk.model.response.Repo;
/**
* Created by Bernat on 05/10/2014.
*/
public class ForkEventPayload extends GithubEventPayload {
public Repo forkee;
public Repo repository;
}
|
package io.dronefleet.mavlink.common;
import io.dronefleet.mavlink.annotations.MavlinkFieldInfo;
import io.dronefleet.mavlink.annotations.MavlinkMessageBuilder;
import io.dronefleet.mavlink.annotations.MavlinkMessageInfo;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.util.Objects;
/**
* Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been
* kept simple, so transmitting the key requires an encrypted channel for true safety.
*/
@MavlinkMessageInfo(
id = 7,
crc = 119,
description = "Emit an encrypted signature / key identifying this system. PLEASE NOTE: This protocol has been kept simple, so transmitting the key requires an encrypted channel for true safety."
)
public final class AuthKey {
private final String key;
private AuthKey(String key) {
this.key = key;
}
/**
* Returns a builder instance for this message.
*/
@MavlinkMessageBuilder
public static Builder builder() {
return new Builder();
}
/**
* key
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 1,
arraySize = 32,
description = "key"
)
public final String key() {
return this.key;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !getClass().equals(o.getClass())) return false;
AuthKey other = (AuthKey)o;
if (!Objects.deepEquals(key, other.key)) return false;
return true;
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + Objects.hashCode(key);
return result;
}
@Override
public String toString() {
return "AuthKey{key=" + key + "}";
}
public static final class Builder {
private String key;
/**
* key
*/
@MavlinkFieldInfo(
position = 1,
unitSize = 1,
arraySize = 32,
description = "key"
)
public final Builder key(String key) {
this.key = key;
return this;
}
public final AuthKey build() {
return new AuthKey(key);
}
}
}
|
<filename>magic_shop/components/order-item/index.js
import { GetSlashYMDHMS } from '../../utils/date'
// components/order-item/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
order: Object,
},
observers: {
order: function (order) {
if (!order) {
return
}
const OrderView = this.getOrderview(order)
this.setData({
OrderView,
})
},
},
/**
* 组件的初始数据
*/
data: {
OrderView: Object,
},
/**
* 组件的方法列表
*/
methods: {
getOrderview(order) {
const paid_time = GetSlashYMDHMS(order.placed_time)
const OrderView = {
paid_time,
title: order.snap_title,
order_no: order.order_no,
price: order.final_total_price,
count: order.total_count,
img: order.snap_img,
status: this.getStausTextByStatus(order.status),
}
return OrderView
},
getStausTextByStatus(status) {
if(status === 1){
return "未支付"
}
if(status === 2){
return "未发货"
}
if(status === 3){
return "已发货"
}
if(status === 4){
return "已完成"
}
},
},
})
|
#!/bin/sh
# Copyright (c) 2014-2015 The TavecchiacoinPay Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
set -e
UNSIGNED="$1"
SIGNATURE="$2"
ARCH=x86_64
ROOTDIR=dist
TEMPDIR=signed.temp
OUTDIR=signed-app
if [ -z "$UNSIGNED" ]; then
echo "usage: $0 <unsigned app> <signature>"
exit 1
fi
if [ -z "$SIGNATURE" ]; then
echo "usage: $0 <unsigned app> <signature>"
exit 1
fi
rm -rf ${TEMPDIR} && mkdir -p ${TEMPDIR}
tar -C ${TEMPDIR} -xf ${UNSIGNED}
cp -rf "${SIGNATURE}"/* ${TEMPDIR}
if [ -z "${PAGESTUFF}" ]; then
PAGESTUFF=${TEMPDIR}/pagestuff
fi
if [ -z "${CODESIGN_ALLOCATE}" ]; then
CODESIGN_ALLOCATE=${TEMPDIR}/codesign_allocate
fi
find ${TEMPDIR} -name "*.sign" | while read i; do
SIZE=`stat -c %s "${i}"`
TARGET_FILE="`echo "${i}" | sed 's/\.sign$//'`"
echo "Allocating space for the signature of size ${SIZE} in ${TARGET_FILE}"
${CODESIGN_ALLOCATE} -i "${TARGET_FILE}" -a ${ARCH} ${SIZE} -o "${i}.tmp"
OFFSET=`${PAGESTUFF} "${i}.tmp" -p | tail -2 | grep offset | sed 's/[^0-9]*//g'`
if [ -z ${QUIET} ]; then
echo "Attaching signature at offset ${OFFSET}"
fi
dd if="$i" of="${i}.tmp" bs=1 seek=${OFFSET} count=${SIZE} 2>/dev/null
mv "${i}.tmp" "${TARGET_FILE}"
rm "${i}"
echo "Success."
done
mv ${TEMPDIR}/${ROOTDIR} ${OUTDIR}
rm -rf ${TEMPDIR}
echo "Signed: ${OUTDIR}"
|
<gh_stars>0
/*
* aetree.h - AE Tree constructor and print functions.
* Copyright (C) Acorn Computers Ltd., 1988-1990.
* Copyright (C) Codemist Ltd., 1987-1992.
* Copyright (C) Advanced RISC Machines Limited, 1991-1992.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 15
* Checkin $Date$
* Revising $Author$
*/
#ifndef _aetree_h
#define _aetree_h
#ifndef _defs_LOADED
# include "defs.h"
#endif
/* NB: it is unclear that the TypeExpr creation fns should be in this */
/* mip file -- TypeExpr's are moving to being a cfe local (opaque) */
/* whose interface to mip is via mcrepoftype. */
#define mk_typevar() ((TypeExpr *)global_cons2(SU_Type, t_unknown, 0))
extern AEop tagbindsort(TagBinder *b);
extern Expr *mk_expr1(AEop op, TypeExpr *t, Expr *a1);
extern Expr *mk_expr2(AEop op, TypeExpr *t, Expr *a1, Expr *a2);
extern Expr *mk_exprlet(AEop op, TypeExpr *t, SynBindList *a1, Expr *a2);
extern Expr *mk_expr3(AEop op, TypeExpr *t, Expr *a1, Expr *a2, Expr *a3);
#ifdef EXTENSION_VALOF
extern Expr *mk_expr_valof(AEop op, TypeExpr *t, Cmd *c);
#endif
#ifdef TARGET_HAS_INLINE_ASSEMBLER
extern AsmInstr *mk_asminstr(void);
#endif
extern Expr *mk_exprwdot(AEop op, TypeExpr *t, Expr *a1, IPtr a2);
extern Expr *mk_exprbdot(AEop op, TypeExpr *t, Expr *a1, int32 a2, int32 a3,
int32 a4);
/* mkDeclRhsList is slowly dying in C++ (syntax aid only). */
extern DeclRhsList *mkDeclRhsList(Symstr *sv, TypeExpr *t, SET_BITMAP s);
extern TopDecl *mkTopDeclFnDef(AEop a, Binder *b, SynBindList *c,
Cmd *d, bool e);
extern TypeExpr *mk_typeexpr1(AEop op, TypeExpr *t, Expr *a1);
extern TypeExpr *mkTypeExprfn(AEop a, TypeExpr *b, SET_BITMAP s,
FormTypeList *c, const TypeExprFnAux *d);
extern TypeExpr *g_mkTypeExprfn(AEop a, TypeExpr *b, SET_BITMAP s,
FormTypeList *c, const TypeExprFnAux *d);
extern FormTypeList *mkFormTypeList(FormTypeList *ftcdr, Symstr *ftname,
TypeExpr *fttype, Expr *ftdefault);
extern FormTypeList *g_mkFormTypeList(FormTypeList *ftcdr, Symstr *ftname,
TypeExpr *fttype, Expr *ftdefault);
/* temporary home, pending demise... */
extern int32 evaluate(Expr *a);
extern Expr *globalize_int(int32 n);
extern FormTypeList *globalize_formals(FormTypeList *d);
/* globalize_typeexpr caches only basic types (including structs/typedefs) */
/* and pointers to things which are already cached. Tough ched arrays/fns */
extern TypeExpr *globalize_typeexpr(TypeExpr *t);
/* and this omits default argument values to avoid a redeclaration by a */
/* postponed class function definition */
extern TypeExpr *globalize_typeexpr_no_default_arg_vals(TypeExpr *t);
extern StringSegList *globalize_strseg(StringSegList *s);
extern Expr *globalize_expr(Expr *e);
extern ScopeSaver globalize_env(ScopeSaver env);
extern TypeExpr *clone_typeexpr(TypeExpr *t);
extern void aetree_init(void);
extern Cmd *mk_cmd_0(AEop op, FileLine x);
/* op = s_break,s_endcase,s_continue */
extern Cmd *mk_cmd_e(AEop op, FileLine x, Expr *e);
/* op = s_return,s_semicolon */
extern Cmd *mk_cmd_default(FileLine x, Cmd *c);
extern Cmd *mk_cmd_lab(AEop op, FileLine x, LabBind *b, Cmd *c);
extern Cmd *mk_cmd_block(FileLine x, SynBindList *bl, CmdList *cl);
extern Cmd *mk_cmd_do(FileLine x, Cmd *c, Expr *e);
extern Cmd *mk_cmd_if(FileLine x, Expr *e, Cmd *c1, Cmd *c2);
extern Cmd *mk_cmd_switch(FileLine x, Expr *e, Cmd *c1, Cmd *c2, Cmd *c3);
extern Cmd *mk_cmd_for(FileLine x, Expr *e1, Expr *e2, Expr *e3, Cmd *c);
extern Cmd *mk_cmd_case(FileLine x, Expr *e, Cmd *c1, Cmd *c2);
extern Cmd *mk_cmd_try(FileLine x, Cmd *body, Handler *handler_list, Cmd *exit);
extern bool is_fpzero(Expr const *e);
extern bool is_fpone(Expr const *e);
extern bool is_fpminusone(Expr const *e);
extern int32 result2;
extern bool integer_constant(Expr const *e);
extern bool is_intzero(Expr const *e);
extern bool is_intone(Expr const *e);
extern bool is_intminusone(Expr const *e);
extern bool resultinflags_fn(Expr *e);
extern void eprintf(char const *s, ...);
extern void pr_typeexpr(TypeExpr *x, Symstr *s);
extern void pr_stringsegs(StringSegList *z);
void pr_int64(int64 const *x);
extern void pr_expr(Expr *x);
extern void pr_exproftype(char const *s, Expr *x);
extern void pr_cmd(Cmd *c);
extern void pr_topdecl(TopDecl *x);
extern void pr_typeexpr_nl(TypeExpr *x, Symstr *s);
extern void pr_expr_nl(Expr *x);
#endif
/* end of aetree.h */
|
#!/bin/bash -e
# helper to create local APT repository includeing all package available in
# the docker images's local apt repo
if [ $# -ne 1 ]; then
echo "Call with: $(basename ${BASH_SOURCE[0]}) <path to local apt directory>" >&2
exit 1
fi
if [ ! -d $1 ]; then
echo "Please create target directory $1 before calling this script!" >&2
exit 1
fi
if [[ -n ${UID} && -n ${GID} ]]; then
addgroup --gid ${GID} --quiet docker-build
adduser --uid=${UID} --gid=${GID} --disabled-password --gecos '' --quiet docker-build
else
echo "UID/GID not set. Use docker run -e UID=$(id -u) -e GID=$(id -g)" >&2
exit 1
fi
# copy all Debian packages in local APT repo and create local APT repository
export HOME=$(echo ~docker-build)
sudo -E -u docker-build /bin/bash -c "\
cd $1 && if ls -A /opt/apt/*.deb >/dev/null 2>&1; then cp -a /opt/apt/. .; fi && \
apt-ftparchive packages . > Packages && \
apt-ftparchive sources . > Sources 2>/dev/null && \
(cat /opt/apt/.Release.header && apt-ftparchive release .) > Release"
|
<!DOCTYPE html>
<html>
<head>
<title>Form Test</title>
</head>
<body>
<form method="post">
<div>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
</div>
<div>
<label for="age">Age:</label>
<input type="number" name="age" id="age">
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
</body>
</html> |
#!/bin/bash
WORKDIR=`echo $0 | sed -e s/build.sh//`
cd ${WORKDIR}
docker build -t docker.io/sbueringer/squid:latest .
if [ "$TRAVIS_BRANCH" == "master" ] && [ ! -z "$DOCKER_USERNAME" ] && [ ! -z $DOCKER_PASSWORD ]
then
docker login -u "$DOCKER_USERNAME" -p "$DOCKER_PASSWORD"
docker push docker.io/sbueringer/squid:latest;
fi
|
use serialport::{SerialPort, SerialPortSettings, Error};
use std::time::Duration;
const SETTINGS: SerialPortSettings = SerialPortSettings {
baud_rate: 9600,
data_bits: serialport::DataBits::Eight,
flow_control: serialport::FlowControl::None,
parity: serialport::Parity::None,
stop_bits: serialport::StopBits::One,
timeout: Duration::from_secs(1),
};
fn main() {
let port_name = "/dev/ttyUSB0"; // Replace with the actual port name
match serialport::open(&port_name) {
Ok(mut port) => {
if let Err(err) = port.configure(&SETTINGS) {
println!("Failed to config port [{}] {:?}", port_name, err);
}
if let Err(err) = port.set_timeout(Duration::from_secs(1)) {
println!("Failed to set timeout [{}] {:?}", port_name, err);
}
}
Err(err) => {
println!("Failed to open port [{}] {:?}", port_name, err);
}
}
} |
<reponame>ingoha/TTGO-T-Wristband
const uint8_t Orbitron_Light5pt7bBitmaps[] PROGMEM = {
0x00, 0xFA, 0xC0, 0x12, 0x7F, 0x24, 0x24, 0xDE, 0x68, 0x48, 0x10, 0xFF,
0x91, 0x90, 0xFF, 0x11, 0x91, 0xFF, 0x10, 0xF0, 0xA4, 0x4F, 0x20, 0x30,
0x13, 0xC8, 0x94, 0x3C, 0x7E, 0x20, 0x90, 0x16, 0x08, 0xD4, 0x1B, 0xFE,
0x80, 0xEA, 0xAC, 0xD5, 0x5C, 0x27, 0xC8, 0xA0, 0x21, 0x3E, 0x40, 0xC0,
0xE0, 0x80, 0x08, 0x44, 0x44, 0x42, 0x00, 0xFF, 0x06, 0x3C, 0x9A, 0x38,
0x7F, 0x80, 0x74, 0x92, 0x48, 0xFF, 0x04, 0x0F, 0xF8, 0x10, 0x3F, 0x80,
0xFF, 0x01, 0x01, 0x3F, 0x01, 0x01, 0xFF, 0x0C, 0x38, 0x92, 0x2F, 0xE0,
0x81, 0x00, 0xFF, 0x02, 0x07, 0xF0, 0x30, 0x7F, 0x80, 0xFD, 0x02, 0x07,
0xF8, 0x30, 0x7F, 0x80, 0xFC, 0x10, 0x41, 0x04, 0x10, 0x40, 0xFF, 0x06,
0x0F, 0xF8, 0x30, 0x7F, 0x80, 0xFF, 0x06, 0x0F, 0xF0, 0x20, 0x7F, 0x80,
0x84, 0x86, 0x12, 0xCC, 0x21, 0xF8, 0x3E, 0x8C, 0x33, 0xC8, 0xFE, 0x04,
0x09, 0xF2, 0x00, 0x08, 0x00, 0xFF, 0x81, 0xBD, 0xA5, 0xBF, 0x80, 0xFF,
0xFF, 0x06, 0x0F, 0xF8, 0x30, 0x60, 0x80, 0xFF, 0x06, 0x0F, 0xF8, 0x30,
0x7F, 0x80, 0xFF, 0x02, 0x04, 0x08, 0x10, 0x3F, 0x80, 0xFF, 0x06, 0x0C,
0x18, 0x30, 0x7F, 0x80, 0xFF, 0x02, 0x07, 0xE8, 0x10, 0x3F, 0x80, 0xFF,
0x02, 0x07, 0xE8, 0x10, 0x20, 0x00, 0xFF, 0x02, 0x04, 0x78, 0x30, 0x7F,
0x80, 0x83, 0x06, 0x0F, 0xF8, 0x30, 0x60, 0x80, 0xFE, 0x02, 0x04, 0x08,
0x10, 0x30, 0x7F, 0x80, 0x83, 0x0A, 0x27, 0x88, 0x90, 0xA0, 0x80, 0x81,
0x02, 0x04, 0x08, 0x10, 0x3F, 0x80, 0x81, 0xC3, 0xA5, 0x99, 0x91, 0x81,
0x81, 0x83, 0x86, 0x8C, 0x98, 0xB0, 0xE0, 0x80, 0xFF, 0x06, 0x0C, 0x18,
0x30, 0x7F, 0x80, 0xFF, 0x06, 0x0F, 0xF8, 0x10, 0x20, 0x00, 0xFE, 0x82,
0x82, 0x82, 0x82, 0x82, 0xFF, 0xFF, 0x06, 0x0F, 0xF8, 0x90, 0xA0, 0x80,
0xFF, 0x02, 0x07, 0xF0, 0x20, 0x7F, 0x80, 0xFE, 0x20, 0x40, 0x81, 0x02,
0x04, 0x00, 0x83, 0x06, 0x0C, 0x18, 0x30, 0x7F, 0x80, 0xC0, 0xD0, 0x22,
0x10, 0x84, 0x12, 0x03, 0x00, 0xC0, 0x86, 0x28, 0xC5, 0x28, 0x94, 0xA2,
0x94, 0x63, 0x04, 0x20, 0xC3, 0x24, 0x18, 0x18, 0x18, 0x24, 0xC3, 0x82,
0x88, 0xA1, 0x41, 0x02, 0x04, 0x00, 0xFE, 0x08, 0x20, 0x86, 0x10, 0x3F,
0x80, 0xEA, 0xAC, 0x84, 0x10, 0x41, 0x04, 0x20, 0xD5, 0x5C, 0x00, 0xFE,
0x80, 0xFC, 0x10, 0x7F, 0x87, 0xF0, 0x82, 0x0F, 0xE1, 0x86, 0x18, 0x7F,
0xFE, 0x08, 0x20, 0x83, 0xF0, 0x04, 0x1F, 0xE1, 0x86, 0x18, 0x7F, 0xFE,
0x18, 0x7F, 0x83, 0xF0, 0xF8, 0xF8, 0x88, 0x88, 0xFE, 0x18, 0x61, 0x87,
0xF0, 0x5F, 0x82, 0x0F, 0xE1, 0x86, 0x18, 0x61, 0xBF, 0x10, 0x01, 0x11,
0x11, 0x11, 0xF0, 0x82, 0x08, 0xE2, 0x93, 0xC9, 0xA3, 0xAA, 0xAB, 0xFF,
0xE2, 0x18, 0x86, 0x21, 0x88, 0x62, 0x10, 0xFE, 0x18, 0x61, 0x86, 0x10,
0xFE, 0x18, 0x61, 0x87, 0xF0, 0xFE, 0x18, 0x61, 0x87, 0xF8, 0x20, 0xFE,
0x18, 0x61, 0x87, 0xF0, 0x41, 0xFC, 0x21, 0x08, 0x40, 0xFF, 0x02, 0x07,
0xF0, 0x3F, 0xC0, 0x88, 0xF8, 0x88, 0x8F, 0x86, 0x18, 0x61, 0x87, 0xF0,
0x83, 0x42, 0x44, 0x24, 0x18, 0x18, 0x84, 0x52, 0x94, 0xA4, 0xCE, 0x31,
0x8C, 0x40, 0xC4, 0xA1, 0x0C, 0x2B, 0x10, 0x83, 0x06, 0x0C, 0x18, 0x3F,
0xC0, 0x9F, 0xF8, 0x44, 0xC8, 0x7C, 0xEA, 0xAC, 0xFF, 0x80, 0xD5, 0x5C,
0xF0 };
const GFXglyph Orbitron_Light5pt7bGlyphs[] PROGMEM = {
{ 0, 1, 1, 3, 0, 0 }, // 0x20 ' '
{ 1, 1, 7, 2, 0, -6 }, // 0x21 '!'
{ 2, 2, 1, 4, 1, -6 }, // 0x22 '"'
{ 3, 8, 7, 8, 0, -6 }, // 0x23 '#'
{ 10, 8, 9, 8, 0, -7 }, // 0x24 '$'
{ 19, 10, 7, 11, 0, -6 }, // 0x25 '%'
{ 28, 9, 7, 10, 0, -6 }, // 0x26 '&'
{ 36, 1, 1, 2, 1, -6 }, // 0x27 '''
{ 37, 2, 7, 3, 0, -6 }, // 0x28 '('
{ 39, 2, 7, 3, 0, -6 }, // 0x29 ')'
{ 41, 5, 4, 5, 0, -6 }, // 0x2A '*'
{ 44, 5, 4, 4, 0, -4 }, // 0x2B '+'
{ 47, 1, 2, 2, 0, 0 }, // 0x2C ','
{ 48, 3, 1, 5, 1, -2 }, // 0x2D '-'
{ 49, 1, 1, 2, 0, 0 }, // 0x2E '.'
{ 50, 5, 7, 5, 0, -6 }, // 0x2F '/'
{ 55, 7, 7, 9, 1, -6 }, // 0x30 '0'
{ 62, 3, 7, 4, 0, -6 }, // 0x31 '1'
{ 65, 7, 7, 9, 1, -6 }, // 0x32 '2'
{ 72, 8, 7, 9, 0, -6 }, // 0x33 '3'
{ 79, 7, 7, 7, 0, -6 }, // 0x34 '4'
{ 86, 7, 7, 9, 1, -6 }, // 0x35 '5'
{ 93, 7, 7, 9, 1, -6 }, // 0x36 '6'
{ 100, 6, 7, 7, 0, -6 }, // 0x37 '7'
{ 106, 7, 7, 9, 1, -6 }, // 0x38 '8'
{ 113, 7, 7, 9, 1, -6 }, // 0x39 '9'
{ 120, 1, 6, 2, 0, -5 }, // 0x3A ':'
{ 121, 1, 7, 2, 0, -5 }, // 0x3B ';'
{ 122, 4, 6, 5, 0, -5 }, // 0x3C '<'
{ 125, 5, 3, 6, 1, -3 }, // 0x3D '='
{ 127, 4, 6, 5, 1, -5 }, // 0x3E '>'
{ 130, 7, 7, 8, 0, -6 }, // 0x3F '?'
{ 137, 8, 7, 9, 0, -6 }, // 0x40 '@'
{ 144, 7, 7, 9, 1, -6 }, // 0x41 'A'
{ 151, 7, 7, 9, 1, -6 }, // 0x42 'B'
{ 158, 7, 7, 8, 0, -6 }, // 0x43 'C'
{ 165, 7, 7, 9, 1, -6 }, // 0x44 'D'
{ 172, 7, 7, 8, 0, -6 }, // 0x45 'E'
{ 179, 7, 7, 7, 0, -6 }, // 0x46 'F'
{ 186, 7, 7, 9, 1, -6 }, // 0x47 'G'
{ 193, 7, 7, 9, 1, -6 }, // 0x48 'H'
{ 200, 1, 7, 2, 0, -6 }, // 0x49 'I'
{ 201, 7, 7, 8, 0, -6 }, // 0x4A 'J'
{ 208, 7, 7, 8, 0, -6 }, // 0x4B 'K'
{ 215, 7, 7, 8, 0, -6 }, // 0x4C 'L'
{ 222, 8, 7, 10, 1, -6 }, // 0x4D 'M'
{ 229, 7, 7, 9, 1, -6 }, // 0x4E 'N'
{ 236, 7, 7, 9, 1, -6 }, // 0x4F 'O'
{ 243, 7, 7, 9, 1, -6 }, // 0x50 'P'
{ 250, 8, 7, 9, 1, -6 }, // 0x51 'Q'
{ 257, 7, 7, 9, 1, -6 }, // 0x52 'R'
{ 264, 7, 7, 9, 1, -6 }, // 0x53 'S'
{ 271, 7, 7, 8, 0, -6 }, // 0x54 'T'
{ 278, 7, 7, 9, 1, -6 }, // 0x55 'U'
{ 285, 10, 7, 10, 0, -6 }, // 0x56 'V'
{ 294, 11, 7, 12, 0, -6 }, // 0x57 'W'
{ 304, 8, 7, 8, 0, -6 }, // 0x58 'X'
{ 311, 7, 7, 8, 0, -6 }, // 0x59 'Y'
{ 318, 7, 7, 8, 1, -6 }, // 0x5A 'Z'
{ 325, 2, 7, 3, 0, -6 }, // 0x5B '['
{ 327, 5, 7, 5, 0, -6 }, // 0x5C '\'
{ 332, 2, 7, 3, 0, -6 }, // 0x5D ']'
{ 334, 1, 1, 0, 0, 0 }, // 0x5E '^'
{ 335, 7, 1, 8, 1, 1 }, // 0x5F '_'
{ 336, 1, 1, 2, 0, -9 }, // 0x60 '`'
{ 337, 6, 6, 8, 1, -5 }, // 0x61 'a'
{ 342, 6, 8, 8, 1, -7 }, // 0x62 'b'
{ 348, 6, 6, 7, 0, -5 }, // 0x63 'c'
{ 353, 6, 8, 7, 0, -7 }, // 0x64 'd'
{ 359, 6, 6, 8, 1, -5 }, // 0x65 'e'
{ 364, 4, 8, 4, 0, -7 }, // 0x66 'f'
{ 368, 6, 8, 7, 0, -5 }, // 0x67 'g'
{ 374, 6, 8, 8, 1, -7 }, // 0x68 'h'
{ 380, 1, 8, 2, 0, -7 }, // 0x69 'i'
{ 381, 4, 11, 3, -2, -7 }, // 0x6A 'j'
{ 387, 6, 8, 6, 0, -7 }, // 0x6B 'k'
{ 393, 2, 8, 3, 0, -7 }, // 0x6C 'l'
{ 395, 10, 6, 11, 0, -5 }, // 0x6D 'm'
{ 403, 6, 6, 8, 1, -5 }, // 0x6E 'n'
{ 408, 6, 6, 8, 1, -5 }, // 0x6F 'o'
{ 413, 6, 8, 8, 1, -5 }, // 0x70 'p'
{ 419, 6, 8, 7, 0, -5 }, // 0x71 'q'
{ 425, 5, 6, 5, 0, -5 }, // 0x72 'r'
{ 429, 7, 6, 8, 0, -5 }, // 0x73 's'
{ 435, 4, 8, 4, 0, -7 }, // 0x74 't'
{ 439, 6, 6, 8, 1, -5 }, // 0x75 'u'
{ 444, 8, 6, 8, 0, -5 }, // 0x76 'v'
{ 450, 10, 6, 11, 0, -5 }, // 0x77 'w'
{ 458, 6, 6, 7, 0, -5 }, // 0x78 'x'
{ 463, 7, 8, 8, 0, -5 }, // 0x79 'y'
{ 470, 5, 6, 7, 1, -5 }, // 0x7A 'z'
{ 474, 2, 7, 3, 0, -6 }, // 0x7B '{'
{ 476, 1, 9, 2, 0, -7 }, // 0x7C '|'
{ 478, 2, 7, 3, 0, -6 }, // 0x7D '}'
{ 480, 4, 1, 4, 0, -2 } }; // 0x7E '~'
const GFXfont Orbitron_Light5pt7b PROGMEM = {
(uint8_t *)Orbitron_Light5pt7bBitmaps,
(GFXglyph *)Orbitron_Light5pt7bGlyphs,
0x20, 0x7E, 10 };
// Approx. 1153 bytes
|
#!/bin/bash
# Written by: Adam Simpkin
# Date: 18 May 2017
#
# This script is an example of how to run the contaminant
# search in SIMBAD. Various command line flags could be set
# but below's example is the most basic usage and illustrates
# its purporse.
simbad-contaminant \
-nproc 4 \
-organism CHICK \
input/2fbb.mtz
|
package com.ibm.socialcrm.notesintegration.connector.util;
/****************************************************************
* IBM OpenSource
*
* (C) Copyright IBM Corp. 2012
*
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
***************************************************************/
import com.ibm.socialcrm.notesintegration.utils.ConstantStrings;
import com.ibm.socialcrm.notesintegration.utils.UtilsPlugin;
import com.ibm.socialcrm.notesintegration.utils.UtilsPluginNLSKeys;
/*
* Mainly used to assemble/disassmble a special drop down list line for the "Items" field in the
* Copy To dialog (AssociateComposite.java). Specifically, this is the special line when there are
* multiple Account items of the same Account name, and when the count is greater than the max
* (specified in NotesDocumentSugaritems.MAX_ACCOUNT_LINES)
*/
public class AccountRedirectObj {
private String _accountName = null;
private int _matchCount = 0;
private String _matchString = ConstantStrings.EMPTY_STRING;
private String _redirectString = UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.UI_ASSOCIATE_REDIRECT_TEXT);
private String _assembledMessageText = null;
private boolean _isRedirect = true;
// assemble the redirect text in drop down list
AccountRedirectObj(String a, int m) {
_accountName = a;
_matchCount = m;
setMatchString();
}
// disassemble the redirect text, mainly to get the account name
public AccountRedirectObj(String s) {
_assembledMessageText = s;
disassembleText();
}
private void disassembleText() {
if (_assembledMessageText != null && _assembledMessageText.indexOf(_redirectString) > -1) {
_isRedirect = true;
String tempText = _assembledMessageText.substring(0, _assembledMessageText.length() - _redirectString.length());
if (tempText.lastIndexOf(ConstantStrings.DASH) > -1) {
tempText = tempText.substring(0, tempText.lastIndexOf(ConstantStrings.DASH));
_accountName = tempText.trim();
}
} else {
_isRedirect = false;
}
}
public String getAccountName() {
return _accountName;
}
public int getMatchCount() {
return _matchCount;
}
private String getMatchString() {
return _matchString;
}
private void setMatchString() {
if (_matchCount > DocumentSugarItems.MAX_ACCOUNT_RESULTLIMIT) {
_matchString = UtilsPlugin.getDefault().getResourceString(UtilsPluginNLSKeys.UI_ASSOCIATE_MATCH_COUNT, new String[] { String.valueOf(_matchCount) });
}
}
private String getRedirectString() {
return _redirectString;
}
public boolean isRedirect() {
return _isRedirect;
}
public String getText() {
StringBuffer sb = new StringBuffer(ConstantStrings.EMPTY_STRING);
sb.append(getAccountName()).append(ConstantStrings.SPACE).append(getMatchString());
sb.append(ConstantStrings.SPACE).append(getRedirectString());
_assembledMessageText = sb.toString();
return _assembledMessageText;
}
}
|
#!/bin/bash
#Jill E. Moore
#Weng Lab
#UMass Medical School
#December 2020
data=$1
workingDir=~/Lab/Luban-Collaboration/Clean
genome=~/Lab/Reference/Human/hg38/HISAT2/genome
cd $workingDir
echo "Mapping ..."
~/bin/hisat2-2.2.1/hisat2 -p 16 -x $genome -1 $data.1.P.fq -2 $data.2.P.fq -S $data.sam
echo "Coverting from sam to bam ..."
samtools view -bS $data.sam -o $data.unsorted.bam
echo "Sorting bam ..."
samtools sort -@ 16 -o $data.bam $data.unsorted.bam
echo "Indexing bam ..."
samtools index $data.bam
mv *sam *bam* ../Mapped
|
package io.opensphere.core.viewer.impl;
import java.util.Collection;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.log4j.Logger;
import io.opensphere.core.Notify;
import io.opensphere.core.Notify.Method;
import io.opensphere.core.math.DefaultEllipsoid;
import io.opensphere.core.math.Ellipsoid;
import io.opensphere.core.math.Matrix3d;
import io.opensphere.core.math.Matrix4d;
import io.opensphere.core.math.MutableVector3d;
import io.opensphere.core.math.Plane;
import io.opensphere.core.math.Quaternion;
import io.opensphere.core.math.Ray3d;
import io.opensphere.core.math.RectangularCylinder;
import io.opensphere.core.math.Shape;
import io.opensphere.core.math.Sphere;
import io.opensphere.core.math.Vector2i;
import io.opensphere.core.math.Vector3d;
import io.opensphere.core.math.WGS84EarthConstants;
import io.opensphere.core.model.Altitude.ReferenceLevel;
import io.opensphere.core.model.GeographicPosition;
import io.opensphere.core.model.LatLonAlt;
import io.opensphere.core.model.ScreenPosition;
import io.opensphere.core.preferences.PreferenceChangeListener;
import io.opensphere.core.projection.AbstractGeographicProjection;
import io.opensphere.core.projection.Projection;
import io.opensphere.core.projection.ProjectionChangeSupport.ProjectionChangeListener;
import io.opensphere.core.util.MathUtil;
import io.opensphere.core.util.TerrainUtil;
import io.opensphere.core.util.lang.EqualsHelper;
import io.opensphere.core.util.lang.ExpectedCloneableException;
import io.opensphere.core.util.lang.StringUtilities;
import io.opensphere.core.viewer.ViewChangeSupport;
import io.opensphere.core.viewer.Viewer;
/**
* A viewer which views a scene in three dimensions.
*/
@SuppressWarnings("PMD.GodClass")
public class Viewer3D extends AbstractDynamicViewer
{
/** A preference key for the viewer position. */
public static final String POSITION_PREF_KEY = "Viewer3D.position";
/** Tolerance for the viewer's position with respect to the terrain. */
public static final double TERRAIN_SAFETY_TOLERANCE = -0.00001;
/** Logger reference. */
private static final Logger LOGGER = Logger.getLogger(Viewer3D.class);
/** The maximum distance from the origin constant. */
private static final double ourMaxOriginDistance = 2000000000.;
/**
* The number of radians to add to the top clipping planes rotation
* calculation.
*/
private static final double ourTopClipIncreaseAngle = .2;
/**
* The maximum amount of degrees we allow the camera to move when zoomed in.
*/
private static final double ourZoomedInDegreeTolerance = .03;
/** The aspect ration. */
private volatile double myAspectRatio = 1.;
/** Bottom clipping plane. */
private final Plane myBottomClip = new Plane();
/** The half view angle x component. */
private volatile double myHalfFOVx = MathUtil.QUARTER_PI * 0.5;
/** The half view angle y component. */
private volatile double myHalfFOVy = myHalfFOVx;
/** The left clipping plane. */
private final Plane myLeftClip = new Plane();
/** The map context. */
private MapContext<DynamicViewer> myMapContext;
/** The model which I view. */
private Shape myModel = new DefaultEllipsoid(WGS84EarthConstants.RADIUS_EQUATORIAL_M, WGS84EarthConstants.RADIUS_EQUATORIAL_M,
WGS84EarthConstants.RADIUS_POLAR_M);
/** The model view matrix. */
private float[] myModelViewMatrix;
/** The position and orientation of the viewer. */
private final ViewerPosition3D myPosition = new ViewerPosition3D();
/** Listener for preference changes. */
private final PreferenceChangeListener myPreferenceChangeListener = evt ->
{
if (evt.getSource() != Viewer3D.this)
{
setPosition(getPreferences().getJAXBObject(ViewerPosition3D.class, POSITION_PREF_KEY, new ViewerPosition3D()));
}
};
/** Listener for projection changes. */
private final ProjectionChangeListener myProjectionChangeListener = evt -> resetProjectionMatrixClipped();
/** The projection matrix. */
private float[] myProjectionMatrix;
/**
* The clipped projection matrix that maximizes depth buffer precision. This
* one is clipped at twice the distance from the viewer position to the
* origin.
*/
private float[] myProjectionMatrixClipped;
/**
* The clipped projection matrix that maximizes depth buffer precision. This
* one is clipped at the origin.
*/
private float[] myProjectionMatrixClippedFarToCenter;
/** The right clipping plane. */
private final Plane myRightClip = new Plane();
/** The max angle by which to spin. */
private final double mySpinAngleLimit = Math.toRadians(7);
/** The top clipping plane. */
private final Plane myTopClip = new Plane();
/**
* Construct me.
*
* @param builder builder with construction parameters.
*/
public Viewer3D(Builder builder)
{
this(builder, true);
}
/**
* Construct me.
*
* @param builder builder with construction parameters.
* @param displayedViewer True if this user is used to display to the monitor, false if it is used
* to render somewhere else such as frame buffers/textures.
*/
public Viewer3D(Builder builder, boolean displayedViewer)
{
super(builder, displayedViewer);
addTrajectoryGenerator(TrajectoryGeneratorType.ARC, new ArcTrajectoryGenerator3D(this));
addTrajectoryGenerator(TrajectoryGeneratorType.ROTATION, new RotationTrajectoryGenerator3D());
addTrajectoryGenerator(TrajectoryGeneratorType.FLAT, new FlatTrajectoryGenerator3D(this));
resetClipPlanes();
if (getPreferences() != null)
{
getPreferences().addPreferenceChangeListener(POSITION_PREF_KEY, myPreferenceChangeListener);
}
}
@Override
public synchronized float[] getAdjustedModelViewMatrix(Matrix4d adjustment)
{
if (myModelViewMatrix == null)
{
resetModelViewMatrix();
}
return new Matrix4d(getModelViewMatrix()).mult(adjustment).toFloatArray();
}
@Override
public double getAltitude()
{
// Using closest model position to account for pitching of earth.
return myPosition.getLocation().subtract(getClosestModelPosition()).getLength();
}
/**
* Get the bottomClip.
*
* @return the bottomClip
*/
public Plane getBottomClip()
{
return myBottomClip;
}
@Override
public KMLCompatibleCamera getCamera(ViewerPosition position)
{
if (!(position instanceof ViewerPosition3D))
{
throw new UnsupportedOperationException("3D viewer cannot create a camera for a non-3D position.");
}
Projection proj = getMapContext().getProjection(Viewer3D.class);
if (!(proj instanceof AbstractGeographicProjection))
{
throw new UnsupportedOperationException(
"Cannot create viewer postion from geographic position for non-geographic projection.");
}
ViewerPosition3D position3D = (ViewerPosition3D)position;
GeographicPosition location = proj.convertToPosition(position3D.getLocation(), ReferenceLevel.ELLIPSOID);
Vector3d posToOrigin = position3D.getLocation().multiply(-1.).getNormalized();
double roll;
double tilt;
ViewerPosition3D untilted;
/* If there is no tilt (the viewer direction is directly at the model
* origin), then there can only be heading. If this viewer was created
* from a KML camera which specified either roll or a combination of
* roll and heading this will result in a KML definition which does not
* contain the same values, but is equivalent. */
if (MathUtil.isZero(1. - Math.abs(position3D.getDir().dot(posToOrigin))))
{
roll = 0.;
tilt = 0.;
untilted = position3D;
}
else
{
/* Get the roll. This operation rotates around the viewer's z-axis
* my moving the viewer's y-axis so that the model's origin is
* coplanar to the viewer's y-z plane. */
ViewerPosition3D unrolled = new ViewerPosition3D(position3D.getLocation(), position3D.getDir(),
position3D.getLocation());
roll = unrolled.getUp().getAngleUnit(position3D.getUp(), position3D.getDir()) * MathUtil.RAD_TO_DEG;
/* Get the tilt. This operation points the viewer's direction at the
* model's origin. When the tilt is more than 90 or less than -90 we
* need to reverse the unrolled view position's y-axis. */
if (0. > Math.signum(unrolled.getDir().dot(posToOrigin)))
{
untilted = new ViewerPosition3D(unrolled.getLocation(), posToOrigin, unrolled.getUp().multiply(-1));
}
else
{
untilted = new ViewerPosition3D(unrolled.getLocation(), posToOrigin, unrolled.getUp());
}
tilt = untilted.getDir().getAngleUnit(unrolled.getDir(), unrolled.getRight()) * MathUtil.RAD_TO_DEG;
}
/* Get the heading. This operation puts view righted? */
ViewerPosition3D righted = new ViewerPosition3D(untilted.getLocation(), untilted.getDir(), new Vector3d(0., 0., 1.));
double heading = righted.getUp().getAngleUnit(untilted.getUp(), untilted.getDir()) * MathUtil.RAD_TO_DEG;
return new KMLCompatibleCamera(location.getLatLonAlt(), heading, tilt, roll);
}
@Override
public ViewerPosition3D getCenteredView(Vector3d position)
{
ViewerPosition3D righted = getRightedView(position);
Vector3d altAdjustedLoc = righted.getLocation().getNormalized().multiply(myPosition.getLocation().getLength());
return new ViewerPosition3D(altAdjustedLoc, righted.getDir(), righted.getUp());
}
@Override
public ViewerPosition getCenteredView(Vector3d position, Vector3d centroidHint)
{
if (centroidHint == null || position.dot(centroidHint) > 0.)
{
return getCenteredView(position);
}
return getCenteredView(position.multiply(-1));
}
@Override
public Vector3d getClosestModelPosition()
{
Vector3d loc = myPosition.getLocation();
return myModel.getIntersection(new Ray3d(loc, loc.multiply(-1.).getNormalized()));
}
@Override
public double getHeading()
{
return myModel.getMapOrientationHeading(myPosition.getDir(), myPosition.getUp());
}
/**
* Get the horizontal field-of-view in radians.
*
* @return The field-of-view.
*/
public double getHorizontalFOV()
{
return myHalfFOVx * 2.;
}
/**
* Get the leftClip.
*
* @return the leftClip
*/
public Plane getLeftClip()
{
return myLeftClip;
}
@Override
public MapContext<DynamicViewer> getMapContext()
{
return myMapContext;
}
/**
* Get the model.
*
* @return the model
*/
public Shape getModel()
{
return myModel;
}
@Override
public Vector3d getModelIntersection()
{
return myModel.getIntersection(new Ray3d(myPosition.getLocation(), myPosition.getDir()));
}
/**
* Get the point on the model which is in view at the given screen location.
*
* @param screenLoc Screen location.
* @return model position.
*/
public Vector3d getModelIntersection(Vector2i screenLoc)
{
ScreenPosition ul = getViewOffset();
int viewportHeight = getViewportHeight();
int correctedX = (int)(screenLoc.getX() - ul.getX());
int correctedY = (int)(viewportHeight - screenLoc.getY() - ul.getY());
Vector2i correctedScreenLoc = new Vector2i(correctedX, correctedY);
return windowToModelCoords(correctedScreenLoc);
}
@Override
public synchronized float[] getModelViewMatrix()
{
if (myModelViewMatrix == null)
{
resetModelViewMatrix();
}
return myModelViewMatrix.clone();
}
@Override
public double getPitch()
{
// Find pitch by finding angle between model intersection and plane
// normal to direction.
// Pitch is then 90 degrees minus this angle value.
Vector3d modelIntersect = getModelIntersection();
if (modelIntersect == null)
{
return 0;
}
modelIntersect = modelIntersect.getNormalized();
Vector3d projectedIntersect = Plane.unitProjection(myPosition.getDir().multiply(-1), modelIntersect).getNormalized();
// Now calculate angle between vectors (and keep sign)
Vector3d orthogonal = myPosition.getRight().multiply(-1);
Vector3d cross = modelIntersect.cross(projectedIntersect);
double dot = modelIntersect.dot(projectedIntersect);
double resultAngle = Math.atan2(orthogonal.dot(cross), dot);
double ninetyDegrees = Math.toRadians(90);
return Math.signum(resultAngle) < 0 ? -1 * (ninetyDegrees - Math.abs(resultAngle)) : ninetyDegrees - resultAngle;
}
@Override
public double getPixelWidth(Ellipsoid ellipsoid)
{
double modelSize;
if (ellipsoid instanceof Sphere)
{
modelSize = ((Sphere)ellipsoid).getRadius() * 2.;
}
else
{
modelSize = ellipsoid.getXAxis().getLength() * 2.;
}
double pctOfView = modelSize / getViewVolumeWidthAt(ellipsoid.getCenter());
return pctOfView * getViewportWidth();
}
@Override
public ViewerPosition3D getPosition()
{
return myPosition;
}
@Override
public float[] getProjectionMatrix()
{
synchronized (this)
{
if (myProjectionMatrix == null)
{
resetProjectionMatrix();
}
return myProjectionMatrix.clone();
}
}
@Override
public float[] getProjectionMatrixClipped(boolean clipFarToCenter)
{
synchronized (this)
{
if (clipFarToCenter)
{
if (myProjectionMatrixClippedFarToCenter == null)
{
myProjectionMatrixClippedFarToCenter = generateProjectionMatrixClipped(true);
}
return myProjectionMatrixClippedFarToCenter.clone();
}
if (myProjectionMatrixClipped == null)
{
myProjectionMatrixClipped = generateProjectionMatrixClipped(false);
}
return myProjectionMatrixClipped.clone();
}
}
@Override
public RectangularCylinder getRectifyBounds(Collection<? extends Vector3d> modelPoints)
{
RectangularCylinder cardinalBounds = new RectangularCylinder(modelPoints);
ViewerPosition3D centeredView = getCenteredView(cardinalBounds.getCenter());
Vector3d[] axes = centeredView.getAxes();
return new RectangularCylinder(modelPoints, axes[0], axes[1], axes[2]);
}
/**
* Get the rightClip.
*
* @return the rightClip
*/
public Plane getRightClip()
{
return myRightClip;
}
@Override
public ViewerPosition3D getRightedView(Vector3d location)
{
ViewerPosition3D pos = new ViewerPosition3D();
Vector3d dir = location.multiply(-1.).getNormalized();
Vector3d up = Vector3d.UNIT_Z;
pos.setPosition(location, dir, up);
return pos;
}
@Override
public ViewerPosition3D getRightedView(ViewerPosition position)
{
if (position instanceof ViewerPosition3D)
{
return getRightedView(position.getLocation());
}
return null;
}
@Override
public ViewerPosition3D getRightedViewAtIntersection(ViewerPosition position)
{
ViewerPosition3D pos = new ViewerPosition3D();
Projection snapshot = myMapContext.getProjection();
Vector3d intersect = snapshot
.getTerrainIntersection(new Ray3d(position.getLocation(), ((ViewerPosition3D)position).getDir()), this);
if (intersect == null)
{
intersect = snapshot.getTerrainIntersection(
new Ray3d(position.getLocation(), ((ViewerPosition3D)position).getLocation().multiply(-1.)), this);
}
if (intersect == null)
{
Vector3d dir = position.getLocation().multiply(-1.);
Vector3d up = Vector3d.UNIT_Z;
pos.setPosition(position.getLocation(), dir, up);
}
else
{
double height = intersect.getLength() + intersect.subtract(position.getLocation()).getLength();
Vector3d intersectNormal = intersect.getNormalized();
Vector3d location = intersectNormal.multiply(height);
Vector3d up = Vector3d.UNIT_Z;
Vector3d dir = intersectNormal.multiply(-1.);
pos.setPosition(location, dir, up);
}
return pos;
}
/**
* Create a new viewer position which is the given position spun about an
* axis of rotation.
*
* @param angleRads The amount to spin the viewer position in radians.
* @param spinAxis The axis about which to spin the viewer position.
* @param limitAngle When true, the angle will be limited to a pre-defined
* maximum.
* @param position The position to spin.
* @return The newly created viewer position.
*/
public ViewerPosition3D getSpinOnAxisPosition(double angleRads, Vector3d spinAxis, boolean limitAngle,
ViewerPosition3D position)
{
double ang = limitAngle ? Math.min(angleRads, mySpinAngleLimit) : angleRads;
if (Double.isNaN(ang))
{
return null;
}
Matrix3d rotMat = new Matrix3d();
rotMat.fromAngleNormalAxis(ang, spinAxis);
Vector3d pos = rotMat.mult(position.getLocation());
Vector3d dir = rotMat.mult(position.getDir());
Vector3d up = rotMat.mult(position.getUp());
return new ViewerPosition3D(pos, dir, up);
}
@Override
public Vector3d getTerrainIntersection()
{
return myMapContext.getProjection().getTerrainIntersection(new Ray3d(myPosition.getLocation(), myPosition.getDir()),
this);
}
@Override
public Vector3d getTerrainIntersection(Vector2i screenLoc)
{
ScreenPosition ul = getViewOffset();
int viewportHeight = getViewportHeight();
int correctedX = (int)(screenLoc.getX() - ul.getX());
int correctedY = (int)(viewportHeight - screenLoc.getY() - ul.getY());
Vector2i correctedScreenLoc = new Vector2i(correctedX, correctedY);
Vector3d model = super.windowToModelCoords(correctedScreenLoc);
Vector3d lookAt = model.subtract(myPosition.getLocation());
return myMapContext.getProjection().getTerrainIntersection(new Ray3d(myPosition.getLocation(), lookAt), this);
}
/**
* Get the topClip.
*
* @return the topClip
*/
public Plane getTopClip()
{
return myTopClip;
}
/**
* Get the vertical field-of-view in radians.
*
* @return The field-of-view.
*/
public double getVerticalFOV()
{
return myHalfFOVy * 2.;
}
@Override
public ViewerPosition3D getViewerPosition(KMLCompatibleCamera camera)
{
Projection proj = getMapContext().getProjection(Viewer3D.class);
if (!(proj instanceof AbstractGeographicProjection))
{
throw new UnsupportedOperationException(
"Cannot create viewer postion from geographic position for non-geographic projection.");
}
Vector3d modelPosition = proj.convertToModel(new GeographicPosition(camera.getLocation()), Vector3d.ORIGIN);
ViewerPosition3D viewPosition = getRightedView(modelPosition);
// Heading - Z rotation
Matrix3d rotation = new Matrix3d();
rotation.fromAngleNormalAxis(camera.getHeading() * MathUtil.DEG_TO_RAD, viewPosition.getDir());
Vector3d up = rotation.mult(viewPosition.getUp());
viewPosition.setPosition(viewPosition.getLocation(), viewPosition.getDir(), up);
// Tilt - X rotation
rotation.fromAngleAxis(camera.getTilt() * MathUtil.DEG_TO_RAD, viewPosition.getRight());
Vector3d dir = rotation.mult(viewPosition.getDir());
up = rotation.mult(viewPosition.getUp());
viewPosition.setPosition(viewPosition.getLocation(), dir, up);
// Roll - Z rotation again
rotation.fromAngleNormalAxis(camera.getRoll() * MathUtil.DEG_TO_RAD, viewPosition.getDir());
up = rotation.mult(viewPosition.getUp());
viewPosition.setPosition(viewPosition.getLocation(), viewPosition.getDir(), up);
return viewPosition;
}
@Override
public double getViewLength(Vector3d ptA, Vector3d ptB)
{
Vector3d vToA = ptA.subtract(myPosition.getLocation()).getNormalized();
Vector3d vToB = ptB.subtract(myPosition.getLocation()).getNormalized();
double dot = MathUtil.clamp(vToA.dot(vToB), -1., 1.);
double angle = Math.abs(Math.acos(dot));
return getViewportHeight() * angle / myHalfFOVy * 0.5;
}
@Override
public double getViewVolumeWidthAt(Vector3d modelPosition)
{
// The tangent of the field of view angle * distance will give the
// view width at the distance.
double tanHalfAngle = Math.tan(myHalfFOVx * 2.);
double distance = modelPosition.distance(myPosition.getLocation());
return distance * tanHalfAngle;
}
@Override
public double getViewVolumeWidthAtIntersection()
{
Vector3d modelIntersect = myModel.getIntersection(new Ray3d(myPosition.getLocation(), myPosition.getDir()));
return getViewVolumeWidthAt(modelIntersect);
}
@Override
public ViewerPosition3D getZoomToFitView(RectangularCylinder bounds)
{
Vector3d center = bounds.getCenter();
ViewerPosition3D centeredView = getCenteredView(center);
// Zoom to to fit the bounds.
double xSpan = bounds.getSpan(centeredView.getRight());
double ySpan = bounds.getSpan(centeredView.getUp());
double dist1 = xSpan / Math.tan(myHalfFOVx) * .5;
double dist2 = ySpan / Math.tan(myHalfFOVy) * .5;
double distance = Math.max(dist1, dist2);
Vector3d pos = center.add(centeredView.getDir().multiply(-distance));
return new ViewerPosition3D(pos, centeredView.getDir(), centeredView.getUp());
}
@Override
public ViewerPosition getZoomToFitView(RectangularCylinder bounds, Vector3d centroidHint)
{
if (centroidHint == null || bounds.getCenter().dot(centroidHint) > 0.)
{
return getZoomToFitView(bounds);
}
ViewerPosition3D centeredView = getCenteredView(centroidHint);
double halfSpan = getModel().getBoundingRadius();
// Do not divide by 2 since we are only using half the span.
double distance = halfSpan / Math.tan(myHalfFOVx);
Vector3d pos = centroidHint.add(centeredView.getDir().multiply(-distance));
return new ViewerPosition3D(pos, centeredView.getDir(), centeredView.getUp());
}
@Override
@SuppressWarnings("PMD.GuardLogStatement")
public boolean isInView(Ellipsoid ellipsoid, double cullCosine)
{
if (LOGGER.isTraceEnabled())
{
LOGGER.trace(StringUtilities.concat("Testing inView for ellipsoid [", ellipsoid, "] cullCosine [",
Double.valueOf(cullCosine), "]"));
}
if (isInView(ellipsoid.getCenter(), 0.))
{
LOGGER.trace("inView center is in view");
return true;
}
Vector3d localTopNormal = ellipsoid.normalToLocal(myTopClip.getNormal()).getNormalized();
Vector3d topEllipsePoint = ellipsoid.localToModel(localTopNormal);
if (!myTopClip.isInFront(topEllipsePoint, 0.))
{
LOGGER.trace("not in front topClip");
return false;
}
Vector3d localBottomNormal = ellipsoid.normalToLocal(myBottomClip.getNormal()).getNormalized();
Vector3d bottomEllipsePoint = ellipsoid.localToModel(localBottomNormal);
if (!myBottomClip.isInFront(bottomEllipsePoint, 0.))
{
LOGGER.trace("not in front bottomClip");
return false;
}
Vector3d localLeftNormal = ellipsoid.normalToLocal(myLeftClip.getNormal()).getNormalized();
Vector3d leftEllipsePoint = ellipsoid.localToModel(localLeftNormal);
if (!myLeftClip.isInFront(leftEllipsePoint, 0.))
{
LOGGER.trace("not in front leftClip");
return false;
}
Vector3d localRightNormal = ellipsoid.normalToLocal(myRightClip.getNormal()).getNormalized();
Vector3d rightEllipsePoint = ellipsoid.localToModel(localRightNormal);
if (!myRightClip.isInFront(rightEllipsePoint, 0.))
{
LOGGER.trace("not in front rightClip");
return false;
}
if (myTopClip.hasIntersection(topEllipsePoint, bottomEllipsePoint)
|| myBottomClip.hasIntersection(topEllipsePoint, bottomEllipsePoint)
|| myRightClip.hasIntersection(leftEllipsePoint, rightEllipsePoint)
|| myLeftClip.hasIntersection(leftEllipsePoint, rightEllipsePoint))
{
LOGGER.trace("inView intersects frustrum");
return true;
}
if (cullCosine < 1. && ellipsoid.getZAxis().getNormalized().dot(getPosition().getDir()) > cullCosine)
{
LOGGER.trace("culled");
return false;
}
LOGGER.trace("inView");
return true;
}
@Override
public boolean isInView(Vector3d point, double radius)
{
// if it is in front of all of the clip planes, then it is in the view
// volume
if (myLeftClip.isInFront(point, radius) && myRightClip.isInFront(point, radius) && myTopClip.isInFront(point, radius)
&& myBottomClip.isInFront(point, radius))
{
Plane earthBisector = new Plane(Vector3d.ORIGIN, myPosition.getLocation());
if (earthBisector.isInFront(point, radius))
{
return true;
}
}
return false;
}
/** Set the field of view back to the default value. */
public synchronized void resetFOV()
{
setFOV(Math.toDegrees(MathUtil.QUARTER_PI));
}
@Override
public void resetView()
{
setPosition(getRightedViewAtIntersection(myPosition));
}
/**
* Determine the vector which points from the viewer position to the given
* screen position.
*
* @param pos screen position
* @return Vector pointing at the screen position
*/
public Vector3d screenToModelPointVector(Vector2i pos)
{
double adjustedX = pos.getX() - getViewOffset().getX();
double adjustedY = pos.getY() - getViewOffset().getY();
// get the percentage of the screen for the positions
// then use that to get the angles off of the viewer
// Intersect those with the earth to get the actual selection points.
double fromXpct = adjustedX / getViewportWidth() - 0.5;
double fromYpct = adjustedY / getViewportHeight() - 0.5;
double fromXAngleChange = -fromXpct * myHalfFOVx * 2.;
double fromYAngleChange = -fromYpct * myHalfFOVy * 2.;
return rotateDir(fromXAngleChange, fromYAngleChange).getNormalized();
}
@Override
public void setCenteredView(Viewer viewer)
{
// Set this viewer to have the same direction, up, and right, but set
// the position so that the viewer points at the origin and maintains
// the same distance.
if (viewer instanceof Viewer3D)
{
Viewer3D v3d = (Viewer3D)viewer;
double dist = myPosition.getLocation().getLength();
Vector3d pos = v3d.getPosition().getDir().multiply(-dist);
ViewerPosition3D viewerPosition = new ViewerPosition3D(pos, v3d.getPosition().getDir(), v3d.getPosition().getUp());
setPosition(viewerPosition);
}
}
/**
* Set the field of view.
*
* @param fov field of view to set.
*/
public synchronized void setFOV(double fov)
{
double halfx = Math.toRadians(fov) * 0.5;
if (!MathUtil.isZero(myHalfFOVx - halfx))
{
myHalfFOVx = halfx;
myHalfFOVy = Math.atan(Math.tan(myHalfFOVx) / myAspectRatio);
resetProjectionMatrix();
}
}
@Override
public void setMapContext(MapContext<DynamicViewer> context)
{
myMapContext = context;
myMapContext.getProjectionChangeSupport().addProjectionChangeListener(myProjectionChangeListener);
}
/**
* Set the model.
*
* @param model the model to set
*/
public void setModel(Shape model)
{
myModel = model;
}
@Override
public void setPosition(ViewerPosition viewerPosition)
{
if (viewerPosition instanceof ViewerPosition3D)
{
ViewerPosition3D pos = (ViewerPosition3D)viewerPosition;
myPosition.setPosition(pos.getLocation(), pos.getDir(), pos.getUp(), pos.getGeoPosition());
viewChanged();
}
else
{
throw new IllegalArgumentException(
"Non compatible position type for Viewer3D : " + viewerPosition.getClass().getName());
}
}
/**
* Set the view.
*
* @param pos position of viewer.
* @param dir direction of viewer.
* @param up up of viewer.
*/
public void setView(Vector3d pos, Vector3d dir, Vector3d up)
{
Vector3d scaledPos = pos;
double originDistance = pos.getLength();
if (originDistance > ourMaxOriginDistance)
{
double scaleFactor = ourMaxOriginDistance / originDistance;
scaledPos = pos.multiply(scaleFactor);
}
// Make sure that the viewer still points at the model
Vector3d intersection = getModel().getIntersection(new Ray3d(scaledPos, dir));
if (intersection == null || intersection.dot(dir) > -100)
{
return;
}
// Make sure that the viewer is not inside the model
MapContext<DynamicViewer> mapContext = getMapContext();
GeographicPosition geopos = null;
if (mapContext != null)
{
if (!mapContext.getProjection().isOutsideModel(scaledPos.add(scaledPos.multiply(Viewer3D.TERRAIN_SAFETY_TOLERANCE))))
{
return;
}
geopos = mapContext.getProjection().convertToPosition(pos, ReferenceLevel.ELLIPSOID);
double elevation = TerrainUtil.getInstance().getElevationInMeters(mapContext, geopos);
geopos = new GeographicPosition(LatLonAlt.createFromDegreesMeters(geopos.getLatLonAlt().getLatD(),
geopos.getLatLonAlt().getLonD(), geopos.getLatLonAlt().getAltM() - elevation, ReferenceLevel.TERRAIN));
if (!validateNewPosition(geopos))
{
return;
}
// System.out.println(geopos);
}
ViewerPosition3D viewerPosition = new ViewerPosition3D(scaledPos, dir, up);
viewerPosition.setGeoPosition(geopos);
setPosition(viewerPosition);
}
/**
* Spin the viewer around an arbitrary axis such that the <i>from</i> point
* is moved to the <i>to</i> point.
*
* @param from The from point.
* @param to The to point.
* @param spinAxis The normalized axis to rotate about.
*/
public void spinOnAxis(Vector3d from, Vector3d to, Vector3d spinAxis)
{
// get the amount of rotation around the spin axis required to
// move "from" to "to". To do this, project the vectors
// onto the plane perpendicular to the spin axis, then find the
// angle between the projections.
Vector3d startProj = Plane.unitProjection(spinAxis, from);
Vector3d endProj = Plane.unitProjection(spinAxis, to);
double dot = MathUtil.clamp(startProj.dot(endProj), -1., 1.);
double rotAngle = Math.acos(dot);
// Determine whether the rotation is positive or negative by comparing
// the spinAxis direction with the rotAxis direction.
Vector3d rotAxis = startProj.cross(endProj).getNormalized();
if (rotAxis.dot(spinAxis) > 0)
{
rotAngle *= -1.;
}
ViewerPosition3D first = getSpinOnAxisPosition(rotAngle, spinAxis, false, getPosition());
// tilt the spin axis
Vector3d oToV = new Vector3d(first.getLocation()).getNormalized();
if (MathUtil.isZero(Math.abs(oToV.dot(spinAxis)) - 1d))
{
return;
}
Vector3d tiltPlaneNormal = oToV.cross(spinAxis).getNormalized();
startProj = Plane.unitProjection(tiltPlaneNormal, from);
endProj = Plane.unitProjection(tiltPlaneNormal, to);
dot = MathUtil.clamp(startProj.dot(endProj), -1., 1.);
rotAngle = Math.acos(dot);
rotAxis = startProj.cross(endProj).getNormalized();
if (rotAxis.dot(tiltPlaneNormal) > 0)
{
rotAngle *= -1.;
}
ViewerPosition3D finish = getSpinOnAxisPosition(rotAngle, tiltPlaneNormal, false, first);
setView(finish.getLocation(), finish.getDir(), finish.getUp());
}
@Override
public void startAnimationToPreferredPosition()
{
ViewerPosition3D pos = getPreferences().getJAXBObject(ViewerPosition3D.class, POSITION_PREF_KEY, null);
if (pos != null)
{
if (isViewerPositionInvalid(pos))
{
Notify.warn("Saved viewing angle is out of bounds. Resetting to default.", Method.TOAST);
pos = new ViewerPosition3D();
}
new ViewerAnimator(this, pos).start();
}
}
@Override
public boolean supportsAdjustedModelView()
{
return true;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder(64);
sb.append("Position : ").append(myPosition);
sb.append(", Direction : ").append(myPosition.getDir());
sb.append(", Up : ").append(myPosition.getUp());
return sb.toString();
}
@Override
public void validateViewerPosition()
{
Vector3d pos = new Vector3d(myPosition.getLocation());
double terrainTolerance = TERRAIN_SAFETY_TOLERANCE;
boolean changed = false;
if (myPosition.getGeoPosition() != null)
{
Vector3d oldPos = pos;
pos = myMapContext.getProjection().convertToModel(myPosition.getGeoPosition(), Vector3d.ORIGIN);
changed = Math.abs(pos.getX() - oldPos.getX()) > 400 || Math.abs(pos.getY() - oldPos.getY()) > 400
|| Math.abs(pos.getZ() - oldPos.getZ()) > 400;
if (myPosition.getGeoPosition().getAlt().getReferenceLevel() != ReferenceLevel.TERRAIN)
{
terrainTolerance *= 10;
}
}
Vector3d backup = myPosition.getDir().multiply(-100);
while (!myMapContext.getProjection().isOutsideModel(pos.add(pos.multiply(terrainTolerance))))
{
changed = true;
pos = pos.add(backup);
}
if (changed)
{
ViewerPosition3D viewerPosition = new ViewerPosition3D(pos, myPosition.getDir(), myPosition.getUp());
viewerPosition.setGeoPosition(myPosition.getGeoPosition());
setPosition(viewerPosition);
}
}
@Override
public Vector3d windowToModelCoords(Vector2i windowCoords)
{
Vector3d model = super.windowToModelCoords(windowCoords);
Vector3d lookAt = model.subtract(myPosition.getLocation());
return myModel.getIntersection(new Ray3d(myPosition.getLocation(), lookAt));
}
@Override
protected void doReshape(int width, int height)
{
setAspectRatio((double)width / (double)height);
}
/**
* Generate the clipped projection matrix.
*
* @param clipFarToCenter When true the far clipping plane will be moved so
* that it passes through the origin. Otherwise the far clipping
* plane will be at twice the distance from the viewer to the
* origin.
* @return The matrix.
*/
protected synchronized float[] generateProjectionMatrixClipped(boolean clipFarToCenter)
{
if (myProjectionMatrix == null)
{
resetProjectionMatrix();
}
float[] clipped = myProjectionMatrix.clone();
Vector3d model = getClosestModelPosition();
double elevation;
if (myMapContext == null)
{
elevation = model.subtract(myPosition.getLocation()).getLength();
}
else
{
// convertToPosition() gives the geographic location with a 0
// altitude (referenced by terrain) and convertToModel() gives
// the location on the terrain.
Projection snapshot = myMapContext.getProjection();
Vector3d terrainModel = snapshot.convertToModel(snapshot.convertToPosition(model, ReferenceLevel.TERRAIN),
Vector3d.ORIGIN);
elevation = terrainModel.subtract(myPosition.getLocation()).getLength();
}
double tanHalfFov = (float)Math.tan(myHalfFOVx);
final double minNearClipDistance = 5.;
double near = Math.max(elevation / (2. * Math.sqrt(2. * tanHalfFov * tanHalfFov + 1.)), minNearClipDistance);
double radius = myModel.getBoundingRadius();
double far = Math.sqrt(elevation * (2. * radius + elevation));
far *= clipFarToCenter ? 1 : 2;
double depth = far - near;
double c = -(far + near) / depth;
double d = -2. * far * near / depth;
clipped[10] = (float)c;
clipped[14] = (float)d;
return clipped;
}
/** reset the clipping plane. */
protected final void resetClipPlanes()
{
// set the point for each plane to the viewer position
Vector3d loc = myPosition.getLocation();
myLeftClip.setPoint(loc);
myRightClip.setPoint(loc);
myBottomClip.setPoint(loc);
myTopClip.setPoint(loc);
myRightClip.setNormal(myPosition.getRight().rotate(myPosition.getUp(), Math.PI - myHalfFOVx));
myLeftClip.setNormal(myPosition.getRight().rotate(myPosition.getUp(), myHalfFOVx));
myBottomClip.setNormal(myPosition.getUp().rotate(myPosition.getRight(), -myHalfFOVy));
// Increase the top clip a bit to account for zoomed in with terrain.
myTopClip.setNormal(myPosition.getUp().rotate(myPosition.getRight(), myHalfFOVy - Math.PI + ourTopClipIncreaseAngle));
}
@Override
protected synchronized void resetInverseModelViewMatrix()
{
setInverseModelViewMatrix(new Matrix4d(getModelViewMatrix()).invert());
}
/** Reset the model view matrix. */
protected synchronized void resetModelViewMatrix()
{
Matrix4d transform = new Matrix4d();
// translate so that the viewer is at the origin
Matrix4d translation = new Matrix4d();
translation.setTranslation(myPosition.getLocation().multiply(-1.));
// rotate to put the viewer pointing in the -z direction with the up
// vector along the +y axis.
Quaternion quat = Quaternion.lookAt(myPosition.getDir().multiply(-1.), myPosition.getUp());
Matrix4d rotation = new Matrix4d();
rotation.setRotationQuaternion(quat);
// set the transform.
transform.multLocal(rotation);
transform.multLocal(translation);
myModelViewMatrix = transform.toFloatArray();
setInverseModelViewMatrix(transform.invert());
clearModelToWindowTransform();
}
/** Reset the projection matrix. */
protected void resetProjectionMatrix()
{
float tan = (float)Math.tan(myHalfFOVx);
synchronized (this)
{
resetProjectionMatrixClipped();
myProjectionMatrix = new float[16];
myProjectionMatrix[0] = 1f / tan;
myProjectionMatrix[5] = (float)(myAspectRatio / tan);
myProjectionMatrix[10] = -1f;
myProjectionMatrix[11] = -1f;
myProjectionMatrix[14] = -2f;
clearModelToWindowTransform();
}
}
/**
* Clear the clipped projection matrices.
*/
protected void resetProjectionMatrixClipped()
{
synchronized (this)
{
myProjectionMatrixClipped = null;
myProjectionMatrixClippedFarToCenter = null;
}
}
/**
* Rotate my current direction and return the resultant vector.
*
* @param xChange change in the x direction (radians).
* @param yChange change in the y direction (radians).
* @return the resultant vector after rotation.
*/
protected Vector3d rotateDir(double xChange, double yChange)
{
return myPosition.getDir().rotate(myPosition.getUp(), xChange).rotate(myPosition.getRight(), yChange);
}
/**
* Set the aspect ratio.
*
* @param aspectRatio aspect ratio to set.
*/
protected synchronized void setAspectRatio(double aspectRatio)
{
myAspectRatio = aspectRatio;
myHalfFOVy = Math.atan(Math.tan(myHalfFOVx) / myAspectRatio);
resetProjectionMatrix();
}
/** Handle a view change. */
protected final void viewChanged()
{
synchronized (this)
{
resetProjectionMatrixClipped();
resetModelViewMatrix();
resetClipPlanes();
notifyViewChanged(ViewChangeSupport.ViewChangeType.VIEW_CHANGE);
if (getPreferences() != null)
{
getPreferences().putJAXBObject(POSITION_PREF_KEY, getPosition().clone(), true, this);
}
}
}
/**
* Validates the new position against the current position to make sure it
* doesn't move drastically.
*
* @param newPosition The new position to validate.
* @return True if the new position is valid, false if there was way too
* much movement.
*/
private boolean validateNewPosition(GeographicPosition newPosition)
{
boolean isValid = true;
if (getPosition().getGeoPosition() != null)
{
LatLonAlt current = getPosition().getGeoPosition().getLatLonAlt();
if (isValid && current.getAltM() < 2000)
{
isValid = Math.abs(newPosition.getLatLonAlt().getLatD() - current.getLatD()) < ourZoomedInDegreeTolerance
&& Math.abs(newPosition.getLatLonAlt().getLonD() - current.getLonD()) < ourZoomedInDegreeTolerance;
}
if (isValid && (newPosition.getLatLonAlt().getAltM() < 2000 || current.getAltM() < 2000))
{
isValid = newPosition.getLatLonAlt().getAltM() - current.getAltM() < 1500;
}
}
return isValid;
}
/**
* Checks if the given viewer position is invalid- inside the model
* or outside the maximum distance from the origin.
*
* @param position the position to validate
* @return true if the viewer position is invalid, false if valid
*/
private boolean isViewerPositionInvalid(ViewerPosition3D position)
{
Vector3d location = new Vector3d(position.getLocation());
double terrainTolerance = TERRAIN_SAFETY_TOLERANCE;
if (position.getGeoPosition() != null && position.getGeoPosition().getAlt().getReferenceLevel() != ReferenceLevel.TERRAIN)
{
terrainTolerance *= 10;
}
if (!myMapContext.getProjection().isOutsideModel(location.add(location.multiply(terrainTolerance)))
|| Math.abs(location.getX()) > ourMaxOriginDistance
|| Math.abs(location.getY()) > ourMaxOriginDistance
|| Math.abs(location.getZ()) > ourMaxOriginDistance)
{
return true;
}
return false;
}
/** Position and orientation information for the 3D viewer. */
@XmlRootElement
public static class ViewerPosition3D implements ViewerPosition, Cloneable
{
/** Direction the viewer faces. */
private volatile Vector3d myDir = new Vector3d(-1., 0., 0.);
/**
* The geographic position of the viewer.
*/
private GeographicPosition myGeoPosition;
/** Viewer current position in model coordinates. */
private volatile Vector3d myLocation = new Vector3d(25000000, 0, 0);
/** The viewer current roll orientation. */
private volatile Vector3d myUp = Vector3d.UNIT_Z;
/**
* Construct a default viewer position.
*/
public ViewerPosition3D()
{
}
/**
* Constructor.
*
* @param location Location of the viewer.
* @param dir Direction which the viewer faces.
* @param up Direction in the view which is towards the top of the
* screen.
*/
public ViewerPosition3D(Vector3d location, Vector3d dir, Vector3d up)
{
setPosition(location, dir, up);
}
@Override
public ViewerPosition3D clone()
{
try
{
return (ViewerPosition3D)super.clone();
}
catch (CloneNotSupportedException e)
{
throw new ExpectedCloneableException(e);
}
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null || getClass() != obj.getClass())
{
return false;
}
ViewerPosition3D other = (ViewerPosition3D)obj;
return EqualsHelper.equals(myDir, other.myDir, myLocation, other.myLocation, myUp, other.myUp);
}
/**
* Get the axes for the local coordinate system of the viewer position.
*
* @return The axes ordered by x-axis, y-axis, z-axis.
*/
public Vector3d[] getAxes()
{
return new Vector3d[] { getRight(), getUp(), getDir() };
}
/**
* Get the dir.
*
* @return the dir
*/
@XmlJavaTypeAdapter(MutableVector3d.Vector3dAdapter.class)
public Vector3d getDir()
{
return myDir;
}
/**
* Gets the geographic position of the viewers position.
*
* @return The geographic position of the viewers position, or null if
* it hasn't been set.
*/
public GeographicPosition getGeoPosition()
{
return myGeoPosition;
}
@Override
@XmlJavaTypeAdapter(MutableVector3d.Vector3dAdapter.class)
public Vector3d getLocation()
{
return myLocation;
}
/**
* Get the normalized cross product of the viewer direction and up.
*
* @return The vector pointing directly right of the viewer.
*/
public final Vector3d getRight()
{
return myDir.cross(myUp).getNormalized();
}
/**
* Get the up.
*
* @return the up
*/
@XmlJavaTypeAdapter(MutableVector3d.Vector3dAdapter.class)
public Vector3d getUp()
{
return myUp;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (myDir == null ? 0 : myDir.hashCode());
result = prime * result + (myLocation == null ? 0 : myLocation.hashCode());
result = prime * result + (myUp == null ? 0 : myUp.hashCode());
return result;
}
/**
* Set the dir.
*
* @param dir the dir to set
*/
public void setDir(Vector3d dir)
{
myDir = dir;
}
/**
* Set the location.
*
* @param location the location to set
*/
public void setLocation(Vector3d location)
{
myLocation = location;
}
/**
* Set the position and orientation.
*
* @param location Location of the viewer
* @param dir Direction the viewer faces.
* @param up The direction which is towards the top of the screen.
*/
public final void setPosition(Vector3d location, Vector3d dir, Vector3d up)
{
myLocation = location;
myDir = dir.getNormalized();
myUp = up.square(myDir).getNormalized();
}
/**
* Set the position and orientation.
*
* @param location Location of the viewer
* @param dir Direction the viewer faces.
* @param up The direction which is towards the top of the screen.
* @param geoPos The geographic position of the viewer.
*/
public final void setPosition(Vector3d location, Vector3d dir, Vector3d up, GeographicPosition geoPos)
{
setPosition(location, dir, up);
myGeoPosition = geoPos;
}
/**
* Set this position to match the given position.
*
* @param viewerPosition The position to which to set.
*/
public void setPosition(ViewerPosition3D viewerPosition)
{
setPosition(viewerPosition.getLocation(), viewerPosition.getDir(), viewerPosition.getUp());
}
/**
* Set the up.
*
* @param up the up to set
*/
public void setUp(Vector3d up)
{
myUp = up;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder(64);
sb.append("Location : ").append(myLocation);
sb.append(" | Direction : ").append(myDir);
sb.append(" | Up : ").append(myUp);
return sb.toString();
}
/**
* Sets the {@link GeographicPosition} the viewer is supposed to be in.
* This is used to keep the viewer in the correct location even after
* terrain updates.
*
* @param geoPosition The {@link GeographicPosition} of the viewer.
*/
protected void setGeoPosition(GeographicPosition geoPosition)
{
myGeoPosition = geoPosition;
}
}
}
|
# STEP 6: perform data evaluation to filter low-quality data samples and tag data samples with quality metrics:
# language model, entailment model, language complexity
output_path="/home/Datasets/processed/SQuAD2.0/"
data_file_prefix="train"
st_idx=0
ed_idx=50000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/SQuAD2.0/"
data_file_prefix="train"
st_idx=50000
ed_idx=92210
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=0
ed_idx=50000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=50000
ed_idx=100000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=100000
ed_idx=150000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=150000
ed_idx=200000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=200000
ed_idx=250000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=250000
ed_idx=300000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=300000
ed_idx=350000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=350000
ed_idx=400000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=400000
ed_idx=450000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=450000
ed_idx=500000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=500000
ed_idx=550000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=550000
ed_idx=600000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=600000
ed_idx=650000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=650000
ed_idx=700000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=700000
ed_idx=750000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=750000
ed_idx=800000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=800000
ed_idx=850000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=850000
ed_idx=900000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=900000
ed_idx=950000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
output_path="/home/Datasets/processed/Wiki10000/"
data_file_prefix="wiki10000"
st_idx=950000
ed_idx=1000000
python3 DE_main.py \
--input_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.txt" \
--input_augmented_pkl_file "${output_path}${data_file_prefix}.sentences.augmented.${st_idx}_${ed_idx}.processed.pkl" \
--output_file "${output_path}${data_file_prefix}.qa.${st_idx}_${ed_idx}.entail.de.txt"
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('security', '0014_index_prisoner_number'),
]
operations = [
migrations.AlterField(
model_name='debitcardsenderdetails',
name='card_number_last_digits',
field=models.CharField(blank=True, db_index=True, max_length=4, null=True),
),
migrations.AlterField(
model_name='debitcardsenderdetails',
name='postcode',
field=models.CharField(blank=True, db_index=True, max_length=250, null=True),
),
]
|
package pulse.tasks.processing;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static pulse.properties.NumericProperties.def;
import static pulse.properties.NumericPropertyKeyword.DIFFUSIVITY;
import static pulse.properties.NumericPropertyKeyword.IDENTIFIER;
import static pulse.properties.NumericPropertyKeyword.TEST_TEMPERATURE;
import java.util.ArrayList;
import java.util.List;
import pulse.properties.NumericPropertyKeyword;
import pulse.tasks.listeners.ResultFormatEvent;
import pulse.tasks.listeners.ResultFormatListener;
/**
* <p>
* A singleton {@code ResultFormat}, which contains a list of
* {@code NumericPropertyKeyword}s used for identification of
* {@code NumericPropert}ies. The format is constructed using a string of unique
* characters.
* </p>
*/
public class ResultFormat {
private List<NumericPropertyKeyword> nameMap;
private final static NumericPropertyKeyword[] minimalArray = new NumericPropertyKeyword[]{IDENTIFIER,
TEST_TEMPERATURE, DIFFUSIVITY};
/**
* <p>
* The default format specified by the
* {@code Messages.getString("ResultFormat.DefaultFormat")}. See file
* messages.properties in {@code pulse.ui}.
* </p>
*/
private static ResultFormat format = new ResultFormat();
private static List<ResultFormatListener> listeners = new ArrayList<ResultFormatListener>();
private ResultFormat() {
this(asList(minimalArray));
}
private ResultFormat(List<NumericPropertyKeyword> keys) {
nameMap = new ArrayList<>();
for (var key : keys) {
nameMap.add(key);
}
}
private ResultFormat(ResultFormat fmt) {
nameMap = new ArrayList<>(fmt.nameMap.size());
nameMap.addAll(fmt.nameMap);
}
public static void addResultFormatListener(ResultFormatListener rfl) {
listeners.add(rfl);
}
public static ResultFormat generateFormat(List<NumericPropertyKeyword> keys) {
format = new ResultFormat(keys);
var rfe = new ResultFormatEvent(format);
for (var rfl : listeners) {
rfl.resultFormatChanged(rfe);
}
return format;
}
/**
* This class uses a singleton pattern, meaning there is only instance of
* this class.
*
* @return the single (static) instance of this class
*/
public static ResultFormat getInstance() {
return format;
}
/**
* Retrieves the list of keyword associated with this {@code ResultFormat}
*
* @return a list of keywords that can be used to access
* {@code NumericProperty} objects
*/
public List<NumericPropertyKeyword> getKeywords() {
return nameMap;
}
/**
* Creates a {@code List<String>} of default abbreviations corresponding to
* the list of keywords specific to {@code NumericProperty} objects.
*
* @return a list of abbreviations (typically, for filling the result table
* headers)
*/
public List<String> abbreviations() {
return nameMap.stream().map(keyword -> def(keyword).getAbbreviation(true)).collect(toList());
}
/**
* Creates a {@code List<String>} of default descriptions corresponding to
* the list of keywords specific to {@code NumericProperty} objects.
*
* @return a list of abbreviations (typically, for filling the result table
* tooltips)
*/
public List<String> descriptors() {
return nameMap.stream().map(keyword -> def(keyword).getDescriptor(true)).collect(toList());
}
/**
* Finds a {@code NumericPropertyKeyword} contained in the {@code nameMap},
* the description of which matches {@code descriptor}.
*
* @param descriptor a {@code String} describing the
* {@code NumericPropertyKeyword}
* @return the {@code NumericPropertyKeyword} object
*/
public NumericPropertyKeyword fromAbbreviation(String descriptor) {
return nameMap.stream().filter(keyword -> def(keyword).getAbbreviation(true).equals(descriptor))
.findFirst().get();
}
/**
* Calculates the length of the format string, which is the same as the size
* of the keyword list.
*
* @return an integer, representing the size of the format string.
*/
public int size() {
return nameMap.size();
}
public int indexOf(NumericPropertyKeyword key) {
if (nameMap.contains(key)) {
return nameMap.indexOf(key);
}
return -1;
}
public static NumericPropertyKeyword[] getMinimalArray() {
return minimalArray;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o == null) {
return false;
}
if (!(o.getClass().equals(o.getClass()))) {
return false;
}
var another = (ResultFormat) o;
return (another.nameMap.containsAll(this.nameMap)) && (this.nameMap.containsAll(another.nameMap));
}
}
|
<reponame>jianglong0156/chromium.src<filename>ui/gfx/rect_base_impl.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/rect_base.h"
#include "base/logging.h"
#include "base/stringprintf.h"
// This file provides the implementation for RectBaese template and
// used to instantiate the base class for Rect and RectF classes.
#if !defined(UI_IMPLEMENTATION)
#error "This file is intended for UI implementation only"
#endif
namespace {
template<typename Type>
void AdjustAlongAxis(Type dst_origin, Type dst_size, Type* origin, Type* size) {
*size = std::min(dst_size, *size);
if (*origin < dst_origin)
*origin = dst_origin;
else
*origin = std::min(dst_origin + dst_size, *origin + *size) - *size;
}
} // namespace
namespace gfx {
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
RectBase(const PointClass& origin, const SizeClass& size)
: origin_(origin), size_(size) {
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
RectBase(const SizeClass& size)
: size_(size) {
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
RectBase(const PointClass& origin)
: origin_(origin) {
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
~RectBase() {}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
SetRect(Type x, Type y, Type width, Type height) {
origin_.SetPoint(x, y);
set_width(width);
set_height(height);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Inset(const InsetsClass& insets) {
Inset(insets.left(), insets.top(), insets.right(), insets.bottom());
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Inset(Type left, Type top, Type right, Type bottom) {
Offset(left, top);
set_width(std::max(width() - left - right, static_cast<Type>(0)));
set_height(std::max(height() - top - bottom, static_cast<Type>(0)));
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Offset(Type horizontal, Type vertical) {
origin_.Offset(horizontal, vertical);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
operator<(const Class& other) const {
if (origin_ == other.origin_) {
if (width() == other.width()) {
return height() < other.height();
} else {
return width() < other.width();
}
} else {
return origin_ < other.origin_;
}
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Contains(Type point_x, Type point_y) const {
return (point_x >= x()) && (point_x < right()) &&
(point_y >= y()) && (point_y < bottom());
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Contains(const Class& rect) const {
return (rect.x() >= x() && rect.right() <= right() &&
rect.y() >= y() && rect.bottom() <= bottom());
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Intersects(const Class& rect) const {
return !(rect.x() >= right() || rect.right() <= x() ||
rect.y() >= bottom() || rect.bottom() <= y());
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Intersect(const Class& rect) {
if (IsEmpty() || rect.IsEmpty()) {
SetRect(0, 0, 0, 0);
return;
}
Type rx = std::max(x(), rect.x());
Type ry = std::max(y(), rect.y());
Type rr = std::min(right(), rect.right());
Type rb = std::min(bottom(), rect.bottom());
if (rx >= rr || ry >= rb)
rx = ry = rr = rb = 0; // non-intersecting
SetRect(rx, ry, rr - rx, rb - ry);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Union(const Class& rect) {
if (IsEmpty()) {
*this = rect;
return;
}
if (rect.IsEmpty())
return;
Type rx = std::min(x(), rect.x());
Type ry = std::min(y(), rect.y());
Type rr = std::max(right(), rect.right());
Type rb = std::max(bottom(), rect.bottom());
SetRect(rx, ry, rr - rx, rb - ry);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
Subtract(const Class& rect) {
if (!Intersects(rect))
return;
if (rect.Contains(*static_cast<const Class*>(this))) {
SetRect(0, 0, 0, 0);
return;
}
Type rx = x();
Type ry = y();
Type rr = right();
Type rb = bottom();
if (rect.y() <= y() && rect.bottom() >= bottom()) {
// complete intersection in the y-direction
if (rect.x() <= x()) {
rx = rect.right();
} else {
rr = rect.x();
}
} else if (rect.x() <= x() && rect.right() >= right()) {
// complete intersection in the x-direction
if (rect.y() <= y()) {
ry = rect.bottom();
} else {
rb = rect.y();
}
}
SetRect(rx, ry, rr - rx, rb - ry);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
AdjustToFit(const Class& rect) {
Type new_x = x();
Type new_y = y();
Type new_width = width();
Type new_height = height();
AdjustAlongAxis(rect.x(), rect.width(), &new_x, &new_width);
AdjustAlongAxis(rect.y(), rect.height(), &new_y, &new_height);
SetRect(new_x, new_y, new_width, new_height);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
PointClass RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass,
Type>::CenterPoint() const {
return PointClass(x() + width() / 2, y() + height() / 2);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
ClampToCenteredSize(const SizeClass& size) {
Type new_width = std::min(width(), size.width());
Type new_height = std::min(height(), size.height());
Type new_x = x() + (width() - new_width) / 2;
Type new_y = y() + (height() - new_height) / 2;
SetRect(new_x, new_y, new_width, new_height);
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
void RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
SplitVertically(Class* left_half, Class* right_half) const {
DCHECK(left_half);
DCHECK(right_half);
left_half->SetRect(this->x(), this->y(), this->width() / 2, this->height());
right_half->SetRect(left_half->right(),
this->y(),
this->width() - left_half->width(),
this->height());
}
template<typename Class,
typename PointClass,
typename SizeClass,
typename InsetsClass,
typename VectorClass,
typename Type>
bool RectBase<Class, PointClass, SizeClass, InsetsClass, VectorClass, Type>::
SharesEdgeWith(const Class& rect) const {
return (y() == rect.y() && height() == rect.height() &&
(x() == rect.right() || right() == rect.x())) ||
(x() == rect.x() && width() == rect.width() &&
(y() == rect.bottom() || bottom() == rect.y()));
}
} // namespace gfx
|
"""Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
Original C++ source file: libsvm_ops.cc
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _core
from tensorflow.python.eager import execute as _execute
from tensorflow.python.framework import dtypes as _dtypes
from tensorflow.python.framework import errors as _errors
from tensorflow.python.framework import tensor_shape as _tensor_shape
from tensorflow.core.framework import op_def_pb2 as _op_def_pb2
# Needed to trigger the call to _set_call_cpp_shape_fn.
from tensorflow.python.framework import common_shapes as _common_shapes
from tensorflow.python.framework import op_def_registry as _op_def_registry
from tensorflow.python.framework import ops as _ops
from tensorflow.python.framework import op_def_library as _op_def_library
from tensorflow.python.util.tf_export import tf_export
_decode_libsvm_outputs = ["label", "feature_indices", "feature_values",
"feature_shape"]
_DecodeLibsvmOutput = _collections.namedtuple(
"DecodeLibsvm", _decode_libsvm_outputs)
@tf_export('decode_libsvm')
def decode_libsvm(input, num_features, dtype=_dtypes.float32, label_dtype=_dtypes.int64, name=None):
r"""Convert LibSVM input to tensors. The output consists of
a label and a feature tensor. The shape of the label tensor
is the same as input and the shape of the feature tensor is
`[input_shape, num_features]`.
Args:
input: A `Tensor` of type `string`. Each string is a record in the LibSVM.
num_features: An `int` that is `>= 1`. The number of features.
dtype: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.float32`.
label_dtype: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to `tf.int64`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (label, feature_indices, feature_values, feature_shape).
label: A `Tensor` of type `label_dtype`. A tensor of the same shape as input.
feature_indices: A `Tensor` of type `int64`. A 2-D int64 tensor of dense_shape [N, ndims].
feature_values: A `Tensor` of type `dtype`. A 1-D tensor of any type and dense_shape [N].
feature_shape: A `Tensor` of type `int64`. A 1-D int64 tensor of dense_shape [ndims].
"""
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
num_features = _execute.make_int(num_features, "num_features")
if dtype is None:
dtype = _dtypes.float32
dtype = _execute.make_type(dtype, "dtype")
if label_dtype is None:
label_dtype = _dtypes.int64
label_dtype = _execute.make_type(label_dtype, "label_dtype")
_, _, _op = _op_def_lib._apply_op_helper(
"DecodeLibsvm", input=input, num_features=num_features, dtype=dtype,
label_dtype=label_dtype, name=name)
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("dtype", _op.get_attr("dtype"), "label_dtype",
_op.get_attr("label_dtype"), "num_features",
_op.get_attr("num_features"))
_execute.record_gradient(
"DecodeLibsvm", _inputs_flat, _attrs, _result, name)
_result = _DecodeLibsvmOutput._make(_result)
return _result
else:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._eager_context.device_name, "DecodeLibsvm",
name, _ctx._post_execution_callbacks, input, "dtype", dtype,
"label_dtype", label_dtype, "num_features", num_features)
_result = _DecodeLibsvmOutput._make(_result)
return _result
except _core._FallbackException:
return decode_libsvm_eager_fallback(
input, dtype=dtype, label_dtype=label_dtype,
num_features=num_features, name=name, ctx=_ctx)
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
def decode_libsvm_eager_fallback(input, num_features, dtype=_dtypes.float32, label_dtype=_dtypes.int64, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function decode_libsvm
"""
_ctx = ctx if ctx else _context.context()
num_features = _execute.make_int(num_features, "num_features")
if dtype is None:
dtype = _dtypes.float32
dtype = _execute.make_type(dtype, "dtype")
if label_dtype is None:
label_dtype = _dtypes.int64
label_dtype = _execute.make_type(label_dtype, "label_dtype")
input = _ops.convert_to_tensor(input, _dtypes.string)
_inputs_flat = [input]
_attrs = ("dtype", dtype, "label_dtype", label_dtype, "num_features",
num_features)
_result = _execute.execute(b"DecodeLibsvm", 4, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"DecodeLibsvm", _inputs_flat, _attrs, _result, name)
_result = _DecodeLibsvmOutput._make(_result)
return _result
_ops.RegisterShape("DecodeLibsvm")(None)
def _InitOpDefLibrary(op_list_proto_bytes):
op_list = _op_def_pb2.OpList()
op_list.ParseFromString(op_list_proto_bytes)
_op_def_registry.register_op_list(op_list)
op_def_lib = _op_def_library.OpDefLibrary()
op_def_lib.add_op_list(op_list)
return op_def_lib
# op {
# name: "DecodeLibsvm"
# input_arg {
# name: "input"
# type: DT_STRING
# }
# output_arg {
# name: "label"
# type_attr: "label_dtype"
# }
# output_arg {
# name: "feature_indices"
# type: DT_INT64
# }
# output_arg {
# name: "feature_values"
# type_attr: "dtype"
# }
# output_arg {
# name: "feature_shape"
# type: DT_INT64
# }
# attr {
# name: "dtype"
# type: "type"
# default_value {
# type: DT_FLOAT
# }
# allowed_values {
# list {
# type: DT_FLOAT
# type: DT_DOUBLE
# type: DT_INT32
# type: DT_INT64
# }
# }
# }
# attr {
# name: "label_dtype"
# type: "type"
# default_value {
# type: DT_INT64
# }
# allowed_values {
# list {
# type: DT_FLOAT
# type: DT_DOUBLE
# type: DT_INT32
# type: DT_INT64
# }
# }
# }
# attr {
# name: "num_features"
# type: "int"
# has_minimum: true
# minimum: 1
# }
# }
_op_def_lib = _InitOpDefLibrary(b"\n\311\001\n\014DecodeLibsvm\022\t\n\005input\030\007\032\024\n\005label\"\013label_dtype\032\023\n\017feature_indices\030\t\032\027\n\016feature_values\"\005dtype\032\021\n\rfeature_shape\030\t\"\033\n\005dtype\022\004type\032\0020\001:\010\n\0062\004\001\002\003\t\"!\n\013label_dtype\022\004type\032\0020\t:\010\n\0062\004\001\002\003\t\"\027\n\014num_features\022\003int(\0010\001") |
#!/bin/sh
openssl dgst \
-sha256 \
-sign ~/.openssl/stub2ch_private.pem \
tools/auth/passphrase.txt \
| base64 -w 0
echo ""
|
// scrivi la soluzione qui...
/*Si scriva un metodo Scala mcd che calcola il massimo comun divisore (MCD) di due numeri interi. Usare la seguente definizione ricorsiva:
MCD(x,y)=x, se y=0
MCD(x,y)=MCD(y, resto della divisione di x per y) altrimenti
Compilare ed eseguire come visto nell’Esercizio 1. Scrivere la soluzione nel file E2.scala in modo simile a quanto fatto negli esercizi precedenti e usare il programma di prova E2Main.scala fornito.
*/
object E2 {
def mcd(x: Int, y:Int): Int = if (y==0) x else mcd(y, x%y)
} |
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file 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.
#
if [ -z "$PLATFORM" ]; then
echo "You should run the main script."
exit 1
fi
LIB_SUFFIX="dll.a"
START_SCRIPT="$INSTALL_BASE/startsample.bat"
START_PREVIEW_SCRIPT="$INSTALL_BASE/startpreview.bat"
CMAKE_PLATFORM_SPECIFIC=(-G 'MSYS Makefiles' -Dgtest_disable_pthreads=ON \
-DGSTREAMER_MEDIA_PLAYER=ON -DPORTAUDIO=ON \
-DPORTAUDIO_LIB_PATH="$THIRD_PARTY_PATH/portaudio/lib/.libs/libportaudio.$LIB_SUFFIX" \
-DPORTAUDIO_INCLUDE_DIR="$THIRD_PARTY_PATH/portaudio/include")
CONFIG_DB_PATH=`cygpath.exe -m $DB_PATH`
GSTREAMER_AUDIO_SINK="directsoundsink"
install_dependencies() {
PACMAN_ARGS="--noconfirm --needed"
# Build tools and make (mingw32-make fails building portAudio)
pacman -S ${PACMAN_ARGS} git mingw-w64-x86_64-toolchain mingw-w64-x86_64-clang mingw-w64-x86_64-cmake msys/tar msys/make
# required by the SDK
pacman -S ${PACMAN_ARGS} mingw-w64-x86_64-sqlite3
# MediaPlayer reference Implementation
pacman -S ${PACMAN_ARGS} mingw64/mingw-w64-x86_64-gstreamer
# MediaPlayer reference Implementation
pacman -S ${PACMAN_ARGS} mingw64/mingw-w64-x86_64-gst-plugins-good mingw64/mingw-w64-x86_64-gst-plugins-base mingw64/mingw-w64-x86_64-gst-plugins-ugly
# Music providers requirements
pacman -S ${PACMAN_ARGS} mingw64/mingw-w64-x86_64-gst-plugins-bad mingw64/mingw-w64-x86_64-faad2
# Install Portaudio
pacman -S ${PACMAN_ARGS} mingw64/mingw-w64-x86_64-portaudio
}
run_os_specifics() {
build_port_audio
# Use clang to compile the SDK.
export CC=`which clang`
export CXX=`which clang++`
}
generate_start_script() {
cat << EOF > "$START_SCRIPT"
set path=`cygpath.exe -m $MSYSTEM_PREFIX/bin`;%path%;
cd `cygpath.exe -m $BUILD_PATH/bin`
SampleApp.exe `cygpath.exe -m $OUTPUT_CONFIG_FILE` DEBUG9
pause
EOF
cat << EOF > "$START_PREVIEW_SCRIPT"
set path=`cygpath.exe -m $MSYSTEM_PREFIX/bin`;%path%;
cd `cygpath.exe -m $BUILD_PATH/bin`
PreviewAlexaClient.exe `cygpath.exe -m $OUTPUT_CONFIG_FILE` DEBUG9
pause
EOF
}
generate_test_script() {
cat << EOF > "${TEST_SCRIPT}"
echo
echo "==============> BUILDING Tests =============="
echo
cd ${BUILD_PATH}
make all -j2
make test
EOF
}
|
#!/bin/bash
sudo apt-get update
apt install scapy net-tools
sudo ip link set dev lo up
sudo ip -6 addr add fc00::8/64 dev enp0s8
sudo ip link set dev enp0s8 up
sudo ip -6 neigh add fc00::1 lladdr 00:15:4d:00:00:00 nud permanent dev enp0s8
sudo ip -6 neigh add fc00::2 lladdr 00:15:4d:00:00:01 nud permanent dev enp0s8
sudo ip -6 neigh add fc00::3 lladdr 00:15:4d:00:00:02 nud permanent dev enp0s8
sudo ip -6 neigh add fc00::4 lladdr 00:15:4d:00:00:03 nud permanent dev enp0s8
sudo ip -6 neigh add fc00::5 lladdr ac:1f:6b:67:06:40 nud permanent dev enp0s8
sudo ip -6 neigh add fc00::9 lladdr 00:15:4d:00:00:04 nud permanent dev enp0s8
sudo sysctl -w net.ipv6.conf.all.seg6_require_hmac=-1
sudo sysctl -w net.ipv6.conf.all.accept_source_route=1
sudo sysctl -w net.ipv6.conf.all.forwarding=1
sudo sysctl -w net.ipv6.conf.enp0s8.seg6_require_hmac=-1
sudo sysctl -w net.ipv6.conf.enp0s8.seg6_enabled=1
sudo sysctl -p |
sudo apt-get -y install xdotool
|
#!/bin/bash
for file in $(git diff --cached --name-only --diff-filter=ACM "*.js")
do
# we only want to lint the staged changes, not any unstaged changes
git show ":$file" | node_modules/.bin/eslint --stdin --stdin-filename "$file"
if [ $? -ne 0 ]; then
echo "ESLint failed on staged file '$file'. Please check your code and try again."
exit 1 # exit with failure status
fi
done
|
# Set the path to save checkpoints
OUTPUT_DIR='YOUR_PATH/k400_videomae_pretrain_large_patch16_224_frame_16x4_tube_mask_ratio_0.9_e1600'
# Set the path to Kinetics train set.
DATA_PATH='YOUR_PATH/list_kinetics-400/train.csv'
# batch_size can be adjusted according to number of GPUs
# this script is for 64 GPUs (8 nodes x 8 GPUs)
OMP_NUM_THREADS=1 python -m torch.distributed.launch --nproc_per_node=8 \
--master_port 12320 --nnodes=8 --node_rank=$1 --master_addr=$2 \
run_mae_pretraining.py \
--data_path ${DATA_PATH} \
--mask_type tube \
--mask_ratio 0.9 \
--model pretrain_videomae_large_patch16_224 \
--decoder_depth 12 \
--batch_size 8 \
--num_frames 16 \
--sampling_rate 4 \
--opt adamw \
--opt_betas 0.9 0.95 \
--warmup_epochs 40 \
--save_ckpt_freq 20 \
--epochs 1601 \
--log_dir ${OUTPUT_DIR} \
--output_dir ${OUTPUT_DIR} |
<filename>utils_OR/DatasetCreation/tempRemoveLight.py
import glob
import os.path as osp
import os
roots = ['mainDiffMat_xml', 'mainDiffMat_xml1']
for root in roots:
scenes = glob.glob(osp.join(root, 'scene*') )
for scene in scenes:
print(scene )
if osp.isdir(scene ):
os.system('rm %s' % (osp.join(scene, 'imenvDirect_*.hdr') ) )
os.system('rm %s' % (osp.join(scene, 'imshadingDirect_*.rgbe') ) )
|
#!/bin/bash
#
# Copyright SecureKey Technologies Inc. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
# Environment variables that affect this script:
# GO_TESTFLAGS: Flags are added to the go test command.
# GO_LDFLAGS: Flags are added to the go test command (example: -s).
# TEST_CHANGED_ONLY: Boolean on whether to only run tests on changed packages.
# TEST_RACE_CONDITIONS: Boolean on whether to test for race conditions.
# TEST_WITH_LINTER: Boolean on whether to run linter prior to unit tests.
# FABRIC_SDKGO_CODELEVEL_TAG: Go tag that represents the fabric code target
# FABRIC_SDKGO_CODELEVEL_VER: Version that represents the fabric code target (primarily for fixture lookup)
# FABRIC_SDKGO_TESTRUN_ID: An identifier for the current run of tests.
# FABRIC_CRYPTOCONFIG_VERSION: Version of cryptoconfig fixture to use
set -e
GO_CMD="${GO_CMD:-go}"
FABRIC_SDKGO_CODELEVEL_TAG="${FABRIC_SDKGO_CODELEVEL_TAG:-devstable}"
FABRIC_SDKGO_TESTRUN_ID="${FABRIC_SDKGO_TESTRUN_ID:-${RANDOM}}"
FABRIC_CRYPTOCONFIG_VERSION="${FABRIC_CRYPTOCONFIG_VERSION:-v1}"
TEST_CHANGED_ONLY="${TEST_CHANGED_ONLY:-false}"
TEST_RACE_CONDITIONS="${TEST_RACE_CONDITIONS:-true}"
TEST_WITH_LINTER="${TEST_WITH_LINTER:-false}"
SCRIPT_DIR="$(dirname "$0")"
CONFIG_DIR=$(pwd)
GOMOD_PATH=$(cd ${SCRIPT_DIR} && ${GO_CMD} env GOMOD)
PROJECT_MODULE=$(awk -F' ' '$1 == "module" {print $2}' ${GOMOD_PATH})
PROJECT_DIR=$(dirname ${GOMOD_PATH})
MODULE="${MODULE:-${PROJECT_MODULE}}"
MODULE_PATH="${PROJECT_DIR}/${MODULE#${PROJECT_MODULE}}" && MODULE_PATH=${MODULE_PATH%/}
PKG_ROOT="${PKG_ROOT:-./}"
source ${SCRIPT_DIR}/lib/find_packages.sh
source ${SCRIPT_DIR}/lib/linter.sh
echo "Running" $(basename "$0") "(${MODULE} ${PKG_ROOT})"
# Find all packages that should be tested.
PWD_ORIG=$(pwd)
cd "${MODULE_PATH}"
declare -a PKG_SRC=(
"${PKG_ROOT}"
)
declare PKG_EXCLUDE=""
findPackages
# Reduce unit tests to changed packages.
if [ "${TEST_CHANGED_ONLY}" = true ]; then
findChangedFiles
declare matcher='( |^)(test/fixtures/|test/metadata/|test/scripts/|Makefile( |$)|go.mod( |$)|golangci.yml( |$)|ci.properties( |$))'
if [[ "${CHANGED_FILES[@]}" =~ ${matcher} ]]; then
echo "Test scripts, fixtures or metadata changed - running all tests"
else
findChangedPackages
filterExcludedPackages
appendDepPackages
PKGS=(${DEP_PKGS[@]})
fi
fi
RACEFLAG=""
if [ "${TEST_RACE_CONDITIONS}" = true ]; then
ARCH=$(uname -m)
if [ "${ARCH}" = "x86_64" ]; then
echo "Enabling data race detection"
RACEFLAG="-race"
else
echo "Data race detection not supported on ${ARCH}"
fi
fi
if [ ${#PKGS[@]} -eq 0 ]; then
echo "Skipping tests since no packages were changed"
exit 0
fi
if [ "${TEST_WITH_LINTER}" = true ]; then
runLinter
fi
# filter out excluded tests
PKGS=($(echo "${PKGS[@]}" | tr ' ' '\n' | \
grep -v ^${PROJECT_MODULE}/pkg/core/cryptosuite/bccsp/multisuite | \
grep -v ^${PROJECT_MODULE}/pkg/core/cryptosuite/bccsp/pkcs11 | \
grep -v ^${PROJECT_MODULE}/pkg/core/cryptosuite/common/pkcs11 | \
grep -v ^${PROJECT_MODULE}/pkg/client/channel/benchmark | \
tr ' ' '\n'))
echo "Code level ${FABRIC_SDKGO_CODELEVEL_TAG} (Fabric ${FABRIC_SDKGO_CODELEVEL_VER})"
echo "Running unit tests..."
GO_TAGS="${GO_TAGS} ${FABRIC_SDKGO_CODELEVEL_TAG}"
GO_LDFLAGS="${GO_LDFLAGS} -X ${PROJECT_MODULE}/test/metadata.ProjectPath=${PROJECT_DIR}"
GO_LDFLAGS="${GO_LDFLAGS} -X ${PROJECT_MODULE}/test/metadata.ChannelConfigPath=test/fixtures/fabric/${FABRIC_SDKGO_CODELEVEL_VER}/channel"
GO_LDFLAGS="${GO_LDFLAGS} -X ${PROJECT_MODULE}/test/metadata.CryptoConfigPath=test/fixtures/fabric/${FABRIC_CRYPTOCONFIG_VERSION}/crypto-config"
GO_LDFLAGS="${GO_LDFLAGS} -X ${PROJECT_MODULE}/test/metadata.TestRunID=${FABRIC_SDKGO_TESTRUN_ID}"
${GO_CMD} test ${RACEFLAG} -cover -tags "testing ${GO_TAGS}" ${GO_TESTFLAGS} -ldflags="${GO_LDFLAGS}" ${PKGS[@]} -p 1 -timeout=40m
echo "Unit tests finished successfully"
cd ${PWD_ORIG}
|
def highest_prime_factor(num):
prime_factors = []
i = 2
while i*i <= num:
if num % i:
i += 1
else:
num //= i
prime_factors.append(i)
if num > 1:
prime_factors.append(num)
if len(prime_factors) > 0:
return max(prime_factors)
else:
return None |
<reponame>sparber/CComprehensiveDatatypes<filename>src/tree/symbols/TSExcl.java
package tree.symbols;
import tree.DefaultTreeNodeSymbol;
public class TSExcl extends DefaultTreeNodeSymbol {
public static int id = EXCL;
public static String text = "!";
public TSExcl() {
super(text, id);
}
}
|
package com.github.danildorogoy.template;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.RowConstraints;
public class StatusBar extends HBox {
private Button resetButton;
public Label whitePlayerAlert;
public Label blackPlayerAlert;
public Label whitePlayerTimer;
public Label blackPlayerTimer;
public Label winner;
private GridPane statusBarGp;
public StatusBar() {
statusBarGp = new GridPane();
resetButton = new Button("Reset");
whitePlayerAlert = new Label("");
blackPlayerAlert = new Label("");
whitePlayerTimer = new Label("");
blackPlayerTimer = new Label("");
winner = new Label("");
ColumnConstraints column = new ColumnConstraints();
column.setPercentWidth(30);
statusBarGp.getColumnConstraints().add(column);
column = new ColumnConstraints();
column.setPercentWidth(30);
statusBarGp.getColumnConstraints().add(column);
column = new ColumnConstraints();
column.setPercentWidth(30);
statusBarGp.getColumnConstraints().add(column);
statusBarGp.setPrefSize(2000, 100);
statusBarGp.getRowConstraints().add(new RowConstraints(70 / 2));
statusBarGp.getRowConstraints().add(new RowConstraints(70 / 2));
statusBarGp.addRow(0, whitePlayerAlert, resetButton, blackPlayerAlert);
statusBarGp.addRow(1, whitePlayerTimer, winner, blackPlayerTimer);
for (Node n : statusBarGp.getChildren()) {
GridPane.setHalignment(n, HPos.CENTER);
GridPane.setValignment(n, VPos.CENTER);
if (n instanceof Label) {
n.setStyle("-fx-font-size: 10pt; -fx-font-weight: bold; -fx-opacity: 1.0;");
}
}
statusBarGp.setVgap(10);
statusBarGp.setHgap(10);
statusBarGp.setPadding(new Insets(10, 10, 10, 10));
statusBarGp.setStyle("-fx-background-color: burlyWood; " +
"-fx-effect: innershadow(gaussian, rgba(0,0,0,0.4), 75, 0.5, 0, 10);");
statusBarGp.setSnapToPixel(false);
getChildren().add(statusBarGp);
}
public void resize(double width, double height) {
super.resize(width, height);
setWidth(width);
setHeight(height);
}
public Button getResetButton() {
return resetButton;
}
} |
#!/bin/sh
# -----------------------------------------------------
# Run with -help for usage.
# If $JAVA_HOME is set, editing this script should not be required.
# Send any questions to fchoong@user.sourceforge.net
# -----------------------------------------------------
# the value set here will override the value passed by $JAVA_HOME or the -jdkhome switch
jdkhome=""
jargs=""
thread_flag=""
PRG=$0
#
# resolve symlinks
#
while [ -h "$PRG" ]; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '^.*-> \(.*\)$' 2>/dev/null`
if expr "$link" : '^/' 2> /dev/null >/dev/null; then
PRG="$link"
else
PRG="`dirname $PRG`/$link"
fi
done
progdir=`dirname $PRG`
progname=`basename $0`
# ../ will lead us to the home
dbhome="$progdir/.."
# absolutize dbhome
dbhome=`cd ${dbhome}; pwd`
#
# bring in needed functions
. ${dbhome}/lib/functions
#--------------------------------------------------------------------------------------------------------------
pre_main
#
# let's go
#
cd $dbhome/data
exec "$jdkhome/bin/java" $thread_flag -classpath "$cp" $jargs "org.hsqldb.Server" "$@"
# and we exit.
|
<filename>src/components/Header.test.tsx
import * as React from 'react';
import * as enzyme from 'enzyme';
import Header from './Header';
import * as Adapter from 'enzyme-adapter-react-16';
enzyme.configure({ adapter: new Adapter() });
it("renders 'new merchant' link in the header when type is merchants_index",()=>{
const header=enzyme.render(<Header type="merchants_index"/>);
expect(header.find(".text-xs-right").text()).toContain("New Merchant")
});
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package brooklyn.entity.monitoring.monit;
import static brooklyn.util.JavaGroovyEquivalents.elvis;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import brooklyn.entity.BrooklynAppLiveTestSupport;
import brooklyn.entity.basic.Entities;
import brooklyn.entity.basic.SameServerEntity;
import brooklyn.entity.basic.SoftwareProcess;
import brooklyn.entity.database.mysql.MySqlNode;
import brooklyn.entity.proxying.EntitySpec;
import brooklyn.event.basic.DependentConfiguration;
import brooklyn.location.MachineDetails;
import brooklyn.location.basic.LocalhostMachineProvisioningLocation;
import brooklyn.test.Asserts;
import brooklyn.test.EntityTestUtils;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
public class MonitIntegrationTest extends BrooklynAppLiveTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(MonitIntegrationTest.class);
LocalhostMachineProvisioningLocation loc;
Process testProcess;
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
super.setUp();
loc = app.newLocalhostProvisioningLocation();
testProcess = (new ProcessBuilder()).command("vi", "monittest").start();
}
@AfterMethod(alwaysRun = true)
@Override
public void tearDown() throws Exception {
try {
super.tearDown();
} finally {
if (testProcess != null) {
testProcess.destroy();
}
}
}
@Test(groups = "Integration")
public void test_localhost() throws Exception {
final MonitNode monitNode = app.createAndManageChild(EntitySpec.create(MonitNode.class)
.configure(MonitNode.CONTROL_FILE_URL, "classpath:///brooklyn/entity/monitoring/monit/monit.monitrc"));
app.start(ImmutableSet.of(loc));
LOG.info("Monit started");
EntityTestUtils.assertAttributeEqualsEventually(monitNode, MonitNode.MONIT_TARGET_PROCESS_STATUS, "Running");
}
@Test(groups = "Integration")
public void test_monitorMySql() throws Exception {
SameServerEntity sameServerEntity = app.createAndManageChild(EntitySpec.create(SameServerEntity.class));
MySqlNode mySqlNode = sameServerEntity.addChild(EntitySpec.create(MySqlNode.class));
Entities.manage(mySqlNode);
Function<String, Map<String, Object>> controlFileSubstitutionsFunction = new Function<String, Map<String, Object>>() {
public Map<String, Object> apply(String input) {
return ImmutableMap.<String, Object>of("targetPidFile", input);
}
};
EntitySpec<MonitNode> monitSpec = EntitySpec.create(MonitNode.class)
.configure(MonitNode.CONTROL_FILE_URL, "classpath:///brooklyn/entity/monitoring/monit/monitmysql.monitrc")
.configure(MonitNode.CONTROL_FILE_SUBSTITUTIONS, DependentConfiguration.valueWhenAttributeReady(mySqlNode,
SoftwareProcess.PID_FILE, controlFileSubstitutionsFunction));
final MonitNode monitNode = sameServerEntity.addChild(monitSpec);
Entities.manage(monitNode);
app.start(ImmutableSet.of(loc));
LOG.info("Monit and MySQL started");
EntityTestUtils.assertAttributeEqualsEventually(monitNode, MonitNode.MONIT_TARGET_PROCESS_STATUS, "Running");
mySqlNode.stop();
Asserts.succeedsEventually(new Runnable() {
@Override
public void run() {
String targetStatus = monitNode.getAttribute(MonitNode.MONIT_TARGET_PROCESS_STATUS);
LOG.debug("MonitNode target status: {}", targetStatus);
assertNotEquals(elvis(targetStatus, ""), "Running");
}
});
mySqlNode.restart();
EntityTestUtils.assertAttributeEqualsEventually(monitNode, MonitNode.MONIT_TARGET_PROCESS_STATUS, "Running");
}
@Test(groups = "Integration")
public void test_monitorMySqlAutoRestart() throws Exception {
// This runs on localhost; free to obtain another machine with impunity.
final String osFlavor;
MachineDetails machineDetails = app.getExecutionContext().submit(new Callable<MachineDetails>() {
public MachineDetails call() throws Exception {
return loc.obtain().getMachineDetails();
}}).get();
if (machineDetails.getOsDetails().isMac()) {
osFlavor = "osx10.6-x86_64";
} else if (machineDetails.getOsDetails().isWindows()) {
throw new UnsupportedOperationException("Windows not supported for test_monitorMySqlAutoRestart");
} else {
osFlavor = "linux2.6-x86_64"; // assume 64 bit linux
}
// The monit node needs to know the installation and run directory of the mysql dir, so we need to specify it explicitly
File tempDir = Files.createTempDir();
tempDir.deleteOnExit();
final String mySqlInstallDir = tempDir.getAbsolutePath() + "/install";
final String mySqlRunDir = tempDir.getAbsolutePath() + "/run";
final String mySqlDataDir = tempDir.getAbsolutePath() + "/data";
final String mySqlVersion = MySqlNode.SUGGESTED_VERSION.getDefaultValue();
SameServerEntity sameServerEntity = app.createAndManageChild(EntitySpec.create(SameServerEntity.class));
final MySqlNode mySqlNode = sameServerEntity.addChild(EntitySpec.create(MySqlNode.class)
.configure(MySqlNode.INSTALL_DIR, mySqlInstallDir)
.configure(MySqlNode.RUN_DIR, mySqlRunDir)
.configure(MySqlNode.DATA_DIR, mySqlDataDir));
Entities.manage(mySqlNode);
Function<String, Map<String, Object>> controlFileSubstitutionsFunction = new Function<String, Map<String, Object>>() {
public Map<String, Object> apply(String input) {
return ImmutableMap.<String, Object>of(
"targetPidFile", input,
"mySqlInstallDir", mySqlInstallDir,
"mySqlRunDir", mySqlRunDir,
"mySqlVersion", mySqlVersion,
"mySqlOsFlavor", osFlavor
);
}
};
EntitySpec<MonitNode> monitSpec = EntitySpec.create(MonitNode.class)
.configure(MonitNode.CONTROL_FILE_URL, "classpath:///brooklyn/entity/monitoring/monit/monitmysqlwithrestart.monitrc")
.configure(MonitNode.CONTROL_FILE_SUBSTITUTIONS, DependentConfiguration.valueWhenAttributeReady(mySqlNode,
SoftwareProcess.PID_FILE, controlFileSubstitutionsFunction));
final MonitNode monitNode = sameServerEntity.addChild(monitSpec);
Entities.manage(monitNode);
app.start(ImmutableSet.of(loc));
LOG.info("Monit and MySQL started");
final String[] initialPid = {""};
Asserts.succeedsEventually(new Runnable() {
@Override
public void run() {
String targetStatus = monitNode.getAttribute(MonitNode.MONIT_TARGET_PROCESS_STATUS);
LOG.debug("MonitNode target status: {}", targetStatus);
assertEquals(elvis(targetStatus, ""), "Running");
try {
initialPid[0] = Files.readFirstLine(new File(mySqlNode.getAttribute(SoftwareProcess.PID_FILE)), Charset.defaultCharset());
LOG.debug("Initial PID: {}", initialPid[0]);
} catch (IOException e) {
Asserts.fail("Could not read PID file: " + e);
}
}
});
mySqlNode.stop();
EntityTestUtils.assertAttributeEqualsEventually(monitNode, MonitNode.MONIT_TARGET_PROCESS_STATUS, "Running");
// NOTE: Do not manually restart the mySqlNode, it should be restarted by monit
Asserts.succeedsEventually(new Runnable() {
@Override
public void run() {
try {
String pidFileLocation = mySqlNode.getAttribute(SoftwareProcess.PID_FILE);
String newPid = Files.readFirstLine(new File(pidFileLocation), Charset.defaultCharset());
LOG.debug("Old PID: {}, New PID: {} read from PID file: {}", new String[] {initialPid[0], newPid, pidFileLocation});
assertNotEquals(initialPid[0], newPid, "Process PID has not changed");
} catch (IOException e) {
Asserts.fail("Could not read PID file: " + e);
}
String targetStatus = monitNode.getAttribute(MonitNode.MONIT_TARGET_PROCESS_STATUS);
LOG.debug("MonitNode target status: {}", targetStatus);
assertEquals(targetStatus, "Running");
}
});
}
}
|
package math;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author exponential-e
* 백준 17830번: 이진수씨의 하루 일과
*
* @see https://www.acmicpc.net/problem/17830/
*
*/
public class Boj17830 {
private static final String NEW_LINE = "\n";
private static final String SPACE = " ";
private static final char QU = '?';
private static final char MAX = '1';
private static final char MIN = '0';
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
while(T-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
char[][] input = new char[2][N];
String line = st.nextToken();
for(int i = 0; i < N; i++) {
input[1][i] = input[0][i] = line.charAt(i);
}
sb.append(todayBinary(N, input[0], MAX)).append(SPACE).append(todayBinary(N, input[1], MIN)).append(NEW_LINE);
}
System.out.println(sb.toString());
}
private static int todayBinary(int n, char[] arr, char instead) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] == QU) arr[i] = instead; // fill '1' or '0'
}
int len = 0;
int flag = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] == MAX) flag++; // first '1'
if(flag > 0) len++; // count cipher
}
len += n;
if(flag == 0) len = 1;
else if(flag == 1) len -= 1;
return len;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.