repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/AgChalcHysteresisFigureA.java | /**
q * Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import java.util.Map;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesColor;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AgChalcHysteresisFigureA {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/Circuit/AgChalcA", DataOrientation.Columns, 300, 270, ChartTheme.Matlab);
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideNW);
chart.getStyleManager().setPlotGridLinesVisible(false);
Map<String, Series> seriesMap = chart.getSeriesMap();
Series series0 = seriesMap.get("Device");
Series series1 = seriesMap.get("100 Hz");
Series series2 = seriesMap.get("1000 Hz");
Series series3 = seriesMap.get("10000 Hz");
// series0 = seriesMap.get(0);
series0.setLineStyle(SeriesLineStyle.NONE);
series0.setMarker(SeriesMarker.CIRCLE);
series0.setMarkerColor(SeriesColor.PINK);
// series1 = seriesMap.get(1);
series1.setMarker(SeriesMarker.NONE);
series1.setLineColor(SeriesColor.BLUE);
// series2 = seriesMap.get(2);
series2.setMarker(SeriesMarker.NONE);
series2.setLineStyle(SeriesLineStyle.DOT_DOT);
series2.setLineColor(SeriesColor.ORANGE);
// series3 = seriesMap.get(3);
series3.setMarker(SeriesMarker.NONE);
series3.setLineStyle(SeriesLineStyle.DASH_DASH);
series3.setLineColor(SeriesColor.PURPLE);
// Show it
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AgChalcHysteresisA.png", 300);
}
}
| 3,587 | 38.866667 | 139 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/AgChalcTimeFigureD.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import java.util.Map;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AgChalcTimeFigureD {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/Circuit/AgChalcD", DataOrientation.Columns, 300, 270, ChartTheme.Matlab);
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Time [s]");
// chart.getStyleManager().setLegendVisible(false);
chart.getStyleManager().setLegendPosition(LegendPosition.InsideNE);
chart.getStyleManager().setPlotGridLinesVisible(false);
Map<String, Series> seriesMap = chart.getSeriesMap();
Series series0 = seriesMap.get("100 Hz");
series0.setMarker(SeriesMarker.NONE);
Series series1 = seriesMap.get("150 Hz");
series1.setMarker(SeriesMarker.NONE);
series1.setLineStyle(SeriesLineStyle.DOT_DOT);
Series series2 = seriesMap.get("200 Hz");
series2.setMarker(SeriesMarker.NONE);
series2.setLineStyle(SeriesLineStyle.DASH_DASH);
// Show it
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AgChalcTimeD.png", 300);
}
}
| 3,125 | 39.597403 | 139 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/AgChalcHysteresisFigureB.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import java.util.Map;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AgChalcHysteresisFigureB {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/Circuit/AgChalcB", DataOrientation.Columns, 300, 270, ChartTheme.Matlab);
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendVisible(true);
chart.getStyleManager().setLegendPosition(LegendPosition.InsideSE);
chart.getStyleManager().setPlotGridLinesVisible(false);
Map<String, Series> seriesMap = chart.getSeriesMap();
Series series0 = seriesMap.get("V");
series0.setMarker(SeriesMarker.NONE);
Series series1 = seriesMap.get("Va");
series1.setMarker(SeriesMarker.NONE);
series1.setLineStyle(SeriesLineStyle.DOT_DOT);
Series series2 = seriesMap.get("Vb");
series2.setMarker(SeriesMarker.NONE);
series2.setLineStyle(SeriesLineStyle.DASH_DASH);
// Show it
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AgChalcHysteresisB.png", 300);
}
}
| 3,123 | 39.571429 | 139 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/AgChalcPulseFigureC.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import java.util.Map;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AgChalcPulseFigureC {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/Circuit/AgChalcC", DataOrientation.Columns, 300, 270, ChartTheme.Matlab);
chart.setYAxisTitle("Resistance [Ohm]");
chart.setXAxisTitle("Pulse Number");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideNE);
chart.getStyleManager().setPlotGridLinesVisible(false);
Map<String, Series> seriesMap = chart.getSeriesMap();
Series series0 = seriesMap.get("10 µs, 0.2 V, -0.5 V");
series0.setLineStyle(SeriesLineStyle.NONE);
Series series1 = seriesMap.get("10 µs, 0.8 V, -2.0 V");
series1.setLineStyle(SeriesLineStyle.NONE);
Series series2 = seriesMap.get("5 µs, 0.8 V, -2.0 V");
series2.setLineStyle(SeriesLineStyle.NONE);
// Show it
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AgChalcHysteresisC.png", 300);
}
}
| 3,001 | 40.123288 | 139 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/AgChalcHysteresisFigureE.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import java.util.Map;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesColor;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.StyleManager.LegendPosition;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AgChalcHysteresisFigureE {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/Circuit/AgChalcE", DataOrientation.Columns, 300, 270, ChartTheme.Matlab);
chart.setYAxisTitle("Current [mA]");
chart.setXAxisTitle("Voltage [V]");
chart.getStyleManager().setLegendPosition(LegendPosition.InsideNW);
chart.getStyleManager().setPlotGridLinesVisible(false);
Map<String, Series> seriesMap = chart.getSeriesMap();
Series series1 = seriesMap.get("100 Hz negative");
series1.setMarker(SeriesMarker.NONE);
series1.setLineColor(SeriesColor.BLUE);
Series series2 = seriesMap.get("100 Hz positive");
series2.setMarker(SeriesMarker.NONE);
series2.setLineStyle(SeriesLineStyle.DOT_DOT);
series2.setLineColor(SeriesColor.ORANGE);
// Show it
new SwingWrapper(chart).displayChart();
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AgChalcTriangleE.png", 300);
}
}
| 3,085 | 40.146667 | 139 | java |
AHaH | AHaH-master/ahah-samples/src/main/java/com/mancrd/ahah/samples/plosahah/model/AHaHRuleFigure.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.samples.plosahah.model;
import java.awt.Color;
import java.io.IOException;
import java.util.Map;
import com.xeiam.xchart.BitmapEncoder;
import com.xeiam.xchart.CSVImporter;
import com.xeiam.xchart.CSVImporter.DataOrientation;
import com.xeiam.xchart.Chart;
import com.xeiam.xchart.Series;
import com.xeiam.xchart.SeriesLineStyle;
import com.xeiam.xchart.SeriesMarker;
import com.xeiam.xchart.StyleManager.ChartTheme;
import com.xeiam.xchart.SwingWrapper;
/**
* @author timmolter
*/
public class AHaHRuleFigure {
public static void main(String[] args) throws Exception {
AHaHRuleFigure aHaHRuleFigure = new AHaHRuleFigure();
Chart chart = CSVImporter.getChartFromCSVDir("./Results/Model/AHaHRule/Functional", DataOrientation.Columns, 300, 300, ChartTheme.Matlab);
aHaHRuleFigure.go(chart, "Functional");
chart = CSVImporter.getChartFromCSVDir("./Results/Model/AHaHRule/Circuit", DataOrientation.Columns, 300, 300, ChartTheme.Matlab);
aHaHRuleFigure.go(chart, "Circuit");
}
private void go(Chart chart, String type) throws IOException {
// import chart from a folder containing CSV files
chart.setChartTitle("AHaH Rule - " + type);
chart.setYAxisTitle("dW");
chart.setXAxisTitle("y");
chart.getStyleManager().setLegendVisible(false);
chart.getStyleManager().setPlotGridLinesVisible(false);
chart.getStyleManager().setAxisTicksVisible(false);
Map<String, Series> seriesMap = chart.getSeriesMap();
Series circuitBias = seriesMap.get("Functional_Bias");
circuitBias.setLineStyle(SeriesLineStyle.NONE);
circuitBias.setMarker(SeriesMarker.CIRCLE);
circuitBias.setMarkerColor(new Color(255, 0, 0, 10));
Series circuitInputs = seriesMap.get("Functional_Inputs");
circuitInputs.setLineStyle(SeriesLineStyle.NONE);
circuitInputs.setMarker(SeriesMarker.CIRCLE);
circuitInputs.setMarkerColor(new Color(0, 0, 255, 10));
BitmapEncoder.savePNGWithDPI(chart, "./PLOS_AHAH/Figures/AHaHRule_" + type + ".png", 300);
// Show it
new SwingWrapper(chart).displayChart();
}
}
| 3,570 | 38.677778 | 142 | java |
AHaH | AHaH-master/ahah-commons/src/test/java/com/mancrd/ahah/commons/TestBitManipulate.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons;
import org.junit.Ignore;
/**
* @author alexnugent
*/
@Ignore
public class TestBitManipulate {
public static void main(String[] args) {
int i = 254;
System.out.println(Integer.toBinaryString(i));
for (int j = 0; j < 8; j++) {
System.out.println(isZero(j, i));
}
}
static public boolean isZero(int position, int value) {
int numbits = 32 - Integer.numberOfLeadingZeros(value);
int z = numbits - position - 1;
return (value &= (1 << z)) == 0;
}
}
| 2,004 | 32.983051 | 94 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/LRUCache.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* A specialized LRUCache where only keys are put into it. The values associated with the keys are managed internally.
*
* @author timmolter
*/
public class LRUCache {
private static final float HASH_TABLE_LOAD_FACTOR = 0.75f;
/** the internal Map containing the key, value pairs */
private LinkedHashMap<String, Integer> map;
private int cacheSize;
private boolean capacityReached = false;
private String lastKey = null;
private int nextLabel = 0;
private boolean reassign = false;
/**
* Constructor
*
* @param cacheSize the maximum number of entries that will be kept in this cache.
*/
public LRUCache(int cacheSize) {
if (cacheSize <= 1) {
throw new IllegalArgumentException("It makes no sense to have a cache of size less than two!");
}
this.cacheSize = cacheSize;
int hashTableCapacity = (int) Math.ceil(cacheSize / HASH_TABLE_LOAD_FACTOR) + 1;
map = new LinkedHashMap<String, Integer>(hashTableCapacity, HASH_TABLE_LOAD_FACTOR, true) {
/**
* This method is invoked by put and putAll AFTER inserting a new entry into the map.
*
* @param eldest - The least recently inserted entry in the map, or if this is an access-ordered map, the least recently accessed entry. This is
* the entry that will be removed it this method returns true. If the map was empty prior to the put or putAll invocation resulting in
* this invocation, this will be the entry that was just inserted; in other words, if the map contains a single entry, the eldest entry
* is also the newest.
* @returns true if the eldest entry should be removed from the map; false if it should be retained.
*/
@Override
protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
if (size() > LRUCache.this.cacheSize) {
LRUCache.this.capacityReached = true;
Integer eldestLabel = eldest.getValue();
map.put(LRUCache.this.lastKey, eldestLabel); // override last put with correct label
LRUCache.this.reassign = true;
return true; // tell it to remove the eldest
}
else {
LRUCache.this.reassign = false;
if (!LRUCache.this.capacityReached) {// if the max size has not been reached then increment the label
LRUCache.this.nextLabel++;
}
return false;
}
}
};
}
/**
* Adds an entry to this cache. The new entry becomes the MRU (most recently used) entry. If an entry with the specified key already exists in the
* cache, it is replaced by the new entry. If the cache is full, the LRU (least recently used) entry is removed from the cache.
*
* @param signature - the key with which the specified value is to be associated. This is usually a String or an Integer
*/
public Integer put(String signature) {
this.lastKey = signature;
Integer label = map.get(signature);
if (label == null) { // no match, add. When added the LRUCache will overwrite the least recently used row, assigning the new id to the row id.
addEntry(signature);
label = map.get(signature);
}
return label;
}
private void addEntry(String key) {
map.put(key, nextLabel);
}
/**
* Returns whether or not the last insert was an overwrite or not.
*
* @return
*/
public boolean isReassign() {
return reassign;
}
/**
* resets everything to new state
*/
public void reset() {
map.clear();
nextLabel = 0;
reassign = false;
}
/**
* Returns the number of used entries in the cache.
*
* @return the number of entries currently in the cache.
*/
public int size() {
return map.size();
}
/**
* check if the CAM is full
*/
public boolean isFull() {
return map.size() == this.cacheSize;
}
/**
* check the max size of the CAM
*/
public int maxSize() {
return this.cacheSize;
}
/**
* get the internal key/value (Signature/Lables) map of the CAM
*/
public LinkedHashMap<String, Integer> getMap() {
return this.map;
}
/**
* Returns a <code>Collection</code> that contains a copy of all cache entries.
*
* @return a <code>Collection</code> with a copy of the cache content.
*/
public Collection<Map.Entry<String, Integer>> getAll() {
return new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
}
/**
* given a label, return the signature
*/
public String reverseLookup(Integer label) {
for (Entry<String, Integer> entry : map.entrySet()) {
if (label.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
sb.append(entry.getKey());
sb.append(" | ");
sb.append(entry.getValue());
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
}
| 6,711 | 30.218605 | 150 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/LinkWeight.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons;
/**
* @author alexnugent
*/
public class LinkWeight implements Comparable<LinkWeight> {
private final long spike;
private final int label;
private final double weight;
private String labelString;
private String spikeString;
/**
* Constructor
*
* @param feature
* @param label
* @param weight
*/
public LinkWeight(long spike, int label, double weight) {
this.spike = spike;
this.label = label;
this.weight = weight;
}
public long getSpike() {
return spike;
}
public int getLabel() {
return label;
}
public double getWeight() {
return weight;
}
@Override
public int compareTo(LinkWeight other) {
if (other.getWeight() > getWeight()) {
return 1;
}
else if (other.getWeight() < getWeight()) {
return -1;
}
return 0;
}
@Override
public String toString() {
return spikeString + "/" + spike + "-->(" + weight + ")-->" + labelString + "/" + label;
}
public String getLabelString() {
return labelString;
}
public void setLabelString(String labelString) {
this.labelString = labelString;
}
public String getSpikeString() {
return spikeString;
}
public void setSpikeString(String spikeString) {
this.spikeString = spikeString;
}
}
| 2,803 | 24.261261 | 94 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/spikes/SpikeEncoder.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.spikes;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import com.mancrd.ahah.commons.LinkWeight;
/**
* @author alexnugent
*/
public abstract class SpikeEncoder<T> implements Serializable {
private static final long idMask = 65535;// 0b1111111111111111;
private final TIntObjectMap<String> reverseMap;
/** abstract methods */
public abstract Set<String> getSpikes(T data);
public abstract short getUniquePositiveID();
/**
* Constructor
*/
public SpikeEncoder() {
reverseMap = new TIntObjectHashMap<String>();
}
public long[] encode(T data) {
Set<String> stringSpikes = getSpikes(data);
long[] spikes = new long[stringSpikes.size()];
int idx = 0;
for (String s : stringSpikes) {
int iSpike = s.hashCode();
if (!reverseMap.containsKey(iSpike)) {
reverseMap.put(iSpike, s);
}
spikes[idx] = (long) iSpike << 16 | getUniquePositiveID();
idx++;
}
return spikes;
}
public short getIdFromSpike(long compositeSpike) {
return (short) (compositeSpike & idMask);
}
public int getOriginalSpikeIDFromComposite(long compositeSpike) {
return (int) (compositeSpike >> 16);
}
public void setSpikeLabel(List<LinkWeight> linkWeights) {
for (LinkWeight linkWeight : linkWeights) {
linkWeight.setSpikeString(getSpikeLabel(getOriginalSpikeIDFromComposite(linkWeight.getSpike())));
}
}
public String getSpikeLabel(int spike) {
return reverseMap.get(spike);
}
public String getSpikeLabel(long spike) {
if (getIdFromSpike(spike) == getUniquePositiveID()) {
return reverseMap.get(getOriginalSpikeIDFromComposite(spike));
}
return null;
}
public TIntObjectMap<String> getReverseMap() {
return reverseMap;
}
public int getSpikePatternSpace() {
return reverseMap.size();
}
}
| 3,460 | 27.841667 | 103 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/spikes/KNearestNeighbors.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.spikes;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.mancrd.ahah.commons.LRUCache;
/**
* @author alexnugent
*/
public class KNearestNeighbors {
private final LRUCache lruCache;
private final Center[] centers;
private final int maxCenters;
private final double repRatio;
private int idx = 0;
/**
* Constructor
*
* @param maxCenters
* @param inputDimension
* @param repRatio
*/
public KNearestNeighbors(int maxCenters, int inputDimension, double repRatio) {
lruCache = new LRUCache(maxCenters);
centers = new Center[maxCenters];
this.maxCenters = maxCenters;
this.repRatio = repRatio;
}
public Set<String> encode(double[] input, int numSpikes) {
if (lruCache.size() < maxCenters) {
Center newCenter = new Center(input, idx++ + "");
centers[lruCache.put(newCenter.getId())] = newCenter;
return new HashSet<String>();
}
double aveDistance = 0;
for (int i = 0; i < centers.length; i++) {
aveDistance += centers[i].setDistance(input);
}
aveDistance /= centers.length;
Arrays.sort(centers);
Set<String> spikes = new HashSet<String>();
for (int i = 0; i < numSpikes; i++) {
spikes.add(centers[i].getId());
if (i > numSpikes) {
break;
}
}
double r = centers[0].getDistance() / aveDistance;
if (r > repRatio) {
Center newCenter = new Center(input, idx++ + "");
centers[lruCache.put(newCenter.getId())] = newCenter;// replaces the least-recently-used
}
return spikes;
}
}
class Center implements Comparable<Center> {
private double[] center;
private double distance;
private final String id;
public Center(double[] center, String id) {
this.center = center;
this.id = id;
}
public void setCenter(double[] center) {
this.center = center;
}
public double getDistance() {
return distance;
}
public String getId() {
return id;
}
public double setDistance(double[] input) {
distance = 0;
for (int i = 0; i < input.length; i++) {
distance += Math.pow((input[i] - center[i]), 2);
}
distance = Math.sqrt(distance);
return distance;
}
@Override
public int compareTo(Center o) {
if (o.getDistance() < getDistance()) {
return 1;
}
else if (o.getDistance() > getDistance()) {
return -1;
}
return 0;
}
@Override
public String toString() {
return Arrays.toString(center) + ", " + distance + ", " + id;
// return distance + ", " + id;
}
}
| 4,089 | 25.050955 | 94 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/spikes/AhahTree.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.spikes;
/**
* This class takes a spike code in an arbitrary dimension and converts it to a spike code in the given dimension R=2^depth.
*
* @author alexnugent
*/
public class AhahTree {
private AhahTree zeroBranch;
private AhahTree oneBranch;
private final TreeNode node;
private static int depth = 8;
/**
* Constructor
*
* @param depth
*/
public AhahTree(int depth) {
AhahTree.depth = depth;
node = new TreeNode();
}
private AhahTree() {
node = new TreeNode();
}
public long encode(long[] spikes) {
return update(spikes, new StringBuffer());
}
public long update(long[] spikes, StringBuffer path) {
int z = node.update(spikes);
if (z == 1) { // take one path
path.append("1");
if (path.length() == depth) {
return path.toString().hashCode();
}
else {
if (oneBranch == null) {
oneBranch = new AhahTree();
}
return oneBranch.update(spikes, path);
}
}
else {// take zero path
path.append("0");
if (path.length() == depth) {
return path.toString().hashCode();
}
else {
if (zeroBranch == null) {
zeroBranch = new AhahTree();
}
return zeroBranch.update(spikes, path);
}
}
}
}
| 2,818 | 26.910891 | 124 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/spikes/TreeNode.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.spikes;
import gnu.trove.map.hash.TLongIntHashMap;
/**
* A node within an AHaHTree. Multiplies in incoming spike pattern by a static random binary hyperplane, which reduces to a strict sum over the spike pattern.
* Anti-Hebbian learning is used to adjust the bias to find a 50-50 split of incoming data. ID's of TreeNodes contained in the route up the tree is the spike code.
*
* @author alexnugent
*/
class TreeNode {
private static double LEARN_RATE = .01;
TLongIntHashMap weights = new TLongIntHashMap();
private double bias = 0;
int update(long[] spikes) {
double y = 0;
for (long spike : spikes) {
y += getWeight(spike);
}
y += bias;
bias += (float) (-LEARN_RATE * y);
int output = 1;
if (y < 0) {
output = -1;
}
return output;
}
private int getWeight(long spike) {
if (weights.contains(spike)) {
return weights.get(spike);
}
else {
if (Math.random() > .5) {
weights.put(spike, 1);
return 1;
}
else {
weights.put(spike, -1);
return -1;
}
}
}
}
| 2,616 | 29.430233 | 163 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/spikes/AHaHA2D.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.spikes;
import java.io.Serializable;
/**
* An AHaHA2D instance is used to convert real-valued signals into a spike code. It is a decision tree nodes operating anti-hebbian plasticity. A AHaHA2D takes values in the update
* method and bins the data set into the low or high bin recursively from the trunk
* of the decision tree to the leaves. The update method returns a binary number encoded as an integer giving routing path up the tree. A call to "putAndParse" will convert this path to a spike code
* consisting of the distinct nodes alone the route.
*
* @author alexnugent
*/
public class AHaHA2D implements Serializable {
private double lRate = .01;
/** Each AHaHA2D (except for the leaves on the tree) are split into a high and low bin split at the average value the TreeBinner receives. Average is computed through Anti-Hebbian learning. */
private AHaHA2D lowBin;
private AHaHA2D highBin;
private float w = 0;
/**
* Constructor
*
* @param depth
*/
public AHaHA2D(int depth) {
if (depth > 0) {
int d = depth - 1;
highBin = new AHaHA2D(d);
lowBin = new AHaHA2D(d);
}
}
public int put(double input) {
int path = 1;
return getState(input, path);
}
public int[] putAndParse(double input) {
int id = put(input);
int numbits = getNumBits(id);
int[] out = new int[numbits - 1];
for (int i = 0; i < out.length; i++) {
out[i] = id >> (numbits - i - 1);
}
return out;
}
public double get(int id) {
return -getPrivate(id, getNumBits(id) - 2);
}
private double getPrivate(int id, int depth) {
if (depth <= 0) {
return w;
}
if (isZero(depth, id)) {
return lowBin.getPrivate(id, depth - 1);
}
else {
return highBin.getPrivate(id, depth - 1);
}
}
private static boolean isZero(int position, int value) {
return (value &= (1 << position)) == 0;
}
public static int getNumBits(int value) {
return 32 - Integer.numberOfLeadingZeros(value);
}
/**
* @param input
* @param sb
*/
private int getState(double input, int path) {
double y = input + w;
this.w -= lRate * y;// anti-hebbian learning
if (y >= 0) {
path = (path << 1) | 1;// took a right, add a one
if (highBin == null) {
return path;
}
else {
return highBin.getState(input, path);
}
}
else {
path = (path << 1);// took a left, add a zero
if (lowBin == null) {// terminal leaf
return path;
}
else {
return lowBin.getState(input, path);
}
}
}
public double getlRate() {
return lRate;
}
public void setlRate(double lRate) {
this.lRate = lRate;
}
}
| 4,250 | 26.967105 | 198 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/utils/FileUtils.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author timmolter
*/
public final class FileUtils {
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
/**
* Constructor - Private constructor to prevent instantiation
*/
private FileUtils() {
}
/**
* Given a path to a File, return the content of the file as a String
*
* @param file
* @return
*/
public static String readFileToString(String filePath) {
String result = null;
File file = new File(filePath);
if (!file.exists()) {
logger.error("SOURCE FILE (" + filePath + ") NOT FOUND!!!");
return null;
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
result = readerToString(reader);
} catch (FileNotFoundException e) {
logger.error("ERROR IN READFILETOSTRING!!!", e);
}
// show file contents here
return result;
}
/**
* Given a File from the classpath, return the content of the file as a String
*
* @param fileName
* @return
*/
public static String readFileFromClasspathToString(String fileName) {
BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtils.class.getClassLoader().getResourceAsStream(fileName)));
String result = readerToString(reader);
// show file contents here
return result;
}
private static String readerToString(BufferedReader reader) {
StringBuffer sb = new StringBuffer();
try {
String text = null;
// repeat until all lines are read
while ((text = reader.readLine()) != null) {
sb.append(text).append(System.getProperty("line.separator"));
}
} catch (FileNotFoundException e) {
logger.error("ERROR IN READFILETOSTRING!!!", e);
} catch (IOException e) {
logger.error("ERROR IN READFILETOSTRING!!!", e);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
logger.error("ERROR IN READFILETOSTRING!!!", e);
}
}
// show file contents here
return sb.toString();
}
public static Object deserialize(File file) {
// Read from disk using FileInputStream
Object obj = null;
try {
FileInputStream f_in = new FileInputStream(file.getAbsoluteFile());
// Read object using ObjectInputStream
ObjectInputStream obj_in = new ObjectInputStream(f_in);
// Read an object
obj = obj_in.readObject();
return obj;
} catch (Exception e) {
logger.error("Error deserializing " + file.getAbsolutePath(), e);
}
return null;
}
public static void serialize(Object object, String path) {
// Write to disk with FileOutputStream
try {
FileOutputStream f_out = new FileOutputStream(path);
// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new ObjectOutputStream(f_out);
// Write object out to disk
obj_out.writeObject(object);
} catch (Exception e) {
logger.error("Error serializing object.", e);
}
}
/**
* This method returns the names of all the files found in the given directory
*
* @param dirName - ex. "./images/colors/original/" *make sure you have the '/' on the end
* @return String[] - an array of file names
*/
public static String[] getAllFileNames(String dirName) {
File dir = new File(dirName);
File[] files = dir.listFiles(); // returns files and folders
if (files != null) {
List<String> fileNames = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
fileNames.add(files[i].getName());
}
}
return fileNames.toArray(new String[fileNames.size()]);
}
else {
logger.debug(dirName + " does not denote a valid directory!");
return new String[0];
}
}
/**
* This method returns the Files found in the given directory
*
* @param dirName - ex. "./images/colors/original/" *make sure you have the '/' on the end
* @return File[] - an array of files
*/
public static File[] getAllFiles(String dirName) {
File dir = new File(dirName);
File[] files = dir.listFiles(); // returns files and folders
if (files != null) {
List<File> filteredFiles = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
filteredFiles.add(files[i]);
}
}
return filteredFiles.toArray(new File[filteredFiles.size()]);
}
else {
logger.debug(dirName + " does not denote a valid directory!");
return new File[0];
}
}
/**
* This method returns the names of all the files found in the given directory matching the given regular expression.
*
* @param dirName - ex. "./images/colors/original/" *make sure you have the '/' on the end
* @param regex - ex. ".*.png"
* @return String[] - an array of file names
*/
public static String[] getAllFileNames(String dirName, String regex) {
String[] allFileNames = getAllFileNames(dirName);
List<String> matchingFileNames = new ArrayList<String>();
for (int i = 0; i < allFileNames.length; i++) {
if (allFileNames[i].matches(regex)) {
matchingFileNames.add(allFileNames[i]);
}
}
return matchingFileNames.toArray(new String[matchingFileNames.size()]);
}
/**
* This method returns the files found in the given directory matching the given regular expression.
*
* @param dirName - ex. "./images/colors/original/" *make sure you have the '/' on the end
* @param regex - ex. ".*.png"
* @return File[] - an array of files
*/
public static File[] getAllFiles(String dirName, String regex) {
File[] allFiles = getAllFiles(dirName);
List<File> matchingFiles = new ArrayList<File>();
for (int i = 0; i < allFiles.length; i++) {
if (allFiles[i].getName().matches(regex)) {
matchingFiles.add(allFiles[i]);
}
}
return matchingFiles.toArray(new File[matchingFiles.size()]);
}
/**
* Copies src file to dst file. If the dst file does not exist, it is created.
*
* @param srcPath
* @param destPath
* @throws IOException
*/
public static boolean copy(String srcPath, String destPath) {
boolean success = true;
InputStream in = null;
OutputStream out = null;
try {
File srcFile = new File(srcPath);
if (!srcFile.exists()) {
logger.error("SOURCE FILE NOT FOUND!!!");
return false;
}
mkDirIfNotExists(destPath.substring(0, destPath.lastIndexOf(File.separatorChar)));
File destFile = new File(destPath);
in = new FileInputStream(srcFile);
out = new FileOutputStream(destFile); // Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (Exception e) {
logger.error("ERROR COPYING FILE!!!", e);
success = false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// eat it
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// eat it
}
}
}
return success;
}
/**
* @param fullyQualifiedFileName
* @return
*/
public static boolean deleteFile(String fullyQualifiedFileName) {
File file = new File(fullyQualifiedFileName);
boolean deleteSuccessful = false;
if (file.exists() && file.canWrite() && !file.isDirectory()) {
try {
deleteSuccessful = file.delete();
} catch (Exception e) {
logger.error("ERROR DELETING FILE!!!", e);
}
}
return deleteSuccessful;
}
/**
* Checks if a file exists
*
* @param pFilePath
* @return
*/
public static boolean fileExists(String pFilePath) {
File file = new File(pFilePath);
return file.exists();
}
/**
* Makes a dir, if it doesn't already exist
*
* @param pFilePath
*/
public static void mkDirIfNotExists(String pFilePath) {
File f = new File(pFilePath);
if (!f.exists()) {
f.mkdir();
}
}
} | 10,269 | 25.401028 | 134 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/utils/CSVUtils.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.LinkedList;
import java.util.List;
/**
* @author timmolter
*/
public class CSVUtils {
/**
* @param listOfLists
* @param path2Dir
* @param fileName
*/
public static void writeCSVRows(List<List<? extends Object>> listOfLists, String path2Dir, String fileName) {
File newFile = new File(path2Dir + fileName + ".csv");
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), "UTF8"));
for (int i = 0; i < listOfLists.size(); i++) {
List<? extends Object> list = listOfLists.get(i);
String csv = StringUtils.join(list, ",") + System.getProperty("line.separator");
out.write(csv);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
// NOP
}
}
}
}
public static double[][] read(String path) {
List<double[]> lines = new LinkedList<double[]>();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
String line;
while ((line = br.readLine()) != null) {
if (!line.contains("#")) {
String[] a = line.split(",");
try {
double[] n = new double[a.length];
for (int i = 0; i < n.length; i++) {
n[i] = Double.parseDouble(a[i]);
}
lines.add(n);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
br.close();
double[][] output = new double[lines.size()][lines.get(0).length];
for (int i = 0; i < output.length; i++) {
output[i] = lines.get(i);
}
return output;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
| 3,632 | 30.051282 | 111 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/utils/StringUtils.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class performs various tasks on Strings
*
* @author alexnugent
*/
public final class StringUtils {
private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
private static DecimalFormat priceFormatter = new DecimalFormat("$###,###,##0.00");
private static DecimalFormat percentFormat = new DecimalFormat("#.##%");
private static SimpleDateFormat dateFormat_yyyyMMdd = new SimpleDateFormat("yyyy.MM.dd");
private static SimpleDateFormat dateFormat_MySQL = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* Constructor - Private constructor to prevent instantiation
*/
private StringUtils() {
}
public static String formatPrice(double number) {
return priceFormatter.format(number);
}
/**
* Joins a collection of Objects separated by a specified separator
*
* @param collection
* @param separator
* @return the joined String
*/
public static String join(Collection<? extends Object> collection, String separator) {
if (collection == null) {
return null;
}
Iterator iterator = collection.iterator();
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return "";
}
Object first = iterator.next();
if (!iterator.hasNext()) {
return first == null ? "" : first.toString();
}
// two or more elements
StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
/**
* Adds whitespace to the end of given String
*
* @param theString
* @param finalLength
* @return
*/
public static String addWhiteSpaceToEnd(String theString, int finalLength) {
int difference = finalLength - theString.length();
StringBuffer buf = new StringBuffer();
buf.append(theString);
for (int i = 0; i < difference; i++) {
buf.append(" ");
}
return buf.toString();
}
/**
* Will convert a decimal to a percentage. For example: .755 --> "75.5%"
*
* @param number the number in decimal form.
* @return
*/
public static String formatPercentage(double number) {
return percentFormat.format(number);
}
/**
* @param date
* @return
*/
public static String formatDate_yyyyMMdd(Date date) {
return dateFormat_yyyyMMdd.format(date);
}
/**
* @param date
* @return
*/
public static String formatDate_MySQL(Date date) {
return dateFormat_MySQL.format(date);
}
/**
* @param dateString
* @return
*/
public static Date parseDateString_MySQL(String dateString) {
Date date = null;
try {
date = dateFormat_MySQL.parse(dateString);
} catch (ParseException e) {
logger.error("COULD NOT PARSE DATE STRING!!!");
}
return date;
}
/**
* Get the MD5 hash of a String
*
* @param input the String to hash
* @return the hash of the given String
*/
public static String getMD5(String input) {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(input.getBytes());
byte[] digest = messageDigest.digest();
BigInteger bigInt = new BigInteger(1, digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (NoSuchAlgorithmException e) {
logger.error("ERROR CREATING MD5!!!", e);
return null;
}
}
}
| 5,781 | 27.204878 | 97 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/utils/ImageUtils.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.utils;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author timmolter
*/
public final class ImageUtils {
private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class);
/**
* Constructor - Private constructor to prevent instantiation
*/
private ImageUtils() {
}
public static boolean saveJPGWithQuality(BufferedImage pBufferedImage, String pPath, String pName, float quality) {
if (pBufferedImage.getColorModel().getTransparency() != Transparency.OPAQUE) {
pBufferedImage = fillTransparentPixels(pBufferedImage, Color.WHITE);
}
boolean saveSuccessful = true;
try {
new File(pPath).mkdirs(); // make the dirs if they don't exist
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality); // a float between 0 and 1
// 1 specifies minimum compression and maximum quality
File file = new File(pPath + pName + ".jpg");
logger.debug("Save Path: " + pPath + pName + ".jpg");
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(pBufferedImage, null, null);
writer.write(null, image, iwp);
writer.dispose();
} catch (Exception e) {
saveSuccessful = false;
logger.debug("ERROR SAVING JPEG IMAGE!!!", e);
}
return saveSuccessful;
}
public static byte[] getJpegImageByteArray(BufferedImage bufferedImage, float quality) {
if (bufferedImage.getColorModel().getTransparency() != Transparency.OPAQUE) {
bufferedImage = fillTransparentPixels(bufferedImage, Color.WHITE);
}
byte[] imageInBytes = null;
try {
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = iter.next();
// instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality); // a float between 0 and 1
ByteArrayOutputStream baos = new ByteArrayOutputStream(37628);
ImageOutputStream output = ImageIO.createImageOutputStream(baos);
writer.setOutput(output);
IIOImage image = new IIOImage(bufferedImage, null, null);
writer.write(null, image, iwp);
imageInBytes = baos.toByteArray();
writer.dispose();
} catch (Exception e) {
logger.debug("ERROR SAVING JPEG IMAGE!!!", e);
}
return imageInBytes;
}
public static boolean saveByteArrayToJpeg(byte[] imageInBytes, String path, String name) {
boolean saveSuccessful = false;
try {
// convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(imageInBytes);
BufferedImage bufferedImage = ImageIO.read(in);
saveSuccessful = ImageIO.write(bufferedImage, "jpeg", new File(path + name));
} catch (IOException e) {
logger.error("ERROR SAVING IMAGE!!!", e);
}
return saveSuccessful;
}
public static BufferedImage fillTransparentPixels(BufferedImage image, Color fillColor) {
int w = image.getWidth();
int h = image.getHeight();
BufferedImage image2 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image2.createGraphics();
g.setColor(fillColor);
g.fillRect(0, 0, w, h);
g.drawRenderedImage(image, null);
g.dispose();
return image2;
}
public static boolean savePNG(BufferedImage pBufferedImage, String pPath, String pName) {
return ImageUtils.saveImage(pBufferedImage, pPath, pName, "png");
}
public static boolean saveJPG(BufferedImage pBufferedImage, String pPath, String pName) {
return ImageUtils.saveImage(pBufferedImage, pPath, pName, "jpg");
}
public static boolean saveImage(BufferedImage pBufferedImage, String pPath, String pName, String pFileExtension) {
new File(pPath).mkdirs(); // make the dirs if they don't exist
File file = new File(pPath + pName + "." + pFileExtension);
boolean saveSuccessful = false;
try {
saveSuccessful = ImageIO.write(pBufferedImage, pFileExtension, file);
} catch (IOException e) {
logger.error("ERROR SAVING IMAGE!!!", e);
}
return saveSuccessful;
}
public static int[] getPixelARGB(int pixel) {
int[] argb = new int[4];
argb[0] = (pixel >> 24) & 0xff; // alpha
argb[1] = (pixel >> 16) & 0xff; // red
argb[2] = (pixel >> 8) & 0xff; // green
argb[3] = (pixel) & 0xff; // blue
// System.out.println("argb: " + argb[0] + ", " + argb[1] + ", " + argb[2] + ", " + argb[3]);
return argb;
}
public static int getPixelInt(int a, int r, int g, int b) {
return (a << 24) | (r << 16) | (g << 8) | b;
}
/**
* Generates a BufferedImage from a given URL
*
* @param imageUrl
* @return BufferedImage - returns null and logs and error if there was a problem
*/
public static BufferedImage getBufferedImageFromURL(String imageUrl) {
URL url;
try {
url = new URL(imageUrl);
} catch (MalformedURLException e) {
logger.error("ERROR GETTING BUFFERED IMAGE FROM URL!!! [" + imageUrl + "] " + e.getClass().getSimpleName());
return null;
}
URLConnection urlConn = null;
try {
urlConn = url.openConnection();
} catch (IOException e) {
logger.error("ERROR GETTING BUFFERED IMAGE FROM URL!!! [" + imageUrl + "] " + e.getClass().getSimpleName());
}
urlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.21; Mac_PowerPC)");
try {
urlConn.connect();
} catch (IOException e) {
logger.error("ERROR GETTING BUFFERED IMAGE FROM URL!!! [" + imageUrl + "] " + e.getClass().getSimpleName());
}
InputStream urlStream = null;
try {
urlStream = urlConn.getInputStream();
} catch (IOException e) {
logger.error("ERROR GETTING BUFFERED IMAGE FROM URL!!! [" + imageUrl + "] " + e.getClass().getSimpleName());
}
try {
// BufferedImage image = ImageIO.read(url);
// BufferedImage image = ImageIO.read(url.openStream());
BufferedImage image = ImageIO.read(urlStream);
return image;
} catch (Exception e) {
logger.error("ERROR GETTING BUFFERED IMAGE FROM URL!!! [" + imageUrl + "] " + e.getClass().getSimpleName());
return null;
}
}
public static Dimension getImageSizeWithoutFullDownload(URL url, int timeout) {
URLConnection urlConn = null;
try {
urlConn = url.openConnection();
} catch (IOException e) {
logger.error("IOEXCEPTION!!! " + e.getClass().getSimpleName());
}
urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.99 Safari/537.22");
urlConn.setReadTimeout(timeout);
try {
urlConn.connect();
} catch (IOException e) {
logger.error("IOEXCEPTION!!! " + e.getClass().getSimpleName());
}
InputStream urlStream = null;
try {
urlStream = urlConn.getInputStream();
} catch (IOException e) {
logger.error("IOEXCEPTION!!! " + e.getClass().getSimpleName());
}
try {
ImageInputStream in = ImageIO.createImageInputStream(urlStream);
try {
final Iterator readers = ImageIO.getImageReaders(in);
if (readers.hasNext()) {
ImageReader reader = (ImageReader) readers.next();
try {
reader.setInput(in);
return new Dimension(reader.getWidth(0), reader.getHeight(0));
} finally {
reader.dispose();
}
}
} finally {
if (in != null)
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Creates a Thumbnail of an image, maintaining the aspect ratio, and scaling the largest dimension to pSize
*
* @param pBufferedImage
* @param pSize
* @return
*/
public static BufferedImage createThumbnail(BufferedImage pBufferedImage, int pSize) {
if (pBufferedImage == null) {
logger.error("GIVEN IMAGE WAS NULL!!! ");
return null;
}
double w = pBufferedImage.getWidth(null);
double h = pBufferedImage.getHeight(null);
double scale;
if (w > h) {// width bigger then height. scale width.
scale = pSize / w;
}
else {
scale = pSize / h;
}
int newHeight = (int) (pBufferedImage.getHeight(null) * scale);
int newWidth = (int) (pBufferedImage.getWidth(null) * scale);
// return (BufferedImage) pBufferedImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
Image lThumbnailImage = pBufferedImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
return ImageUtils.imageToBufferedImage(lThumbnailImage);
}
/**
* @param pImage
* @return
*/
private static BufferedImage imageToBufferedImage(Image pImage) {
int w = pImage.getWidth(null);
int h = pImage.getHeight(null);
int type = BufferedImage.TYPE_INT_ARGB; // other options
BufferedImage lBufferedImage = new BufferedImage(w, h, type);
Graphics2D g2 = lBufferedImage.createGraphics();
g2.drawImage(pImage, 0, 0, null);
g2.dispose();
return lBufferedImage;
}
/**
* Creates a BufferredImage give a File
*
* @param pFile
* @return
*/
public static BufferedImage getBufferedImageFromFile(File pFile) {
BufferedImage lBufferedImage = null;
try {
lBufferedImage = ImageIO.read(pFile);
} catch (IOException e) {
logger.error("ERROR GETTING BUFFERED IMAGE!!!", e);
}
return lBufferedImage;
}
/**
* Generates a MD5 Hash for a given Bufferred Image
*
* @param pBufferedImage
* @return String - a 32 char String representing the MD5 hash of the image.
*/
public static String getMD5Hash(BufferedImage pBufferedImage) {
String hexString = "";
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(pBufferedImage, "png", outputStream); // works for any type of image
byte[] data = outputStream.toByteArray();
MessageDigest md = null;
md = MessageDigest.getInstance("MD5");
md.update(data);
byte[] bytes = md.digest();
for (int i = 0; i < bytes.length; i++) {
hexString += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
}
} catch (Exception e) {
logger.error("ERROR CREATING MD5 HASH!!!", e);
}
return hexString;
}
}
| 13,113 | 31.380247 | 168 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/utils/DateUtils.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* @author timmolter
*/
public final class DateUtils {
/**
* Constructor - Private constructor to prevent instantiation
*/
private DateUtils() {
}
/**
* Given a Date String and a format String, returns a Date Object
*
* @param dateString
* @param formatString
* @return
* @throws ParseException
*/
public static Date getDateFromString(String dateString, String formatString) throws ParseException {
DateFormat sdf = new SimpleDateFormat(formatString);
return sdf.parse(dateString);
}
/**
* Add years to a date. Use - sign to subtract years
*
* @param date
* @param years
* @return
*/
public static Date addYears(Date date, int years) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
lCalendar.add(Calendar.YEAR, years);
return lCalendar.getTime();
}
/**
* Add months to a date. Use - sign to subtract months
*
* @param date
* @param months
* @return
*/
public static Date addMonths(Date date, int months) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
lCalendar.add(Calendar.MONTH, months);
return lCalendar.getTime();
}
/**
* Add days to a date. Use - sign to subtract days
*
* @param date
* @param days
* @return
*/
public static Date addDays(Date date, int days) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
lCalendar.add(Calendar.DAY_OF_YEAR, days);
return lCalendar.getTime();
}
/**
* Add hours to a date. Use - sign to subtract hours
*
* @param date
* @param hours
* @return
*/
public static Date addHours(Date date, int hours) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
lCalendar.add(Calendar.HOUR_OF_DAY, hours);
return lCalendar.getTime();
}
/**
* Add minutes to a date. Use - sign to subtract minutes
*
* @param date
* @param minutes
* @return
*/
public static Date addMinutes(Date date, int minutes) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
lCalendar.add(Calendar.MINUTE, minutes);
return lCalendar.getTime();
}
/**
* Add seconds to a date. Use - sign to subtract seconds
*
* @param date
* @param seconds
* @return
*/
public static Date addSeconds(Date date, int seconds) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
lCalendar.add(Calendar.SECOND, seconds);
return lCalendar.getTime();
}
/**
* Checks if the first date is near to the second date within the number of days specified
*
* @param date1
* @param date2
* @param days
* @return
*/
public static boolean isNear(Date date1, Date date2, int days) {
if (date1 == null || date2 == null) {
return false;
}
Date vLowerDate = addDays(date2, -days);
Date vUpperDate = addDays(date2, days);
return date1.after(vLowerDate) && date1.before(vUpperDate);
}
/**
* Removes the timestamp portion of a date
*
* @param date
* @return
*/
public static Date removeTimestamp(Date date) {
try {
DateFormat dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);
String dateString = dateFormat.format(date);
return dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String getDateSQLString(Date date) {
SimpleDateFormat SQL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
return SQL_DATE_FORMAT.format(date);
}
public static String getDateTimeSQLString(Date date) {
SimpleDateFormat SQL_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return SQL_DATE_FORMAT.format(date);
}
/**
* Check if the given date is today
*
* @param date
* @return
*/
public static boolean isToday(Date date) {
Date today = removeTimestamp(new Date());
return today.equals(removeTimestamp(date));
}
/**
* Check if two Date objects are the same date
*
* @param date1
* @param date2
* @return
*/
public static boolean isSameDate(Date date1, Date date2) {
date1 = removeTimestamp(date1);
date2 = removeTimestamp(date2);
return date1.equals(date2);
}
/**
* Check if given date is the first of the month
*
* @param date
* @return
*/
public static boolean isFirstDayOfMonth(Date date) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
if (lCalendar.get(Calendar.DAY_OF_MONTH) == 1) {
return true;
}
else {
return false;
}
}
public static Date getLastDayOfPreviousMonth(Date date) {
Calendar lCalendar = Calendar.getInstance();
lCalendar.setTime(date);
lCalendar.set(Calendar.DAY_OF_MONTH, 1);
Date lTmpDate = lCalendar.getTime();
return addDays(lTmpDate, -1);
}
public static Date getLastDayOfMonth(Date date) {
date = addMonths(date, 1);
return getLastDayOfPreviousMonth(date);
}
/**
* Creates a current Date without timestamp
*
* @return
*/
public static Date createTruncatedDate() {
return removeTimestamp(new Date());
}
public static long getDifferenceInDays(Date from, Date to) {
double lDifference = to.getTime() - from.getTime();
return Math.round(lDifference / (1000 * 60 * 60 * 24));
}
public static Date getNextBusinessDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.FRIDAY) {
calendar.add(Calendar.DATE, 3);
}
else if (dayOfWeek == Calendar.SATURDAY) {
calendar.add(Calendar.DATE, 2);
}
else {
calendar.add(Calendar.DATE, 1);
}
Date nextBusinessDay = calendar.getTime();
return nextBusinessDay;
}
public static boolean isSameDateTime(Date date1, Date date2) {
int results = date1.compareTo(date2);
if (results > 0) {
return false;
}
else if (results < 0) {
return false;
}
else {
return true;
}
}
public static int getTimezoneDifference(String timezone1, String timezone2) {
// Timezone1
Calendar lCalendar = new GregorianCalendar(TimeZone.getTimeZone(timezone1));
lCalendar.setTimeInMillis(new Date().getTime());
int Timezone1HourOfDay = lCalendar.get(Calendar.HOUR_OF_DAY);
int Timezone1DayOfMonth = lCalendar.get(Calendar.DAY_OF_MONTH);
// Timezone2
lCalendar = new GregorianCalendar(TimeZone.getTimeZone(timezone2));
lCalendar.setTimeInMillis(new Date().getTime());
int TimezoneHourOfDay = lCalendar.get(Calendar.HOUR_OF_DAY);
int TimezoneDayOfMonth = lCalendar.get(Calendar.DAY_OF_MONTH);
int hourDifference = Timezone1HourOfDay - TimezoneHourOfDay;
int dayDifference = Timezone1DayOfMonth - TimezoneDayOfMonth;
if (dayDifference != 0) {
hourDifference = hourDifference + 24;
}
return hourDifference;
}
}
| 8,825 | 24.731778 | 102 | java |
AHaH | AHaH-master/ahah-commons/src/main/java/com/mancrd/ahah/commons/utils/RunningStat.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.commons.utils;
/**
* RunningStat keeps track of running average and standard deviation values for incoming values
*
* @author timmolter
*/
public class RunningStat {
private int count = 0;
private double average = 0.0;
private double pwrSumAvg = 0.0;
private double stdDev = 0.0;
/**
* Incoming new values used to calculate the running statistics
*
* @param value
*/
public void put(double value) {
count++;
average += (value - average) / count;
pwrSumAvg += (value * value - pwrSumAvg) / count;
stdDev = Math.sqrt((pwrSumAvg * count - count * average * average) / (count - 1));
}
public double getAverage() {
return average;
}
public double getStandardDeviation() {
return Double.isNaN(stdDev) ? 0.0 : stdDev;
}
}
| 2,286 | 32.632353 | 95 | java |
AHaH | AHaH-master/ahah-motorcontroller/src/main/java/com/mancrd/ahah/motorcontroller/LearningBuffer.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.motorcontroller;
/**
* @author alexnugent
*/
class LearningBuffer {
private final BufferElement[] buffer;
private int idx = 0;
/**
* Constructor
*
* @param bufferSize
*/
LearningBuffer(int bufferSize) {
this.buffer = new BufferElement[bufferSize];
}
/**
* @param feature
* @param y
* @param value
* @return
*/
BufferElement put(String[] feature, double[] y, double value) {
int i = idx % buffer.length;
BufferElement outgoing = buffer[i];
buffer[i] = new BufferElement(feature, y, value);
idx++;
return outgoing;
}
BufferElement[] getBuffer() {
return buffer;
}
}
| 2,148 | 29.7 | 94 | java |
AHaH | AHaH-master/ahah-motorcontroller/src/main/java/com/mancrd/ahah/motorcontroller/BufferElement.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.motorcontroller;
/**
* @author alexnugent
*/
final class BufferElement {
private final String[] feature;
private final double[] y;
private final double value;
/**
* Constructor
*
* @param feature
* @param y
* @param value
*/
BufferElement(String[] feature, double[] y, double value) {
this.feature = feature;
this.value = value;
this.y = y;
}
String[] getFeature() {
return feature;
}
double getValue() {
return value;
}
double[] getY() {
return y;
}
}
| 2,030 | 28.014286 | 94 | java |
AHaH | AHaH-master/ahah-motorcontroller/src/main/java/com/mancrd/ahah/motorcontroller/Feature.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.motorcontroller;
/**
* A DTO that encapsulates a feature and its weight
*
* @author alexnugent
*/
final class Feature implements Comparable<Feature> {
private final String featureUUID;
private final double weight;
/**
* Constructor
*
* @param featureUUID
* @param weight
*/
Feature(String featureUUID, double weight) {
this.featureUUID = featureUUID;
this.weight = weight;
}
String getFeatureUUID() {
return featureUUID;
}
double getWeight() {
return weight;
}
@Override
public int compareTo(Feature other) {
if (other.getWeight() > getWeight()) {
return 1;
}
else if (other.getWeight() < getWeight()) {
return -1;
}
return 0;
}
@Override
public String toString() {
return featureUUID + "(" + weight + ")";
}
}
| 2,324 | 27.353659 | 94 | java |
AHaH | AHaH-master/ahah-motorcontroller/src/main/java/com/mancrd/ahah/motorcontroller/Actuator.java | /**
* Copyright (c) 2013 M. Alexander Nugent Consulting <[email protected]>
*
* M. Alexander Nugent Consulting Research License Agreement
* Non-Commercial Academic Use Only
*
* This Software is proprietary. By installing, copying, or otherwise using this
* Software, you agree to be bound by the terms of this license. If you do not agree,
* do not install, copy, or use the Software. The Software is protected by copyright
* and other intellectual property laws.
*
* You may use the Software for non-commercial academic purpose, subject to the following
* restrictions. You may copy and use the Software for peer-review and methods verification
* only. You may not create derivative works of the Software. You may not use or distribute
* the Software or any derivative works in any form for commercial or non-commercial purposes.
*
* Violators will be prosecuted to the full extent of the law.
*
* All rights reserved. No warranty, explicit or implicit, provided.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRßANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.mancrd.ahah.motorcontroller;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* This class encapsulates all of the learning
*
* @author alexnugent
*/
public class Actuator {
private final static double CONFIDENCE = 0;
private final static double L = .1;
private final static double ALPHA = L;
private final static double BETA = 5 * L;
private final static double NOISE_RATE_NODE = .01;
private final static double STARTING_WEIGHT_MAG = 1E-9;
private final int numJoints;
private final int numFibers;
private final int numNodes;
private final Map<String, double[]> globalMap; // input line --> (weights)
private final LearningBuffer buffer;
private final Random random = new Random();
/**
* Constructor
*
* @param labels
* @param delay
*/
public Actuator(int numJoints, int numFibers, int delay) {
this.numJoints = numJoints;
this.numFibers = numFibers;
this.numNodes = numJoints * 2 * numFibers;
globalMap = new HashMap<String, double[]>();
buffer = new LearningBuffer(delay);
}
/**
* @param spikes - a Collection of Objects. The internal map keys off of the Objects' toString() values, so make sure your Objects implement
* unique toString() implementations
* @param value
* @return - labels as ints
*/
public int[] update(Set<String> spikes, double value) {
// build feature Activation
double[] yArray = new double[numNodes];
String[] featureSetArray = new String[spikes.size()]; // this is used for buffering
int idx = 0;
for (String spike : spikes) { // loop through all of the features in the feature set
featureSetArray[idx] = spike;
double[] weights = getWeightVector(spike);
weights[weights.length - 1] = 0;
for (int i = 0; i < yArray.length; i++) {
yArray[i] += weights[i];
weights[weights.length - 1] += Math.abs(weights[i]); // this is used to store the total "link share" for each feature for rapid feedback
// later.
}
idx++;
}
// add noise
for (int i = 0; i < yArray.length; i++) {
yArray[i] += NOISE_RATE_NODE * random.nextGaussian();
}
// Learn delayed
learnDelayed(featureSetArray, yArray, value);
return getActuations(yArray);
}
private int[] getActuations(double[] yArray) {
int[] actuations = new int[numJoints];
if (yArray == null) {
return actuations;
}
int idx = 0;
for (int m = 0; m < numJoints; m++) {
for (int mi = 0; mi < 2; mi++) {
for (int f = 0; f < numFibers; f++) {
if (yArray[idx] > 0) {
if (mi == 0) {
actuations[m]++;
}
else {
actuations[m]--;
}
}
idx++;
}
}
}
return actuations;
}
/**
* @param feature
* @param y
* @param value
*/
private void learnDelayed(String[] feature, double[] yArray, double value) {
BufferElement bufferElement = this.buffer.put(feature, yArray, value); // learning takes place on buffered data, not live data!
if (bufferElement != null) {
double dV = value - bufferElement.getValue();
double[] y = bufferElement.getY();
double h = Math.signum(dV);
double L = 1.0 / feature.length;
double[] desired = getDesired(y, h);
for (int i = 0; i < bufferElement.getFeature().length; i++) {
double[] weights = getWeightVector(bufferElement.getFeature()[i]);
for (int j = 0; j < y.length; j++) {
weights[j] += -L * BETA * y[j];// anti-hebbian learning from access
if (desired[j] * y[j] > 0) {
weights[j] += Math.signum(y[j]) * L * ALPHA;// shot of reinformence
}
}
}
}
}
private double[] getDesired(double[] y, double h) {
double[] desired = new double[y.length];
int[] actuations = getActuations(y);
int idx = 0;
for (int m = 0; m < numJoints; m++) {
for (int mi = 0; mi < 2; mi++) {
for (int f = 0; f < numFibers; f++) {
if (h > 0) {// better than expected. reward this
if (mi == 0) {// positive collective
desired[idx] = Math.signum(actuations[m]);
}
else {// negative going collective
desired[idx] = -Math.signum(actuations[m]);
}
}
else {// worse or equal to expected. should have done opposite
if (mi == 0) {// positive collective
desired[idx] = -Math.signum(actuations[m]);
}
else {// negative going collective
desired[idx] = Math.signum(actuations[m]);
}
}
idx++;
}
}
}
return desired;
}
/**
* gets the weight and creates a new random weight if it does not exist.
*
* @param spike
* @return
*/
private double[] getWeightVector(String spike) {
double[] weights = globalMap.get(spike);
if (weights == null) {
weights = new double[numNodes];// the extra dimension is used to store the weight magnitude sum...
for (int i = 0; i < weights.length; i++) {
weights[i] = STARTING_WEIGHT_MAG * (2 * Math.random() - 1);
}
globalMap.put(spike, weights);
}
return weights;
}
double getConfidence() {
return CONFIDENCE;
}
public int getNumUniqueLabels() {
return globalMap.size();
}
}
| 7,025 | 29.025641 | 144 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/androidTest/java/com/example/edgedashanalytics/ExampleInstrumentedTest.java | package com.example.edgedashanalytics;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.edgedashanalytics", appContext.getPackageName());
}
}
| 773 | 27.666667 | 93 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/test/java/com/example/edgedashanalytics/ExampleUnitTest.java | package com.example.edgedashanalytics;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
| 391 | 20.777778 | 81 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/setting/SettingsActivity.java | package com.example.edgedashanalytics.page.setting;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.EditTextPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.util.dashcam.DashCam;
import com.example.edgedashanalytics.util.file.FileManager;
import com.example.edgedashanalytics.util.hardware.PowerMonitor;
import com.example.edgedashanalytics.util.nearby.Algorithm;
import com.example.edgedashanalytics.util.nearby.Algorithm.AlgorithmKey;
import com.example.edgedashanalytics.util.video.analysis.InnerAnalysis;
import com.example.edgedashanalytics.util.video.analysis.OuterAnalysis;
import java.util.Locale;
import java.util.StringJoiner;
public class SettingsActivity extends AppCompatActivity {
private static final String TAG = SettingsActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
private static String getWifiName(Context context) {
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (manager.isWifiEnabled()) {
WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo != null) {
// SSIDs are surrounded with quotation marks, should remove them
return wifiInfo.getSSID().replace("\"", "");
}
}
return "offline";
}
public static void printPreferences(boolean isMaster, boolean autoDownEnabled, Context c) {
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(c);
final boolean defaultBool = false;
final int defaultInt = 1;
final String defaultString = "1";
String objectModel = pref.getString(c.getString(R.string.object_model_key),
c.getString(R.string.default_object_model_key));
String poseModel = pref.getString(c.getString(R.string.pose_model_key),
c.getString(R.string.default_pose_model_key));
String algorithmKey = c.getString(R.string.scheduling_algorithm_key);
AlgorithmKey algorithm = AlgorithmKey.valueOf(pref.getString(algorithmKey, Algorithm.DEFAULT_ALGORITHM.name()));
boolean local = pref.getBoolean(c.getString(R.string.local_process_key), defaultBool);
boolean segmentationEnabled = pref.getBoolean(c.getString(R.string.enable_segment_key), defaultBool);
int segNum = pref.getInt(c.getString(R.string.segment_number_key), defaultInt);
int delay = Integer.parseInt(pref.getString(c.getString(R.string.download_delay_key), defaultString));
boolean dualDownload = pref.getBoolean(c.getString(R.string.dual_download_key), defaultBool);
boolean isCharging = ((BatteryManager) c.getSystemService(Context.BATTERY_SERVICE)).isCharging();
boolean sim = pref.getBoolean(c.getString(R.string.enable_download_simulation_key), defaultBool);
int simDelay = Integer.parseInt(pref.getString(c.getString(R.string.simulation_delay_key), defaultString));
int testVideoCount = DashCam.getTestVideoCount();
double stopDivisor = Double.parseDouble(pref.getString(c.getString(R.string.early_stop_divisor_key), "0"));
int batteryLevel = PowerMonitor.getBatteryLevel(c);
StringJoiner prefMessage = new StringJoiner("\n ");
prefMessage.add("Preferences:");
prefMessage.add(String.format("Master: %s", isMaster));
prefMessage.add(String.format("Object detection model: %s", objectModel));
prefMessage.add(String.format("Pose estimation model: %s", poseModel));
prefMessage.add(String.format("Algorithm: %s", algorithm.name()));
prefMessage.add(String.format("Local processing: %s", local));
prefMessage.add(String.format("Auto download: %s", autoDownEnabled));
prefMessage.add(String.format("Segmentation: %s", segmentationEnabled));
prefMessage.add(String.format("Segment number: %s", segNum));
prefMessage.add(String.format("Download delay: %s", delay));
prefMessage.add(String.format("Dual download: %s", dualDownload));
prefMessage.add(String.format("Wi-Fi: %s", getWifiName(c)));
prefMessage.add(String.format("Concurrent downloads: %s", DashCam.concurrentDownloads));
prefMessage.add(String.format("Charging: %s", isCharging));
prefMessage.add(String.format("Simulated downloads: %s", sim));
prefMessage.add(String.format("Simulated delay: %s", simDelay));
prefMessage.add(String.format("Test video count: %s", testVideoCount));
prefMessage.add(String.format(Locale.ENGLISH, "Early stop divisor: %.4f", stopDivisor));
prefMessage.add(String.format("Starting battery level: %s%%", batteryLevel));
Log.i(I_TAG, prefMessage.toString());
OuterAnalysis outerAnalysis = new OuterAnalysis(c);
InnerAnalysis innerAnalysis = new InnerAnalysis(c);
outerAnalysis.printParameters();
innerAnalysis.printParameters();
}
public static class SettingsFragment extends PreferenceFragmentCompat {
private AlertDialog clearDialog = null;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
Preference clearLogsButton = findPreference(getString(R.string.clear_logs_key));
if (clearLogsButton != null) {
clearLogsButton.setOnPreferenceClickListener(preference -> clearLogsPrompt());
}
Context context = getContext();
if (context == null) {
Log.w(TAG, "Null context");
return;
}
clearDialog = new AlertDialog.Builder(context)
.setTitle("Clear logs?")
.setPositiveButton(android.R.string.yes,
(DialogInterface dialog, int which) -> FileManager.clearLogs())
.setNegativeButton(android.R.string.no,
(DialogInterface dialog, int which) -> Log.v(TAG, "Canceled log clearing"))
.create();
// https://stackoverflow.com/a/34556215
clearDialog.setOnShowListener(dialog -> {
Button posButton = clearDialog.getButton(DialogInterface.BUTTON_POSITIVE);
Button negButton = clearDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 2f);
negButton.setLayoutParams(params);
posButton.setLayoutParams(params);
negButton.invalidate();
posButton.invalidate();
});
EditTextPreference downloadDelay = findPreference(getString(R.string.download_delay_key));
setupTextPreference(downloadDelay, InputType.TYPE_CLASS_NUMBER);
EditTextPreference simDelay = findPreference(getString(R.string.simulation_delay_key));
setupTextPreference(simDelay, InputType.TYPE_CLASS_NUMBER);
EditTextPreference testVideoCount = findPreference(getString(R.string.test_video_count_key));
setupTextPreference(testVideoCount, InputType.TYPE_CLASS_NUMBER);
EditTextPreference earlyStopDivisor = findPreference(getString(R.string.early_stop_divisor_key));
setupTextPreference(earlyStopDivisor,
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
}
private boolean clearLogsPrompt() {
if (clearDialog == null) {
Log.w(TAG, "Null dialog");
return false;
} else {
clearDialog.show();
return true;
}
}
private void setupTextPreference(EditTextPreference editTextPreference, int inputType) {
if (editTextPreference != null) {
setTextSummaryToValue(editTextPreference, editTextPreference.getText());
editTextPreference.setOnPreferenceChangeListener((preference, newValue) ->
setTextSummaryToValue((EditTextPreference) preference, (String) newValue));
editTextPreference.setOnBindEditTextListener(editText -> {
editText.setInputType(inputType);
editText.selectAll();
});
}
}
private boolean setTextSummaryToValue(EditTextPreference editTextPreference, String value) {
if (editTextPreference == null) {
Log.w(TAG, "Null EditTextPreference");
return false;
} else {
editTextPreference.setSummary(value);
return true;
}
}
}
}
| 10,114 | 47.166667 | 122 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/adapter/RawAdapter.java | package com.example.edgedashanalytics.page.adapter;
import android.util.Log;
import android.widget.Toast;
import com.example.edgedashanalytics.page.main.ActionButton;
import com.example.edgedashanalytics.page.main.VideoFragment;
import com.example.edgedashanalytics.util.video.analysis.AnalysisTools;
public class RawAdapter extends VideoRecyclerViewAdapter {
private static final String TAG = RawAdapter.class.getSimpleName();
private static final String BUTTON_TEXT = ActionButton.ADD.toString();
public RawAdapter(VideoFragment.Listener listener) {
super(listener);
}
@Override
public void onBindViewHolder(final VideoViewHolder holder, final int position) {
holder.video = videos.get(position);
holder.videoFileNameView.setText(videos.get(position).getName());
holder.actionButton.setText(BUTTON_TEXT);
holder.actionButton.setOnClickListener(v -> {
if (listener == null) {
Log.e(TAG, "Null listener");
return;
}
if (listener.getIsConnected()) {
listener.getAddVideo(holder.video);
listener.getNextTransfer();
} else {
Log.v(TAG, String.format("User selected %s", holder.video));
AnalysisTools.processVideo(holder.video, v.getContext());
Toast.makeText(v.getContext(), "Add to processing queue", Toast.LENGTH_SHORT).show();
}
});
if (tracker.isSelected(getItemId(position))) {
holder.layout.setBackgroundResource(android.R.color.darker_gray);
} else {
holder.layout.setBackgroundResource(android.R.color.transparent);
}
}
}
| 1,732 | 35.104167 | 101 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/adapter/ResultRecyclerViewAdapter.java | package com.example.edgedashanalytics.page.adapter;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.page.main.ResultsFragment;
import java.io.File;
import java.util.List;
@SuppressWarnings("FieldCanBeLocal")
public class ResultRecyclerViewAdapter extends RecyclerView.Adapter<ResultRecyclerViewAdapter.ResultViewHolder> {
private static final String TAG = ResultRecyclerViewAdapter.class.getSimpleName();
private final ResultsFragment.Listener listener;
private final String BUTTON_ACTION_TEXT;
private List<Result> results;
public ResultRecyclerViewAdapter(ResultsFragment.Listener listener, String buttonText) {
this.listener = listener;
this.BUTTON_ACTION_TEXT = buttonText;
setHasStableIds(true);
}
@NonNull
@Override
public ResultViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.result_list_item, parent, false);
return new ResultViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ResultViewHolder holder, int position) {
holder.result = results.get(position);
holder.resultFileNameView.setText(results.get(position).getName());
holder.actionButton.setText(BUTTON_ACTION_TEXT);
holder.actionButton.setOnClickListener(v -> {
File resultFile = new File(holder.result.getData());
Uri contentUri = FileProvider.getUriForFile(v.getContext(), "com.example.edgedashanalytics.fileprovider", resultFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(contentUri, "text/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
v.getContext().startActivity(intent);
// if (null != listener) {
// listener.onListFragmentInteraction(holder.result);
// }
});
}
@Override
public int getItemCount() {
return results.size();
}
@Override
public long getItemId(int position) {
return position;
}
public void setResults(List<Result> results) {
this.results = results;
notifyDataSetChanged();
}
public static class ResultViewHolder extends RecyclerView.ViewHolder {
private final View view;
private final TextView resultFileNameView;
private final Button actionButton;
private final LinearLayout layout;
private Result result;
private ResultViewHolder(@NonNull View itemView) {
super(itemView);
view = itemView;
resultFileNameView = itemView.findViewById(R.id.result_name);
actionButton = itemView.findViewById(R.id.result_action_button);
layout = itemView.findViewById(R.id.result_row);
}
@NonNull
@Override
public String toString() {
return super.toString() + " '" + resultFileNameView.getText() + "'";
}
}
}
| 3,496 | 33.284314 | 130 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/adapter/VideoRecyclerViewAdapter.java | package com.example.edgedashanalytics.page.adapter;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.Selection;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.widget.RecyclerView;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.page.main.VideoFragment;
import com.example.edgedashanalytics.util.TimeManager;
import com.example.edgedashanalytics.util.dashcam.DashCam;
import com.example.edgedashanalytics.util.video.analysis.AnalysisTools;
import org.apache.commons.lang3.time.DurationFormatUtils;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* {@link RecyclerView.Adapter} that can display a {@link Video} and makes a call to the
* specified {@link VideoFragment.Listener}.
*/
public abstract class VideoRecyclerViewAdapter extends RecyclerView.Adapter<VideoRecyclerViewAdapter.VideoViewHolder> {
private static final String TAG = VideoRecyclerViewAdapter.class.getSimpleName();
List<Video> videos;
SelectionTracker<Long> tracker;
final VideoFragment.Listener listener;
VideoRecyclerViewAdapter(VideoFragment.Listener listener) {
this.listener = listener;
setHasStableIds(true);
}
public void setTracker(SelectionTracker<Long> tracker) {
this.tracker = tracker;
}
public void processSelected(Selection<Long> positions, Context c) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(c);
boolean simDownload = pref.getBoolean(c.getString(R.string.enable_download_simulation_key), false);
String defaultDelay = "1000";
int downloadDelay = Integer.parseInt(pref.getString(c.getString(R.string.simulation_delay_key), defaultDelay));
if (simDownload) {
Log.d(I_TAG, String.format("Starting simulated download with delay: %s", downloadDelay));
Thread transferDelayThread = new Thread(processSelectedDelay(positions, downloadDelay, c));
transferDelayThread.start();
} else {
processSelectedNow(positions, c);
}
}
private void processSelectedNow(Selection<Long> positions, Context context) {
if (listener.getIsConnected()) {
for (Long pos : positions) {
Video video = videos.get(pos.intValue());
listener.getAddVideo(video);
}
listener.getNextTransfer();
} else {
for (Long pos : positions) {
Video video = videos.get(pos.intValue());
AnalysisTools.processVideo(video, context);
}
}
}
private Runnable processSelectedDelay(Selection<Long> positions, int delay, Context context) {
// Not safe to concurrently modify recycler view list, better to copy videos first
ArrayList<Video> selectedVideos = new ArrayList<>(positions.size());
positions.iterator().forEachRemaining(p -> selectedVideos.add(videos.get(p.intValue())));
return () -> {
for (Video video : selectedVideos) {
if (listener.getIsConnected()) {
listener.getAddVideo(video);
listener.getNextTransfer();
} else {
AnalysisTools.processVideo(video, context);
}
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
Log.e(I_TAG, String.format("Thread error: \n%s", e.getMessage()));
}
}
};
}
public Runnable simulateDownloads(int delay, Consumer<Video> downloadCallback, boolean dualDownload) {
LinkedList<Video> videoList = videos.stream()
.sorted((v1, v2) -> DashCam.testVideoComparator(v1.getName(), v2.getName()))
.limit(DashCam.getTestVideoCount())
.collect(Collectors.toCollection(LinkedList::new));
int downloadCount = dualDownload ? 2 : 1;
return () -> {
ArrayList<Video> toDownload = new ArrayList<>(2);
for (int i = 0; i < downloadCount; i++) {
if (videoList.isEmpty()) {
downloadCallback.accept(null);
return;
}
Video video = videoList.pop();
toDownload.add(video);
TimeManager.addStartTime(video.getName());
}
// Assumes concurrent downloading, video pairs share a single delay and will complete at the same time
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(() -> toDownload.forEach(v -> {
String time = DurationFormatUtils.formatDuration(delay, "ss.SSS");
Log.i(I_TAG, String.format("Successfully downloaded %s in %ss, 0nW consumed", v.getName(), time));
downloadCallback.accept(v);
}), delay, TimeUnit.MILLISECONDS);
executor.shutdown();
};
}
@NonNull
@Override
public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.video_list_item, parent, false);
return new VideoViewHolder(view);
}
@Override
public int getItemCount() {
return videos.size();
}
@Override
public long getItemId(int position) {
return position;
}
public void setVideos(List<Video> videos) {
this.videos = videos;
notifyDataSetChanged();
}
public static class VideoViewHolder extends RecyclerView.ViewHolder {
final TextView videoFileNameView;
final Button actionButton;
Video video;
final LinearLayout layout;
private VideoViewHolder(View view) {
super(view);
videoFileNameView = view.findViewById(R.id.video_name);
actionButton = view.findViewById(R.id.video_action_button);
layout = itemView.findViewById(R.id.video_row);
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails() {
return new ItemDetailsLookup.ItemDetails<>() {
@Override
public int getPosition() {
return getAbsoluteAdapterPosition();
}
@NonNull
@Override
public Long getSelectionKey() {
return getItemId();
}
};
}
@NonNull
@Override
public String toString() {
return super.toString() + " '" + videoFileNameView.getText() + "'";
}
}
}
| 7,498 | 35.940887 | 119 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/adapter/ProcessingAdapter.java | package com.example.edgedashanalytics.page.adapter;
import android.util.Log;
import android.widget.Toast;
import com.example.edgedashanalytics.event.video.AddEvent;
import com.example.edgedashanalytics.event.video.RemoveEvent;
import com.example.edgedashanalytics.event.video.Type;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.page.main.ActionButton;
import com.example.edgedashanalytics.page.main.VideoFragment;
import com.example.edgedashanalytics.util.video.analysis.AnalysisTools;
import org.greenrobot.eventbus.EventBus;
public class ProcessingAdapter extends VideoRecyclerViewAdapter {
private static final String BUTTON_TEXT = ActionButton.REMOVE.toString();
private static final String TAG = ProcessingAdapter.class.getSimpleName();
public ProcessingAdapter(VideoFragment.Listener listener) {
super(listener);
}
@Override
public void onBindViewHolder(final VideoViewHolder holder, final int position) {
holder.video = videos.get(position);
holder.videoFileNameView.setText(videos.get(position).getName());
holder.actionButton.setText(BUTTON_TEXT);
holder.actionButton.setOnClickListener(v -> {
if (null != listener) {
listener.getIsConnected();
}
final Video video = holder.video;
Log.v(TAG, String.format("Removed %s from processing queue", video));
AnalysisTools.cancelProcess(video.getData());
EventBus.getDefault().post(new RemoveEvent(video, Type.PROCESSING));
EventBus.getDefault().post(new AddEvent(video, Type.RAW));
Toast.makeText(v.getContext(), "Remove from processing queue", Toast.LENGTH_SHORT).show();
});
if (position == 0) {
holder.layout.setBackgroundResource(android.R.color.holo_green_light);
holder.actionButton.setEnabled(false);
} else {
holder.layout.setBackgroundResource(android.R.color.transparent);
}
}
}
| 2,040 | 38.25 | 102 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/main/MainActivity.java | package com.example.edgedashanalytics.page.main;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.BuildConfig;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.data.result.ResultRepository;
import com.example.edgedashanalytics.data.video.ExternalStorageVideosRepository;
import com.example.edgedashanalytics.data.video.ProcessingVideosRepository;
import com.example.edgedashanalytics.data.video.VideosRepository;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.page.adapter.ProcessingAdapter;
import com.example.edgedashanalytics.page.adapter.RawAdapter;
import com.example.edgedashanalytics.page.setting.SettingsActivity;
import com.example.edgedashanalytics.util.dashcam.DashCam;
import com.example.edgedashanalytics.util.file.FileManager;
import com.example.edgedashanalytics.util.hardware.PowerMonitor;
import com.example.edgedashanalytics.util.nearby.Endpoint;
import com.example.edgedashanalytics.util.nearby.NearbyFragment;
import com.example.edgedashanalytics.util.video.eventhandler.ProcessingVideosEventHandler;
import com.example.edgedashanalytics.util.video.eventhandler.RawVideosEventHandler;
import com.example.edgedashanalytics.util.video.eventhandler.ResultEventHandler;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.function.Consumer;
public class MainActivity extends AppCompatActivity implements
VideoFragment.Listener, ResultsFragment.Listener, NearbyFragment.Listener {
private static final String TAG = MainActivity.class.getSimpleName();
public static final String I_TAG = "Important";
private VideoFragment rawFragment;
private VideoFragment processingFragment;
private ResultsFragment resultsFragment;
private ConnectionFragment connectionFragment;
private final FragmentManager supportFragmentManager = getSupportFragmentManager();
private Fragment activeFragment;
private final BottomNavigationView.OnItemSelectedListener bottomNavigationOnItemSelectedListener
= new BottomNavigationView.OnItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.navigation_raw) {
Log.v(TAG, "Navigation raw button clicked");
showNewFragmentAndHideOldFragment(rawFragment);
return true;
} else if (itemId == R.id.navigation_processing) {
Log.v(TAG, "Navigation processing button clicked");
showNewFragmentAndHideOldFragment(processingFragment);
return true;
} else if (itemId == R.id.navigation_completed) {
Log.v(TAG, "Navigation completed button clicked");
showNewFragmentAndHideOldFragment(resultsFragment);
Toast.makeText(MainActivity.this, String.format("Result count: %s", resultsFragment.getItemCount()),
Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
};
private void showNewFragmentAndHideOldFragment(Fragment newFragment) {
supportFragmentManager.beginTransaction().hide(activeFragment).show(newFragment).commit();
activeFragment = newFragment;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermissions();
scanVideoDirectories();
setToolBarAsTheAppBar();
setUpBottomNavigation();
setUpFragments();
FileManager.initialiseDirectories();
storeLogsInFile();
DashCam.setup(this);
}
@Override
protected void onStop() {
super.onStop();
try {
Runtime.getRuntime().exec("logcat -c");
} catch (IOException e) {
Log.e(I_TAG, String.format("Unable to clear logcat:\n%s", e.getMessage()));
}
}
private void storeLogsInFile() {
int id = android.os.Process.myPid();
@SuppressWarnings("SpellCheckingInspection")
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
String logPath = String.format("%s/%s.log", FileManager.getLogDirPath(), timestamp);
try {
// Clear logcat buffer
Runtime.getRuntime().exec("logcat -c");
// Write logcat messages to logPath
String loggingCommand = String.format("logcat --pid %s -f %s", id, logPath);
Log.v(TAG, String.format("Running logging command: %s", loggingCommand));
Runtime.getRuntime().exec(loggingCommand);
} catch (IOException e) {
Log.e(I_TAG, String.format("Unable to store log in file:\n%s", e.getMessage()));
}
}
private void checkPermissions() {
String[] PERMISSIONS = {
Manifest.permission.INTERNET,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.NFC
};
if (lacksPermissions(PERMISSIONS)) {
requestPermissions(PERMISSIONS, 1);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
String[] ANDROID_12_PERMISSIONS = {
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.MANAGE_EXTERNAL_STORAGE
};
if (lacksPermissions(ANDROID_12_PERMISSIONS)) {
requestPermissions(ANDROID_12_PERMISSIONS, 2);
}
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
String[] ANDROID_13_PERMISSIONS = {
Manifest.permission.NEARBY_WIFI_DEVICES
};
if (lacksPermissions(ANDROID_13_PERMISSIONS)) {
requestPermissions(ANDROID_13_PERMISSIONS, 3);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
Uri uri = Uri.parse("package:" + BuildConfig.APPLICATION_ID);
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri);
startActivity(intent);
}
}
private boolean lacksPermissions(String... permissions) {
if (permissions != null) {
for (String permission : permissions) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
return true;
}
}
}
return false;
}
private void scanVideoDirectories() {
MediaScannerConnection.OnScanCompletedListener scanCompletedListener = (path, uri) ->
Log.d(TAG, String.format("Scanned %s\n -> uri=%s", path, uri));
MediaScannerConnection.scanFile(this, new String[]{FileManager.getRawDirPath()},
null, scanCompletedListener);
}
private void setToolBarAsTheAppBar() {
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("EDA");
toolbar.setTitleTextColor(getColor(R.color.white));
setSupportActionBar(toolbar);
}
private void setUpBottomNavigation() {
BottomNavigationView bottomNavigation = findViewById(R.id.navigation);
bottomNavigation.setOnItemSelectedListener(bottomNavigationOnItemSelectedListener);
}
private void setUpFragments() {
VideosRepository rawRepository = new ExternalStorageVideosRepository(this, FileManager.getRawDirPath());
VideosRepository processingRepository = new ProcessingVideosRepository();
ResultRepository resultRepository = new ResultRepository();
connectionFragment = new ConnectionFragment();
rawFragment = VideoFragment.newInstance(ActionButton.ADD,
new RawVideosEventHandler(rawRepository), RawAdapter::new);
processingFragment = VideoFragment.newInstance(ActionButton.REMOVE,
new ProcessingVideosEventHandler(processingRepository), ProcessingAdapter::new);
resultsFragment = ResultsFragment.newInstance(ActionButton.OPEN, new ResultEventHandler(resultRepository));
supportFragmentManager.beginTransaction().add(R.id.main_container, connectionFragment, "4").hide(connectionFragment).commit();
supportFragmentManager.beginTransaction().add(R.id.main_container, resultsFragment, "3").hide(resultsFragment).commit();
supportFragmentManager.beginTransaction().add(R.id.main_container, processingFragment, "2").hide(processingFragment).commit();
supportFragmentManager.beginTransaction().add(R.id.main_container, rawFragment, "1").commit();
rawFragment.setRepository(rawRepository);
processingFragment.setRepository(processingRepository);
resultsFragment.setRepository(resultRepository);
activeFragment = rawFragment;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_connect) {
Log.v(TAG, "Connect button clicked");
checkWifiStrength();
showNewFragmentAndHideOldFragment(connectionFragment);
return true;
} else if (itemId == R.id.action_download) {
Log.v(TAG, "Download button clicked");
Toast.makeText(this, "Starting download", Toast.LENGTH_SHORT).show();
DashCam.downloadTestVideosLoop(this);
return true;
} else if (itemId == R.id.action_clean) {
Log.v(TAG, "Clean button clicked");
Toast.makeText(this, "Cleaning directories", Toast.LENGTH_SHORT).show();
cleanDirectories();
return true;
} else if (itemId == R.id.action_power) {
Log.v(TAG, "Power button clicked");
PowerMonitor.startPowerMonitor(this);
Toast.makeText(this,
String.format(Locale.ENGLISH, "Average power: %dmW", PowerMonitor.getAveragePowerMilliWatts()),
Toast.LENGTH_SHORT).show();
PowerMonitor.printSummary();
return true;
} else if (itemId == R.id.action_settings) {
Log.v(TAG, "Setting button clicked");
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
private void cleanDirectories() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
if (pref.getBoolean(getString(R.string.remove_raw_key), false)) {
rawFragment.cleanRepository(this);
}
processingFragment.cleanRepository(this);
resultsFragment.cleanRepository();
FileManager.cleanDirectories(this);
}
private void checkWifiStrength() {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int level;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
level = wifiManager.calculateSignalLevel(wifiInfo.getRssi());
} else {
int numberOfLevels = 5;
level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels);
}
String signalMessage = String.format("Signal strength: %s, Speed: %s MB/s", level, DashCam.latestDownloadSpeed);
Log.v(TAG, signalMessage);
Toast.makeText(this, signalMessage, Toast.LENGTH_SHORT).show();
}
@Override
public boolean getIsConnected() {
return isConnected();
}
@Override
public void getAddVideo(Video video) {
addVideo(video);
}
@Override
public void getNextTransfer() {
nextTransfer();
}
@Override
public Runnable simulateDownloads(int delay, Consumer<Video> downloadCallback, boolean dualDownload) {
return rawFragment.simulateDownloads(delay, downloadCallback, dualDownload);
}
@Override
public void onListFragmentInteraction(Result result) {
}
@Override
public void connectEndpoint(Endpoint endpoint) {
connectionFragment.connectEndpoint(endpoint);
}
@Override
public void disconnectEndpoint(Endpoint endpoint) {
connectionFragment.disconnectEndpoint(endpoint);
}
@Override
public void removeEndpoint(Endpoint endpoint) {
connectionFragment.removeEndpoint(endpoint);
}
@Override
public boolean isConnected() {
return connectionFragment.isConnected();
}
@Override
public void addVideo(Video video) {
connectionFragment.addVideo(video);
}
@Override
public void nextTransfer() {
connectionFragment.nextTransfer();
}
@Override
public Runnable getSimulateDownloads(int delay, Consumer<Video> downloadCallback, boolean dualDownload) {
return simulateDownloads(delay, downloadCallback, dualDownload);
}
}
| 14,854 | 38.825737 | 134 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/main/ConnectionFragment.java | package com.example.edgedashanalytics.page.main;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.util.nearby.NearbyFragment;
public class ConnectionFragment extends NearbyFragment {
private static final String TAG = ConnectionFragment.class.getSimpleName();
public ConnectionFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_connection, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.device_list);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(rootView.getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(deviceAdapter);
TextView locName = rootView.findViewById(R.id.local_name);
locName.setText(localName);
SwitchCompat discoverSwitch = rootView.findViewById(R.id.discover_switch);
SwitchCompat advertiseSwitch = rootView.findViewById(R.id.advertise_switch);
SwitchCompat autoDownloadSwitch = rootView.findViewById(R.id.auto_download_switch);
discoverSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
Log.v(TAG, "Discovery switch checked");
startDiscovery(buttonView.getContext());
} else {
Log.v(TAG, "Discovery switch unchecked");
stopDiscovery();
}
});
advertiseSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
Log.v(TAG, "Advertisement switch checked");
startAdvertising(buttonView.getContext());
} else {
Log.v(TAG, "Advertisement switch unchecked");
stopAdvertising();
}
});
autoDownloadSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
Log.v(TAG, "Auto-download switch checked");
startDashDownload();
} else {
Log.v(TAG, "Auto-download switch unchecked");
stopDashDownload();
}
});
return rootView;
}
}
| 2,898 | 34.790123 | 103 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/main/VideoFragment.java | package com.example.edgedashanalytics.page.main;
import android.content.Context;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.selection.ItemKeyProvider;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.data.video.VideoViewModel;
import com.example.edgedashanalytics.data.video.VideoViewModelFactory;
import com.example.edgedashanalytics.data.video.VideosRepository;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.page.adapter.VideoRecyclerViewAdapter;
import com.example.edgedashanalytics.util.video.VideoDetailsLookup;
import com.example.edgedashanalytics.util.video.eventhandler.VideoEventHandler;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A simple {@link Fragment} subclass.
* Use the {@link VideoFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class VideoFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int columnCount = 1;
private Listener listener;
private ActionButton actionButton;
private VideosRepository repository;
private VideoViewModel videoViewModel;
private VideoEventHandler videoEventHandler;
private VideoRecyclerViewAdapter adapter;
private Function<Listener, VideoRecyclerViewAdapter> adapterCreator;
private ActionMode actionMode;
private SelectionTracker<Long> tracker;
private final ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.video_selection_menu, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.send) {
if (actionButton.equals(ActionButton.ADD)) {
adapter.processSelected(tracker.getSelection(), getContext());
}
mode.finish();
return true;
} else if (itemId == R.id.select_all) {
for (long i = 0L; i < adapter.getItemCount(); i++) {
tracker.select(i);
}
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
tracker.clearSelection();
actionMode = null;
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public VideoFragment() {
}
static VideoFragment newInstance(ActionButton actionButton, VideoEventHandler handler,
Function<Listener, VideoRecyclerViewAdapter> adapterCreator) {
VideoFragment fragment = new VideoFragment();
Bundle args = new Bundle();
int columnCount = 1;
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
fragment.actionButton = actionButton;
fragment.videoEventHandler = handler;
fragment.adapterCreator = adapterCreator;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
columnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
setVideoViewModel(new ViewModelProvider(this,
new VideoViewModelFactory(activity.getApplication(), repository)).get(VideoViewModel.class));
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_video_list, container, false);
EventBus.getDefault().register(videoEventHandler);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (columnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, columnCount));
}
adapter = adapterCreator.apply(listener);
recyclerView.setAdapter(adapter);
FragmentActivity activity = getActivity();
if (activity == null) {
return null;
}
videoViewModel.getVideos().observe(activity, videos -> adapter.setVideos(videos));
ItemKeyProvider<Long> videoKeyProvider = new ItemKeyProvider<>(ItemKeyProvider.SCOPE_MAPPED) {
@Override
public Long getKey(int position) {
return adapter.getItemId(position);
}
@Override
public int getPosition(@NonNull Long key) {
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForItemId(key);
return viewHolder == null ? RecyclerView.NO_POSITION : viewHolder.getLayoutPosition();
}
};
tracker = new SelectionTracker.Builder<>(
"video_selection",
recyclerView,
videoKeyProvider,
new VideoDetailsLookup(recyclerView),
StorageStrategy.createLongStorage())
.withSelectionPredicate(SelectionPredicates.createSelectAnything())
.build();
tracker.addObserver(new SelectionTracker.SelectionObserver<>() {
@Override
public void onSelectionChanged() {
super.onSelectionChanged();
// Check that CAB isn't already active and that an item has been selected, prevents activation
// from calls to notifyDataSetChanged()
if (actionMode == null && tracker.hasSelection()) {
actionMode = view.startActionMode(actionModeCallback);
}
}
});
adapter.setTracker(tracker);
}
return view;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof Listener) {
listener = (Listener) context;
} else {
throw new RuntimeException(context + " must implement VideoFragment.Listener");
}
}
@Override
public void onDetach() {
EventBus.getDefault().unregister(videoEventHandler);
super.onDetach();
listener = null;
}
void setRepository(VideosRepository repository) {
this.repository = repository;
}
private void setVideoViewModel(VideoViewModel videoViewModel) {
this.videoViewModel = videoViewModel;
}
void cleanRepository(Context context) {
List<Video> videos = repository.getVideos().getValue();
if (videos != null) {
int videoCount = videos.size();
for (int i = 0; i < videoCount; i++) {
Video video = videos.get(0);
context.getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
MediaStore.MediaColumns.DATA + "=?", new String[]{video.getData()});
repository.delete(0);
}
}
adapter.setVideos(new ArrayList<>());
}
Runnable simulateDownloads(int delay, Consumer<Video> downloadCallback, boolean dualDownload) {
return adapter.simulateDownloads(delay, downloadCallback, dualDownload);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface Listener {
boolean getIsConnected();
void getAddVideo(Video video);
void getNextTransfer();
Runnable simulateDownloads(int delay, Consumer<Video> downloadCallback, boolean dualDownload);
}
}
| 9,724 | 34.885609 | 114 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/main/ActionButton.java | package com.example.edgedashanalytics.page.main;
public enum ActionButton {
ADD,
REMOVE,
OPEN
}
| 109 | 12.75 | 48 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/page/main/ResultsFragment.java | package com.example.edgedashanalytics.page.main;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.data.result.ResultRepository;
import com.example.edgedashanalytics.data.result.ResultViewModel;
import com.example.edgedashanalytics.data.result.ResultViewModelFactory;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.page.adapter.ResultRecyclerViewAdapter;
import com.example.edgedashanalytics.util.video.eventhandler.ResultEventHandler;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Use the {@link ResultsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ResultsFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int columnCount = 1;
private Listener listener;
private ActionButton actionButton;
private ResultRepository repository;
private ResultViewModel resultViewModel;
private ResultEventHandler resultEventHandler;
private ResultRecyclerViewAdapter adapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ResultsFragment() {
}
static ResultsFragment newInstance(ActionButton actionButton, ResultEventHandler handler) {
ResultsFragment fragment = new ResultsFragment();
Bundle args = new Bundle();
int columnCount = 1;
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
fragment.actionButton = actionButton;
fragment.resultEventHandler = handler;
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
columnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
this.resultViewModel = new ViewModelProvider(this,
new ResultViewModelFactory(activity.getApplication(), repository)).get(ResultViewModel.class);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_result_list, container, false);
EventBus.getDefault().register(resultEventHandler);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (columnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, columnCount));
}
adapter = new ResultRecyclerViewAdapter(listener, actionButton.toString());
recyclerView.setAdapter(adapter);
FragmentActivity activity = getActivity();
if (activity == null) {
return null;
}
resultViewModel.getResults().observe(activity, results -> adapter.setResults(results));
}
return view;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof Listener) {
listener = (Listener) context;
} else {
throw new RuntimeException(context + " must implement ResultsFragment.Listener");
}
}
@Override
public void onDetach() {
EventBus.getDefault().unregister(resultEventHandler);
super.onDetach();
listener = null;
}
void setRepository(ResultRepository repository) {
this.repository = repository;
}
void cleanRepository() {
List<Result> results = repository.getResults().getValue();
if (results != null) {
int resultsCount = results.size();
for (int i = 0; i < resultsCount; i++) {
repository.delete(0);
}
}
adapter.setResults(new ArrayList<>());
}
int getItemCount() {
return adapter.getItemCount();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface Listener {
@SuppressWarnings({"unused", "EmptyMethod"})
void onListFragmentInteraction(Result result);
}
}
| 5,490 | 32.481707 | 110 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/TimeManager.java | package com.example.edgedashanalytics.util;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.util.Log;
import androidx.collection.SimpleArrayMap;
import org.apache.commons.lang3.time.DurationFormatUtils;
import java.time.Duration;
import java.time.Instant;
public class TimeManager {
private static final SimpleArrayMap<String, Instant> startTimes = new SimpleArrayMap<>();
public static String getDurationString(Instant start) {
return getDurationString(start, true);
}
public static String getDurationString(Instant start, boolean roundUp) {
long duration = Duration.between(start, Instant.now()).toMillis();
return formatDuration(duration, roundUp);
}
private static String getDurationString(Instant start, Instant end) {
long duration = Duration.between(start, end).toMillis();
return formatDuration(duration, true);
}
private static String formatDuration(long duration, boolean roundUp) {
String time = DurationFormatUtils.formatDuration(duration, "ss.SSS");
if (roundUp && time.equals("00.000")) {
// Time value is less than one millisecond, round up to one millisecond
return "00.001";
}
return time;
}
public static void addStartTime(String filename) {
startTimes.put(filename, Instant.now());
}
public static Instant getStartTime(String filename) {
return startTimes.get(filename);
}
public static void printTurnaroundTime(String filename, Instant end) {
printTurnaroundTime(filename, filename, end);
}
public static void printTurnaroundTime(String originalName, String newName, Instant end) {
Instant start = startTimes.get(originalName);
if (start == null) {
Log.w(I_TAG, String.format("Could not calculate the turnaround time of %s", newName));
} else {
String time = getDurationString(start, end);
Log.i(I_TAG, String.format("Turnaround time of %s: %ss", newName, time));
}
}
}
| 2,103 | 31.875 | 98 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/nearby/Algorithm.java | package com.example.edgedashanalytics.util.nearby;
import java.util.Comparator;
import java.util.List;
public class Algorithm {
public enum AlgorithmKey {
round_robin,
fastest,
least_busy,
fastest_cpu,
most_cpu_cores,
most_ram,
most_storage,
highest_battery,
max_capacity
}
public static final AlgorithmKey DEFAULT_ALGORITHM = AlgorithmKey.fastest;
/**
* @return next endpoint in round-robin sequence
*/
static Endpoint getRoundRobinEndpoint(List<Endpoint> endpoints, int transferCount) {
int nextIndex = transferCount % endpoints.size();
return endpoints.get(nextIndex);
}
/**
* @return an inactive endpoint with the most completions, or the endpoint with the shortest job queue
*/
static Endpoint getFastestEndpoint(List<Endpoint> endpoints) {
int maxComplete = Integer.MIN_VALUE;
int minJobs = Integer.MAX_VALUE;
Endpoint fastest = null;
for (Endpoint endpoint : endpoints) {
if (endpoint.isInactive() && endpoint.completeCount > maxComplete) {
maxComplete = endpoint.completeCount;
fastest = endpoint;
}
}
if (fastest != null) {
return fastest;
}
// No free workers, so just choose the one with the shortest job queue, use completion count as tiebreaker
for (Endpoint endpoint : endpoints) {
if (endpoint.getJobCount() < minJobs ||
(endpoint.getJobCount() == minJobs && endpoint.completeCount > maxComplete)) {
maxComplete = endpoint.completeCount;
minJobs = endpoint.getJobCount();
fastest = endpoint;
}
}
return fastest;
}
/**
* @return the endpoint with the smallest job queue
*/
static Endpoint getLeastBusyEndpoint(List<Endpoint> endpoints) {
return endpoints.stream().min(Comparator.comparing(Endpoint::getJobCount)).orElse(null);
}
static Endpoint getFastestCpuEndpoint(List<Endpoint> endpoints) {
long maxCpuHz = 0;
int minJobs = Integer.MAX_VALUE;
Endpoint fastest = null;
for (Endpoint endpoint : endpoints) {
if (endpoint.isInactive() && endpoint.hardwareInfo.cpuFreq > maxCpuHz) {
maxCpuHz = endpoint.hardwareInfo.cpuFreq;
fastest = endpoint;
}
}
if (fastest != null) {
return fastest;
}
for (Endpoint endpoint : endpoints) {
if (endpoint.hardwareInfo.cpuFreq > maxCpuHz ||
endpoint.hardwareInfo.cpuFreq == maxCpuHz && endpoint.getJobCount() < minJobs) {
maxCpuHz = endpoint.hardwareInfo.cpuFreq;
minJobs = endpoint.getJobCount();
fastest = endpoint;
}
}
return fastest;
}
static Endpoint getMaxCpuCoreEndpoint(List<Endpoint> endpoints) {
int maxCpuCores = 0;
int minJobs = Integer.MAX_VALUE;
Endpoint result = null;
for (Endpoint endpoint : endpoints) {
if (endpoint.isInactive() && endpoint.hardwareInfo.cpuCores > maxCpuCores) {
maxCpuCores = endpoint.hardwareInfo.cpuCores;
result = endpoint;
}
}
if (result != null) {
return result;
}
for (Endpoint endpoint : endpoints) {
if (endpoint.hardwareInfo.cpuCores > maxCpuCores ||
endpoint.hardwareInfo.cpuCores == maxCpuCores && endpoint.getJobCount() < minJobs) {
maxCpuCores = endpoint.hardwareInfo.cpuCores;
minJobs = endpoint.getJobCount();
result = endpoint;
}
}
return result;
}
static Endpoint getMaxRamEndpoint(List<Endpoint> endpoints) {
long maxRam = 0;
int minJobs = Integer.MAX_VALUE;
Endpoint result = null;
for (Endpoint endpoint : endpoints) {
if (endpoint.isInactive() && endpoint.hardwareInfo.availRam > maxRam) {
maxRam = endpoint.hardwareInfo.availRam;
result = endpoint;
}
}
if (result != null) {
return result;
}
for (Endpoint endpoint : endpoints) {
if (endpoint.hardwareInfo.availRam > maxRam ||
endpoint.hardwareInfo.availRam == maxRam && endpoint.getJobCount() < minJobs) {
maxRam = endpoint.hardwareInfo.availRam;
minJobs = endpoint.getJobCount();
result = endpoint;
}
}
return result;
}
static Endpoint getMaxStorageEndpoint(List<Endpoint> endpoints) {
long maxStorage = 0;
int minJobs = Integer.MAX_VALUE;
Endpoint result = null;
for (Endpoint endpoint : endpoints) {
if (endpoint.isInactive() && endpoint.hardwareInfo.availStorage > maxStorage) {
maxStorage = endpoint.hardwareInfo.availStorage;
result = endpoint;
}
}
if (result != null) {
return result;
}
for (Endpoint endpoint : endpoints) {
if (endpoint.hardwareInfo.availStorage > maxStorage ||
endpoint.hardwareInfo.availStorage == maxStorage && endpoint.getJobCount() < minJobs) {
maxStorage = endpoint.hardwareInfo.availStorage;
minJobs = endpoint.getJobCount();
result = endpoint;
}
}
return result;
}
static Endpoint getMaxBatteryEndpoint(List<Endpoint> endpoints) {
int maxBattery = 0;
int minJobs = Integer.MAX_VALUE;
Endpoint result = null;
for (Endpoint endpoint : endpoints) {
if (endpoint.isInactive() && endpoint.hardwareInfo.batteryLevel > maxBattery) {
maxBattery = endpoint.hardwareInfo.batteryLevel;
result = endpoint;
}
}
if (result != null) {
return result;
}
for (Endpoint endpoint : endpoints) {
if (endpoint.hardwareInfo.batteryLevel > maxBattery ||
endpoint.hardwareInfo.batteryLevel == maxBattery && endpoint.getJobCount() < minJobs) {
maxBattery = endpoint.hardwareInfo.batteryLevel;
minJobs = endpoint.getJobCount();
result = endpoint;
}
}
return result;
}
static Endpoint getMaxCapacityEndpoint(List<Endpoint> endpoints) {
Endpoint fastest = endpoints.stream()
.filter(Endpoint::isInactive)
.max(Endpoint.compareProcessing())
.orElse(null);
if (fastest != null) {
return fastest;
}
return endpoints.stream()
.max(Endpoint.compareProcessing().thenComparing(Endpoint::getJobCount))
.orElse(null);
}
}
| 7,108 | 30.878924 | 114 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/nearby/Endpoint.java | package com.example.edgedashanalytics.util.nearby;
import androidx.annotation.NonNull;
import com.example.edgedashanalytics.util.hardware.HardwareInfo;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Endpoint {
static final int MAX_CONNECTION_ATTEMPTS = 10;
final String id;
final String name;
private final List<String> jobList = new ArrayList<>();
boolean connected;
HardwareInfo hardwareInfo;
int sendCount = 0;
int completeCount = 0;
int connectionAttempt = 0;
Endpoint(String id, String name) {
this.id = id;
this.name = name;
this.connected = false;
}
boolean isInactive() {
return jobList.isEmpty();
}
void addJob(String videoName) {
jobList.add(videoName);
}
void removeJob(String videoName) {
jobList.remove(videoName);
}
int getJobCount() {
return jobList.size();
}
static Comparator<Endpoint> compareProcessing() {
return (e1, e2) -> HardwareInfo.compareProcessing(e1.hardwareInfo, e2.hardwareInfo);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Endpoint) {
Endpoint other = (Endpoint) obj;
return id.equals(other.id);
}
return false;
}
@Override
public int hashCode() {
return id.hashCode();
}
@NonNull
@Override
public String toString() {
return String.format("Endpoint{id=%s, name=%s}", id, name);
}
}
| 1,550 | 20.84507 | 92 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/nearby/NearbyFragment.java | package com.example.edgedashanalytics.util.nearby;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.collection.SimpleArrayMap;
import androidx.fragment.app.Fragment;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.event.result.AddResultEvent;
import com.example.edgedashanalytics.event.video.AddEvent;
import com.example.edgedashanalytics.event.video.RemoveByNameEvent;
import com.example.edgedashanalytics.event.video.RemoveEvent;
import com.example.edgedashanalytics.event.video.Type;
import com.example.edgedashanalytics.model.Content;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.page.setting.SettingsActivity;
import com.example.edgedashanalytics.util.TimeManager;
import com.example.edgedashanalytics.util.dashcam.DashCam;
import com.example.edgedashanalytics.util.file.FileManager;
import com.example.edgedashanalytics.util.file.JsonManager;
import com.example.edgedashanalytics.util.hardware.HardwareInfo;
import com.example.edgedashanalytics.util.hardware.PowerMonitor;
import com.example.edgedashanalytics.util.nearby.Algorithm.AlgorithmKey;
import com.example.edgedashanalytics.util.nearby.Message.Command;
import com.example.edgedashanalytics.util.video.FfmpegTools;
import com.example.edgedashanalytics.util.video.VideoManager;
import com.example.edgedashanalytics.util.video.analysis.InnerAnalysis;
import com.example.edgedashanalytics.util.video.analysis.OuterAnalysis;
import com.example.edgedashanalytics.util.video.analysis.VideoAnalysis;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.connection.AdvertisingOptions;
import com.google.android.gms.nearby.connection.ConnectionInfo;
import com.google.android.gms.nearby.connection.ConnectionLifecycleCallback;
import com.google.android.gms.nearby.connection.ConnectionOptions;
import com.google.android.gms.nearby.connection.ConnectionResolution;
import com.google.android.gms.nearby.connection.ConnectionType;
import com.google.android.gms.nearby.connection.ConnectionsClient;
import com.google.android.gms.nearby.connection.ConnectionsStatusCodes;
import com.google.android.gms.nearby.connection.DiscoveredEndpointInfo;
import com.google.android.gms.nearby.connection.DiscoveryOptions;
import com.google.android.gms.nearby.connection.EndpointDiscoveryCallback;
import com.google.android.gms.nearby.connection.Payload;
import com.google.android.gms.nearby.connection.PayloadCallback;
import com.google.android.gms.nearby.connection.PayloadTransferUpdate;
import com.google.android.gms.nearby.connection.Strategy;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.greenrobot.eventbus.EventBus;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
public abstract class NearbyFragment extends Fragment {
private static final String TAG = NearbyFragment.class.getSimpleName();
private static final Strategy STRATEGY = Strategy.P2P_STAR;
private static final String SERVICE_ID = "com.example.edgedashanalytics";
private static final String LOCAL_NAME_KEY = "LOCAL_NAME";
private static final String MESSAGE_SEPARATOR = "~";
private static int transferCount = 0;
private final ReceiveFilePayloadCallback payloadCallback = new ReceiveFilePayloadCallback();
private final Queue<Message> transferQueue = new LinkedList<>();
private final LinkedHashMap<String, Endpoint> discoveredEndpoints = new LinkedHashMap<>();
private final ExecutorService analysisExecutor = Executors.newSingleThreadExecutor();
private final List<Future<?>> analysisFutures = new ArrayList<>();
private final ScheduledExecutorService downloadTaskExecutor = Executors.newSingleThreadScheduledExecutor();
private final LinkedHashMap<String, Instant> waitTimes = new LinkedHashMap<>();
private ConnectionsClient connectionsClient;
protected DeviceListAdapter deviceAdapter;
protected String localName = null;
private Listener listener;
private boolean verbose;
private boolean master = false;
private boolean isMasterFastest = false;
private InnerAnalysis innerAnalysis;
private OuterAnalysis outerAnalysis;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity activity = getActivity();
if (activity == null) {
Log.e(TAG, "No activity");
return;
}
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(activity);
verbose = pref.getBoolean(getString(R.string.verbose_output_key), false);
deviceAdapter = new DeviceListAdapter(listener, activity, discoveredEndpoints);
connectionsClient = Nearby.getConnectionsClient(activity);
setLocalName(activity);
innerAnalysis = new InnerAnalysis(activity);
outerAnalysis = new OuterAnalysis(activity);
}
@Override
public void onStop() {
super.onStop();
stopDashDownload();
DashCam.clearDownloads();
stopAdvertising();
stopDiscovery();
payloadCallback.cancelAllPayloads();
connectionsClient.stopAllEndpoints();
}
private void setLocalName(Context context) {
if (localName != null) {
return;
}
SharedPreferences sharedPrefs = context.getSharedPreferences(LOCAL_NAME_KEY, Context.MODE_PRIVATE);
String uniqueId = sharedPrefs.getString(LOCAL_NAME_KEY, null);
if (uniqueId == null) {
uniqueId = RandomStringUtils.randomAlphanumeric(8);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(LOCAL_NAME_KEY, uniqueId);
editor.apply();
}
localName = String.format("%s [%s]", Build.MODEL, uniqueId);
}
private final EndpointDiscoveryCallback endpointDiscoveryCallback =
new EndpointDiscoveryCallback() {
@Override
public void onEndpointFound(@NonNull String endpointId, @NonNull DiscoveredEndpointInfo info) {
Log.d(TAG, String.format("Found endpoint %s: %s", endpointId, info.getEndpointName()));
if (!discoveredEndpoints.containsKey(endpointId)) {
discoveredEndpoints.put(endpointId, new Endpoint(endpointId, info.getEndpointName()));
deviceAdapter.notifyItemInserted(discoveredEndpoints.size() - 1);
}
}
@Override
public void onEndpointLost(@NonNull String endpointId) {
// A previously discovered endpoint has gone away.
Log.d(TAG, String.format("Lost endpoint %s", discoveredEndpoints.get(endpointId)));
if (discoveredEndpoints.containsKey(endpointId)) {
discoveredEndpoints.remove(endpointId);
deviceAdapter.notifyDataSetChanged();
}
}
};
private final ConnectionLifecycleCallback connectionLifecycleCallback =
new ConnectionLifecycleCallback() {
@Override
public void onConnectionInitiated(@NonNull String endpointId, @NonNull ConnectionInfo connectionInfo) {
Log.d(TAG, String.format("Initiated connection with %s: %s",
endpointId, connectionInfo.getEndpointName()));
if (!discoveredEndpoints.containsKey(endpointId)) {
discoveredEndpoints.put(endpointId, new Endpoint(endpointId, connectionInfo.getEndpointName()));
deviceAdapter.notifyItemInserted(discoveredEndpoints.size() - 1);
}
connectionsClient.acceptConnection(endpointId, payloadCallback);
}
@Override
public void onConnectionResult(@NonNull String endpointId, ConnectionResolution result) {
switch (result.getStatus().getStatusCode()) {
case ConnectionsStatusCodes.STATUS_OK:
// We're connected! Can now start sending and receiving data.
Endpoint endpoint = discoveredEndpoints.get(endpointId);
Log.i(TAG, String.format("Connected to %s", endpoint));
if (endpoint != null) {
endpoint.connected = true;
endpoint.connectionAttempt = 0;
requestHardwareInfo(endpointId);
deviceAdapter.notifyDataSetChanged();
}
break;
case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
// The connection was rejected by one or both sides.
Log.i(TAG, String.format("Connection rejected by %s", discoveredEndpoints.get(endpointId)));
break;
case ConnectionsStatusCodes.STATUS_ERROR:
// The connection broke before it was able to be accepted.
Log.e(TAG, "Connection error");
break;
default:
// Unknown status code
Log.e(TAG, "Unknown status code");
}
}
@Override
public void onDisconnected(@NonNull String endpointId) {
// We've been disconnected from this endpoint. No more data can be sent or received.
Endpoint endpoint = discoveredEndpoints.get(endpointId);
if (endpoint == null) {
Log.d(TAG, String.format("Disconnected from %s", endpointId));
return;
}
if (endpoint.connected) {
Log.d(TAG, String.format("Disconnected from %s", endpoint));
endpoint.connected = false;
deviceAdapter.notifyDataSetChanged();
}
if (master && endpoint.connectionAttempt < Endpoint.MAX_CONNECTION_ATTEMPTS) {
int delay = 5;
ScheduledExecutorService reconnectExecutor = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> promise = reconnectExecutor.scheduleWithFixedDelay(reconnect(endpoint),
1, delay, TimeUnit.SECONDS);
reconnectExecutor.schedule(() -> promise.cancel(false),
delay * Endpoint.MAX_CONNECTION_ATTEMPTS, TimeUnit.SECONDS);
}
}
private Runnable reconnect(Endpoint endpoint) {
return () -> {
Log.d(TAG, String.format("Attempting reconnection with %s (attempt %s)",
endpoint, endpoint.connectionAttempt));
endpoint.connectionAttempt++;
connectEndpoint(endpoint);
};
}
};
protected void startAdvertising(Context context) {
// Only master should advertise
master = true;
PowerMonitor.startPowerMonitor(context);
AdvertisingOptions advertisingOptions = new AdvertisingOptions.Builder()
.setStrategy(STRATEGY).setConnectionType(ConnectionType.DISRUPTIVE).build();
connectionsClient.startAdvertising(localName, SERVICE_ID, connectionLifecycleCallback, advertisingOptions)
.addOnSuccessListener((Void unused) ->
Log.d(TAG, "Started advertising"))
.addOnFailureListener((Exception e) ->
Log.e(TAG, String.format("Advertisement failure: \n%s", e.getMessage())));
}
protected void startDiscovery(Context context) {
PowerMonitor.startPowerMonitor(context);
SettingsActivity.printPreferences(master, false, context);
DiscoveryOptions discoveryOptions = new DiscoveryOptions.Builder().setStrategy(STRATEGY).build();
connectionsClient.startDiscovery(SERVICE_ID, endpointDiscoveryCallback, discoveryOptions)
.addOnSuccessListener((Void unused) ->
Log.d(TAG, "Started discovering"))
.addOnFailureListener((Exception e) ->
Log.e(TAG, String.format("Discovery failure: \n%s", e.getMessage())));
}
protected void stopAdvertising() {
Log.d(TAG, "Stopped advertising");
connectionsClient.stopAdvertising();
}
protected void stopDiscovery() {
Log.d(TAG, "Stopped discovering");
connectionsClient.stopDiscovery();
}
// https://stackoverflow.com/a/11944965/8031185
protected void startDashDownload() {
// Only master (or offline device) should start downloads
master = true;
Context context = getContext();
if (context == null) {
Log.e(TAG, "No context");
return;
}
String defaultDelay = "1000";
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
int delay = Integer.parseInt(pref.getString(context.getString(R.string.download_delay_key), defaultDelay));
SettingsActivity.printPreferences(master, true, context);
Log.w(I_TAG, "Started downloading from dash cam");
PowerMonitor.startPowerMonitor(context);
boolean simDownload = pref.getBoolean(context.getString(R.string.enable_download_simulation_key), false);
int simDelay = Integer.parseInt(pref.getString(context.getString(R.string.simulation_delay_key), defaultDelay));
boolean dualDownload = pref.getBoolean(context.getString(R.string.dual_download_key), false);
Endpoint fastest = getConnectedEndpoints().stream().max(Endpoint.compareProcessing()).orElse(null);
isMasterFastest = fastest != null &&
HardwareInfo.compareProcessing(new HardwareInfo(context), fastest.hardwareInfo) > 0;
if (simDownload) {
downloadTaskExecutor.scheduleWithFixedDelay(listener.getSimulateDownloads(simDelay,
this::downloadCallback, dualDownload), 0, delay, TimeUnit.MILLISECONDS);
} else {
DashCam.setDownloadCallback(context, this::downloadCallback);
downloadTaskExecutor.scheduleWithFixedDelay(DashCam.downloadTestVideos(), 0, delay, TimeUnit.MILLISECONDS);
}
}
protected void stopDashDownload() {
if (!downloadTaskExecutor.isShutdown()) {
Log.w(I_TAG, "Stopped downloading from dash cam");
downloadTaskExecutor.shutdown();
} else {
Log.w(TAG, "Dash cam downloads have already stopped");
}
}
private void downloadCallback(Video video) {
if (video == null) {
stopDashDownload();
return;
}
if (!isConnected()) {
analyse(video, false);
return;
}
Context context = getContext();
if (context == null) {
Log.e(TAG, "No context");
return;
}
FfmpegTools.setDuration(video.getData());
EventBus.getDefault().post(new AddEvent(video, Type.RAW));
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
boolean segmentationEnabled = pref.getBoolean(getString(R.string.enable_segment_key), false);
int segNum = pref.getInt(getString(R.string.segment_number_key), 0);
if (!segmentationEnabled) {
addVideo(video);
nextTransfer();
return;
}
if (segNum < 2 && getConnectedEndpoints().size() > 1) {
// Dynamic segmentation
evenSegmentation(video);
} else {
// Static segmentation
splitAndQueue(video.getData(), segNum);
}
}
private void evenSegmentation(Video video) {
List<Endpoint> endpoints = getConnectedEndpoints();
if (isMasterFastest) {
if (video.isOuter()) {
// Process whole video locally
Log.d(I_TAG, String.format("Processing %s locally", video.getName()));
analyse(video, false);
} else {
// Split video and send to workers
List<Video> segments = FfmpegTools.splitAndReturn(getContext(), video.getData(), endpoints.size());
List<Endpoint> sortedEndpoints = endpoints.stream()
.sorted(Endpoint.compareProcessing())
.collect(Collectors.toList());
for (int i = 0; i < segments.size() && i < sortedEndpoints.size(); i++) {
sendFile(new Message(segments.get(i), Command.SEGMENT), sortedEndpoints.get(i));
}
}
} else {
Endpoint fastest = endpoints.stream().max(Endpoint.compareProcessing()).orElse(null);
if (video.isOuter()) {
// Send whole video to the fastest worker
sendFile(new Message(video, Command.ANALYSE), fastest);
} else {
// Master will locally process one segment
List<Video> segments = FfmpegTools.splitAndReturn(getContext(), video.getData(), endpoints.size());
analyse(segments.remove(0), false);
// Send remaining segments to non-fastest workers
List<Endpoint> remainingEndpoints = endpoints.stream()
.filter(e -> e != fastest)
.sorted(Endpoint.compareProcessing())
.collect(Collectors.toList());
for (int i = 0; i < segments.size() && i < remainingEndpoints.size(); i++) {
sendFile(new Message(segments.get(i), Command.SEGMENT), remainingEndpoints.get(i));
}
}
}
}
private List<Endpoint> getConnectedEndpoints() {
return discoveredEndpoints.values().stream().filter(e -> e.connected).collect(Collectors.toList());
}
public boolean isConnected() {
return discoveredEndpoints.values().stream().anyMatch(e -> e.connected);
}
public void connectEndpoint(Endpoint endpoint) {
Log.d(TAG, String.format("Attempting to connect to %s", endpoint));
if (!endpoint.connected) {
ConnectionOptions connectionOptions = new ConnectionOptions.Builder()
.setConnectionType(ConnectionType.DISRUPTIVE).build();
connectionsClient.requestConnection(localName, endpoint.id, connectionLifecycleCallback, connectionOptions)
.addOnSuccessListener(
// We successfully requested a connection. Now both sides
// must accept before the connection is established.
(Void unused) -> Log.d(TAG, String.format("Requested connection with %s", endpoint)))
.addOnFailureListener(
// Nearby Connections failed to request the connection.
(Exception e) -> Log.e(TAG, String.format("Endpoint failure: \n%s", e.getMessage())));
} else {
Log.d(TAG, String.format("'%s' is already connected", endpoint));
}
}
public void disconnectEndpoint(Endpoint endpoint) {
Log.d(TAG, String.format("Disconnected from '%s'", endpoint));
connectionsClient.disconnectFromEndpoint(endpoint.id);
endpoint.connected = false;
deviceAdapter.notifyDataSetChanged();
}
public void removeEndpoint(Endpoint endpoint) {
Log.d(TAG, String.format("Removed %s", endpoint));
discoveredEndpoints.remove(endpoint.id);
deviceAdapter.notifyDataSetChanged();
}
private void sendAdjMessage(double adjust, String toEndpointId) {
String commandMessage = String.join(
MESSAGE_SEPARATOR, Command.ADJ_ESD.toString(), String.format(Locale.ENGLISH, "%.4f", adjust));
Payload commandBytesPayload = Payload.fromBytes(commandMessage.getBytes(UTF_8));
connectionsClient.sendPayload(toEndpointId, commandBytesPayload);
}
@SuppressWarnings("SameParameterValue")
private void sendCommandMessage(Command command, String filename, String toEndpointId) {
String commandMessage = String.join(MESSAGE_SEPARATOR, command.toString(), filename);
Payload filenameBytesPayload = Payload.fromBytes(commandMessage.getBytes(UTF_8));
connectionsClient.sendPayload(toEndpointId, filenameBytesPayload);
}
private void sendHardwareInfo(Context context) {
HardwareInfo hwi = new HardwareInfo(context);
String hwiMessage = String.join(MESSAGE_SEPARATOR, Command.HW_INFO.toString(), hwi.toJson());
Payload messageBytesPayload = Payload.fromBytes(hwiMessage.getBytes(UTF_8));
Log.d(TAG, String.format("Sending hardware information: \n%s", hwi));
// Only sent from worker to master, might be better to make bidirectional
List<String> connectedEndpointIds = discoveredEndpoints.values().stream()
.filter(e -> e.connected)
.map(e -> e.id)
.collect(Collectors.toList());
connectionsClient.sendPayload(connectedEndpointIds, messageBytesPayload);
}
private void requestHardwareInfo(String toEndpoint) {
Log.d(TAG, String.format("Requesting hardware information from %s", toEndpoint));
String hwrMessage = String.format("%s%s", Command.HW_INFO_REQUEST, MESSAGE_SEPARATOR);
Payload messageBytesPayload = Payload.fromBytes(hwrMessage.getBytes(UTF_8));
connectionsClient.sendPayload(toEndpoint, messageBytesPayload);
}
private void queueVideo(Video video, Command command) {
transferQueue.add(new Message(video, command));
}
public void addVideo(Video video) {
queueVideo(video, Command.ANALYSE);
}
private void returnContent(Content content) {
List<Endpoint> endpoints = getConnectedEndpoints();
Message message = new Message(content, Command.RETURN);
if (!master) {
sendFile(message, endpoints.get(0));
} else {
Log.e(TAG, "Non-worker attempting to return a video");
}
}
private void splitAndQueue(String videoPath, int segNum) {
Context context = getContext();
if (context == null) {
Log.e(TAG, "No context");
return;
}
Instant start = Instant.now();
String baseVideoName = FilenameUtils.getBaseName(videoPath);
List<Video> videos = FfmpegTools.splitAndReturn(context, videoPath, segNum);
if (videos == null || videos.size() == 0) {
Log.e(I_TAG, String.format("Could not split %s", baseVideoName));
return;
}
String time = TimeManager.getDurationString(start);
Log.i(I_TAG, String.format("Split %s into %s segments in %ss", baseVideoName, segNum, time));
int vidNum = videos.size();
if (vidNum != segNum) {
Log.w(TAG, String.format("Number of segmented videos (%d) does not match intended value (%d)",
vidNum, segNum));
}
if (vidNum == 1) {
queueVideo(videos.get(0), Command.ANALYSE);
return;
}
for (Video segment : videos) {
queueVideo(segment, Command.SEGMENT);
}
}
private void handleSegment(String resultName, String fromEndpointId) {
String segmentName = FileManager.getVideoNameFromResultName(resultName);
String baseName = FfmpegTools.getBaseName(resultName);
String parentName = String.format("%s.%s", baseName, FilenameUtils.getExtension(resultName));
String videoName = FileManager.getVideoNameFromResultName(parentName);
Instant end = Instant.now();
TimeManager.printTurnaroundTime(videoName, segmentName, end);
double adjust = VideoAnalysis.getEsdAdjust(videoName, end, isConnected());
if (fromEndpointId != null && adjust != 0) {
sendAdjMessage(adjust, fromEndpointId);
}
List<Result> results = FileManager.getResultsFromDir(FileManager.getSegmentResSubDirPath(resultName));
int resultTotal = FfmpegTools.getSegmentCount(resultName);
if (results == null) {
Log.d(TAG, "Couldn't retrieve results");
return;
}
if (results.size() == resultTotal) {
Log.d(TAG, String.format("Received all result segments of %s", baseName));
Result result = JsonManager.mergeResults(parentName);
EventBus.getDefault().post(new AddResultEvent(result));
EventBus.getDefault().post(new RemoveByNameEvent(videoName, Type.RAW));
EventBus.getDefault().post(new RemoveByNameEvent(videoName, Type.PROCESSING));
// TimeManager.printTurnaroundTime(videoName);
PowerMonitor.printSummary();
PowerMonitor.printBatteryLevel(getContext());
} else {
Log.v(TAG, String.format("Received a segment of %s", baseName));
}
}
public void nextTransfer() {
Context context = getContext();
if (context == null) {
Log.e(TAG, "No context");
return;
}
Message message;
synchronized (transferQueue) {
if (transferQueue.isEmpty()) {
Log.i(TAG, "Transfer queue is empty");
return;
}
message = transferQueue.remove();
}
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String algorithmKey = getString(R.string.scheduling_algorithm_key);
String localProcessKey = getString(R.string.local_process_key);
AlgorithmKey algorithm = AlgorithmKey.valueOf(pref.getString(algorithmKey, Algorithm.DEFAULT_ALGORITHM.name()));
boolean localProcess = pref.getBoolean(localProcessKey, false);
Log.v(TAG, String.format("nextTransfer with selected algorithm: %s", algorithm.name()));
List<Endpoint> endpoints = getConnectedEndpoints();
boolean localFree = analysisFutures.stream().allMatch(Future::isDone);
boolean anyFreeEndpoint = endpoints.stream().anyMatch(Endpoint::isInactive);
if (localProcess && endpoints.size() == 1 && algorithm.equals(AlgorithmKey.max_capacity)) {
Video video = (Video) message.content;
boolean isOuter = video.isOuter();
if ((isMasterFastest && isOuter) || (!isMasterFastest && !isOuter)) {
Log.d(I_TAG, String.format("Processing %s locally", video.getName()));
analyse(video, false);
} else {
sendFile(message, endpoints.get(0));
}
return;
}
if (localProcess && localFree && (isMasterFastest || !anyFreeEndpoint)) {
Video video = (Video) message.content;
Log.d(I_TAG, String.format("Processing %s locally", video.getName()));
analyse(video, false);
return;
}
Endpoint selected = null;
switch (algorithm) {
case round_robin:
selected = Algorithm.getRoundRobinEndpoint(endpoints, transferCount);
break;
case fastest:
selected = Algorithm.getFastestEndpoint(endpoints);
break;
case least_busy:
selected = Algorithm.getLeastBusyEndpoint(endpoints);
break;
case fastest_cpu:
selected = Algorithm.getFastestCpuEndpoint(endpoints);
break;
case most_cpu_cores:
selected = Algorithm.getMaxCpuCoreEndpoint(endpoints);
break;
case most_ram:
selected = Algorithm.getMaxRamEndpoint(endpoints);
break;
case most_storage:
selected = Algorithm.getMaxStorageEndpoint(endpoints);
break;
case highest_battery:
selected = Algorithm.getMaxBatteryEndpoint(endpoints);
break;
case max_capacity:
selected = Algorithm.getMaxCapacityEndpoint(endpoints);
break;
}
sendFile(message, selected);
}
private void sendFile(Message message, Endpoint toEndpoint) {
if (message == null || toEndpoint == null) {
Log.e(I_TAG, "No message or endpoint selected");
return;
}
File fileToSend = new File(message.content.getData());
Uri uri = Uri.fromFile(fileToSend);
Payload filePayload = null;
Context context = getContext();
if (context == null) {
Log.e(TAG, "No context");
return;
}
try {
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if (pfd != null) {
filePayload = Payload.fromFile(pfd);
}
} catch (FileNotFoundException e) {
Log.e(TAG, String.format("sendFile ParcelFileDescriptor error: \n%s", e.getMessage()));
}
if (filePayload == null) {
Log.e(I_TAG, String.format("Could not create file payload for %s", message.content));
return;
}
Log.i(I_TAG, String.format("Sending %s to %s", message.content.getName(), toEndpoint.name));
// Construct a message mapping the ID of the file payload to the desired filename and command.
String bytesMessage = String.join(MESSAGE_SEPARATOR, message.command.toString(),
Long.toString(filePayload.getId()), uri.getLastPathSegment());
// Send the filename message as a bytes payload.
// Master will send to all workers, workers will just send to master
Payload filenameBytesPayload = Payload.fromBytes(bytesMessage.getBytes(UTF_8));
connectionsClient.sendPayload(toEndpoint.id, filenameBytesPayload);
// Finally, send the file payload.
connectionsClient.sendPayload(toEndpoint.id, filePayload);
toEndpoint.addJob(uri.getLastPathSegment());
transferCount++;
}
private void analyse(File videoFile) {
analyse(VideoManager.getVideoFromPath(getContext(), videoFile.getAbsolutePath()), true);
}
private void analyse(Video video, boolean returnResult) {
if (video == null) {
Log.e(TAG, "No video");
return;
}
if (master) {
waitTimes.put(video.getName(), Instant.now());
}
Log.d(TAG, String.format("Analysing %s", video.getName()));
EventBus.getDefault().post(new AddEvent(video, Type.PROCESSING));
EventBus.getDefault().post(new RemoveEvent(video, Type.RAW));
String outPath = FileManager.getResultPathOrSegmentResPathFromVideoName(video.getName());
Future<?> future = analysisExecutor.submit(analysisRunnable(video, outPath, returnResult));
analysisFutures.add(future);
}
private Runnable analysisRunnable(Video video, String outPath, boolean returnResult) {
return () -> {
String videoName = video.getName();
if (waitTimes.containsKey(videoName)) {
Instant start = waitTimes.remove(videoName);
String time = TimeManager.getDurationString(start, false);
Log.i(I_TAG, String.format("Wait time of %s: %ss", videoName, time));
} else {
Log.e(TAG, String.format("Could not record wait time of %s", videoName));
}
VideoAnalysis videoAnalysis = video.isInner() ? innerAnalysis : outerAnalysis;
videoAnalysis.analyse(video.getData(), outPath);
Result result = new Result(outPath);
EventBus.getDefault().post(new RemoveEvent(video, Type.PROCESSING));
if (!FfmpegTools.isSegment(result.getName())) {
EventBus.getDefault().post(new AddResultEvent(result));
Instant end = Instant.now();
if (master) {
TimeManager.printTurnaroundTime(videoName, end);
double adjust = VideoAnalysis.getEsdAdjust(videoName, end, isConnected());
if (adjust != 0) {
VideoAnalysis.adjustEsd(adjust);
}
}
}
if (returnResult) {
returnContent(result);
} else if (FfmpegTools.isSegment(result.getName())) {
// Master completed analysing a segment
handleSegment(result.getName(), null);
nextTransfer();
}
PowerMonitor.printBatteryLevel(getContext());
};
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof Listener) {
listener = (Listener) context;
} else {
throw new RuntimeException(context + " must implement NearbyFragment.Listener");
}
}
@Override
public void onDetach() {
super.onDetach();
listener = null;
}
public interface Listener {
void connectEndpoint(Endpoint endpoint);
void disconnectEndpoint(Endpoint endpoint);
void removeEndpoint(Endpoint endpoint);
boolean isConnected();
void addVideo(Video video);
void nextTransfer();
Runnable getSimulateDownloads(int delay, Consumer<Video> downloadCallback, boolean dualDownload);
}
private class ReceiveFilePayloadCallback extends PayloadCallback {
private final SimpleArrayMap<Long, Payload> incomingFilePayloads = new SimpleArrayMap<>();
private final SimpleArrayMap<Long, Payload> completedFilePayloads = new SimpleArrayMap<>();
private final SimpleArrayMap<Long, String> filePayloadFilenames = new SimpleArrayMap<>();
private final SimpleArrayMap<Long, Command> filePayloadCommands = new SimpleArrayMap<>();
private final SimpleArrayMap<Long, Instant> startTimes = new SimpleArrayMap<>();
private final SimpleArrayMap<Long, Long> startPowers = new SimpleArrayMap<>();
private Instant lastUpdate = Instant.now();
private static final int updateInterval = 10;
@Override
public void onPayloadReceived(@NonNull String endpointId, @NonNull Payload payload) {
Log.d(TAG, String.format("onPayloadReceived(endpointId=%s, payload=%s)", endpointId, payload));
if (payload.getType() == Payload.Type.BYTES) {
String message = new String(Objects.requireNonNull(payload.asBytes()), UTF_8);
String[] parts = message.split(MESSAGE_SEPARATOR);
long payloadId;
String videoName;
String videoPath;
Video video;
Endpoint fromEndpoint = discoveredEndpoints.get(endpointId);
if (fromEndpoint == null) {
Log.e(TAG, String.format("Failed to retrieve endpoint %s", endpointId));
return;
}
Context context = getContext();
if (context == null) {
Log.e(TAG, "No context");
return;
}
switch (Command.valueOf(parts[0])) {
case ERROR:
//
break;
case ANALYSE:
case SEGMENT:
Log.v(TAG, String.format("Started downloading %s from %s", message, fromEndpoint));
PowerMonitor.startPowerMonitor(context);
payloadId = addPayloadFilename(parts);
startTimes.put(payloadId, Instant.now());
startPowers.put(payloadId, PowerMonitor.getTotalPowerConsumption());
processFilePayload(payloadId, endpointId);
break;
case RETURN:
videoName = parts[2];
Log.v(TAG, String.format("Started downloading %s from %s", videoName, fromEndpoint));
payloadId = addPayloadFilename(parts);
startTimes.put(payloadId, Instant.now());
startPowers.put(payloadId, PowerMonitor.getTotalPowerConsumption());
fromEndpoint.removeJob(FileManager.getVideoNameFromResultName(videoName));
fromEndpoint.completeCount++;
processFilePayload(payloadId, endpointId);
PowerMonitor.printSummary();
PowerMonitor.printBatteryLevel(getContext());
break;
case COMPLETE:
// requestHardwareInfo(endpointId);
videoName = parts[1];
Log.d(TAG, String.format("%s has finished downloading %s", fromEndpoint, videoName));
if (!FfmpegTools.isSegment(videoName)) {
videoPath = String.format("%s/%s", FileManager.getRawDirPath(), videoName);
video = VideoManager.getVideoFromPath(context, videoPath);
EventBus.getDefault().post(new AddEvent(video, Type.PROCESSING));
EventBus.getDefault().post(new RemoveEvent(video, Type.RAW));
}
nextTransfer();
break;
case HW_INFO:
HardwareInfo hwi = HardwareInfo.fromJson(parts[1]);
Log.i(TAG, String.format("Received hardware information from %s: \n%s", fromEndpoint, hwi));
fromEndpoint.hardwareInfo = hwi;
break;
case HW_INFO_REQUEST:
sendHardwareInfo(context);
break;
case ADJ_ESD:
VideoAnalysis.adjustEsd(Double.parseDouble(parts[1]));
break;
}
} else if (payload.getType() == Payload.Type.FILE) {
// Add this to our tracking map, so that we can retrieve the payload later.
incomingFilePayloads.put(payload.getId(), payload);
}
}
/**
* Extracts the payloadId and filename from the message and stores it in the
* filePayloadFilenames map. The format is command:payloadId:filename
* where ":" is MESSAGE_SEPARATOR.
*/
private long addPayloadFilename(String[] message) {
Command command = Command.valueOf(message[0]);
long payloadId = Long.parseLong(message[1]);
String filename = message[2];
filePayloadFilenames.put(payloadId, filename);
filePayloadCommands.put(payloadId, command);
return payloadId;
}
private void processFilePayload(long payloadId, String fromEndpointId) {
// BYTES and FILE could be received in any order, so we call when either the BYTES or the FILE
// payload is completely received. The file payload is considered complete only when both have
// been received.
Payload filePayload = completedFilePayloads.get(payloadId);
String filename = filePayloadFilenames.get(payloadId);
Command command = filePayloadCommands.get(payloadId);
if (filePayload != null && filename != null && command != null) {
String time;
long power;
if (startTimes.containsKey(payloadId)) {
Instant start = startTimes.remove(payloadId);
time = TimeManager.getDurationString(start);
} else {
Log.e(I_TAG, String.format("Could not record transfer time of %s", filename));
time = "0.000";
}
if (startPowers.containsKey(payloadId)) {
power = PowerMonitor.getPowerConsumption(startPowers.remove(payloadId));
} else {
Log.e(TAG, String.format("Could not record transfer power consumption of %s", filename));
power = 0;
}
Log.i(I_TAG, String.format("Completed downloading %s from %s in %ss, %dnW consumed",
filename, discoveredEndpoints.get(fromEndpointId), time, power));
completedFilePayloads.remove(payloadId);
filePayloadFilenames.remove(payloadId);
filePayloadCommands.remove(payloadId);
if (Message.isAnalyse(command)) {
sendCommandMessage(Command.COMPLETE, filename, fromEndpointId);
}
// Get the received file (which will be in the Downloads folder)
Payload.File payload = filePayload.asFile();
if (payload == null) {
Log.e(I_TAG, String.format("Could not create file payload for %s", filename));
return;
}
//noinspection deprecation
File payloadFile = payload.asJavaFile();
if (payloadFile == null) {
Log.e(I_TAG, String.format("Could not create file payload for %s", filename));
return;
}
if (Message.isAnalyse(command)) {
waitTimes.put(filename, Instant.now());
// Video needs to be in a video directory for it to be scanned on Android version 28 and below
File videoDest = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) ?
new File(payloadFile.getParentFile(), filename) :
new File(FileManager.getRawDirPath(), filename);
boolean rename = payloadFile.renameTo(videoDest);
if (!rename) {
Log.e(I_TAG, String.format("Could not rename %s", filename));
return;
}
MediaScannerConnection.scanFile(getContext(), new String[]{videoDest.getAbsolutePath()}, null,
(path, uri) -> analyse(videoDest));
} else if (command.equals(Command.RETURN)) {
String resultName = FileManager.getResultNameFromVideoName(filename);
String resultsDestPath = FileManager.getResultPathOrSegmentResPathFromVideoName(resultName);
File resultsDest = new File(resultsDestPath);
try {
Files.move(payloadFile.toPath(), resultsDest.toPath(), REPLACE_EXISTING);
} catch (IOException e) {
Log.e(I_TAG, String.format("processFilePayload copy error: \n%s", e.getMessage()));
return;
}
if (FfmpegTools.isSegment(resultName)) {
handleSegment(resultName, fromEndpointId);
} else {
String videoName = FileManager.getVideoNameFromResultName(filename);
Result result = new Result(resultsDestPath);
EventBus.getDefault().post(new AddResultEvent(result));
EventBus.getDefault().post(new RemoveByNameEvent(videoName, Type.PROCESSING));
Instant end = Instant.now();
TimeManager.printTurnaroundTime(videoName, end);
double adjust = VideoAnalysis.getEsdAdjust(videoName, end, isConnected());
if (adjust != 0) {
sendAdjMessage(adjust, fromEndpointId);
}
}
}
}
}
@Override
public void onPayloadTransferUpdate(@NonNull String endpointId, @NonNull PayloadTransferUpdate update) {
if (verbose) {
Instant now = Instant.now();
if (Duration.between(lastUpdate, now).compareTo(Duration.ofSeconds(updateInterval)) > 0) {
lastUpdate = now;
int progress = (int) (100.0 * (update.getBytesTransferred() / (double) update.getTotalBytes()));
Log.v(TAG, String.format("Transfer to %s: %d%%", endpointId, progress));
}
}
if (update.getStatus() == PayloadTransferUpdate.Status.SUCCESS) {
Log.v(TAG, String.format("Transfer to %s complete", discoveredEndpoints.get(endpointId)));
long payloadId = update.getPayloadId();
Payload payload = incomingFilePayloads.remove(payloadId);
completedFilePayloads.put(payloadId, payload);
if (payload != null && payload.getType() == Payload.Type.FILE) {
processFilePayload(payloadId, endpointId);
}
}
}
private void cancelAllPayloads() {
Log.v(TAG, "Cancelling all payloads");
for (int i = 0; i < incomingFilePayloads.size(); i++) {
Long payloadId = incomingFilePayloads.keyAt(i);
connectionsClient.cancelPayload(payloadId);
}
}
}
}
| 47,248 | 42.749074 | 120 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/nearby/Message.java | package com.example.edgedashanalytics.util.nearby;
import com.example.edgedashanalytics.model.Content;
class Message {
final Content content;
final Command command;
Message(Content content, Command command) {
this.content = content;
this.command = command;
}
public enum Command {
ERROR, // Error during transfer
ANALYSE, // Analyse the transferred file
SEGMENT, // Analyse the transferred file as a video segment
COMPLETE, // Completed file transfer
RETURN, // Returning results file
HW_INFO, // Message contains hardware information
HW_INFO_REQUEST, // Requesting hardware information
ADJ_ESD // Adjust ESD
}
static boolean isAnalyse(Command command) {
return (command.equals(Command.ANALYSE) || command.equals(Command.SEGMENT));
}
}
| 861 | 28.724138 | 84 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/nearby/DeviceListAdapter.java | package com.example.edgedashanalytics.util.nearby;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.edgedashanalytics.R;
import java.util.LinkedHashMap;
public class DeviceListAdapter extends RecyclerView.Adapter<DeviceListAdapter.DeviceViewHolder> {
private final NearbyFragment.Listener listener;
private final LinkedHashMap<String, Endpoint> endpoints;
private final LayoutInflater inflater;
DeviceListAdapter(NearbyFragment.Listener listener, Context context, LinkedHashMap<String, Endpoint> endpoints) {
this.listener = listener;
this.inflater = LayoutInflater.from(context);
this.endpoints = endpoints;
}
@NonNull
@Override
public DeviceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = inflater.inflate(R.layout.device_list_item, parent, false);
return new DeviceViewHolder(itemView, this);
}
@Override
public void onBindViewHolder(@NonNull DeviceViewHolder holder, int position) {
Endpoint endpoint = (Endpoint) endpoints.values().toArray()[position];
holder.deviceName.setText(endpoint.name);
holder.deviceName.setClickable(!endpoint.connected);
holder.disconnectButton.setEnabled(endpoint.connected);
holder.removeButton.setEnabled(!endpoint.connected);
if (endpoint.connected) {
holder.connectionStatus.setImageResource(R.drawable.status_connected);
holder.disconnectButton.clearColorFilter();
holder.removeButton.setColorFilter(Color.LTGRAY);
} else {
holder.connectionStatus.setImageResource(R.drawable.status_disconnected);
holder.disconnectButton.setColorFilter(Color.LTGRAY);
holder.removeButton.clearColorFilter();
}
holder.deviceName.setOnClickListener(v -> {
if (!endpoint.connected) {
Toast.makeText(v.getContext(), String.format("Connecting to %s", endpoint.name), Toast.LENGTH_LONG).show();
listener.connectEndpoint(endpoint);
}
});
holder.disconnectButton.setOnClickListener(v -> listener.disconnectEndpoint(endpoint));
holder.removeButton.setOnClickListener(v -> listener.removeEndpoint(endpoint));
}
@Override
public int getItemCount() {
return endpoints.size();
}
static class DeviceViewHolder extends RecyclerView.ViewHolder {
@SuppressWarnings({"FieldCanBeLocal", "unused"})
private final DeviceListAdapter adapter;
private final TextView deviceName;
private final ImageView connectionStatus;
private final ImageView disconnectButton;
private final ImageView removeButton;
private DeviceViewHolder(View itemView, DeviceListAdapter adapter) {
super(itemView);
this.adapter = adapter;
this.deviceName = itemView.findViewById(R.id.device_item_text);
this.connectionStatus = itemView.findViewById(R.id.connection_status);
this.disconnectButton = itemView.findViewById(R.id.disconnect_button);
this.removeButton = itemView.findViewById(R.id.remove_device_button);
}
}
}
| 3,528 | 38.651685 | 123 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/VideoDetailsLookup.java | package com.example.edgedashanalytics.util.video;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.widget.RecyclerView;
import com.example.edgedashanalytics.page.adapter.VideoRecyclerViewAdapter;
public class VideoDetailsLookup extends ItemDetailsLookup<Long> {
private final RecyclerView recyclerView;
public VideoDetailsLookup(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
}
@Nullable
@Override
public ItemDetails<Long> getItemDetails(@NonNull MotionEvent e) {
View view = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(view);
if (holder instanceof VideoRecyclerViewAdapter.VideoViewHolder) {
return ((VideoRecyclerViewAdapter.VideoViewHolder) holder).getItemDetails();
}
}
return null;
}
}
| 1,098 | 31.323529 | 92 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/FfmpegTools.java | package com.example.edgedashanalytics.util.video;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.arthenica.ffmpegkit.FFmpegKit;
import com.arthenica.ffmpegkit.FFprobeKit;
import com.arthenica.ffmpegkit.MediaInformation;
import com.arthenica.ffmpegkit.MediaInformationSession;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.util.file.FileManager;
import org.apache.commons.io.FilenameUtils;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
public class FfmpegTools {
private static final String TAG = FfmpegTools.class.getSimpleName();
private static final char SEGMENT_SEPARATOR = '!';
private static Double duration = null;
private static void executeFfmpeg(ArrayList<String> ffmpegArgs) {
Log.i(TAG, String.format("Running ffmpeg with:\n %s", TextUtils.join(" ", ffmpegArgs)));
FFmpegKit.executeWithArguments(ffmpegArgs.toArray(new String[0]));
}
public static void setDuration(String filePath) {
// Assume that all videos are of equal length, only need to set once
if (duration != null) {
return;
}
Log.v(TAG, String.format("Retrieving duration of %s", filePath));
MediaInformationSession session = FFprobeKit.getMediaInformation(filePath);
MediaInformation info = session.getMediaInformation();
String durationString = info.getDuration();
try {
duration = Double.parseDouble(durationString);
} catch (NumberFormatException e) {
Log.e(I_TAG, String.format("ffmpeg-mobile error, could not retrieve duration of %s:\n%s",
filePath, e.getMessage()));
}
}
private static double getDuration() {
return duration;
}
public static long getDurationMillis() {
return Math.round(duration * 1000);
}
// Get base video name from split segment's name
public static String getBaseName(String segmentName) {
String baseFileName = FilenameUtils.getBaseName(segmentName);
String[] components = baseFileName.split(String.format("%c", SEGMENT_SEPARATOR));
if (components.length > 0) {
return components[0];
} else {
return baseFileName;
}
}
public static int getSegmentCount(String segmentName) {
String baseName = FilenameUtils.getBaseName(segmentName);
String[] components = baseName.split(String.format("%c", SEGMENT_SEPARATOR));
if (components.length < 1) {
return -1;
}
String countString = components[components.length - 1];
if (countString == null) {
return -1;
}
return Integer.parseInt(countString);
}
public static boolean isSegment(String filename) {
return filename.contains(String.format("%c", SEGMENT_SEPARATOR));
}
public static List<Video> splitAndReturn(Context context, String filePath, int segNum) {
String baseName = FilenameUtils.getBaseName(filePath);
if (segNum < 2) {
Log.d(TAG, String.format("Segment number (%d) too low, returning whole video %s", segNum, baseName));
return new ArrayList<>(Collections.singletonList(VideoManager.getVideoFromPath(context, filePath)));
}
splitVideo(filePath, segNum);
String segmentDirPath = FileManager.getSegmentDirPath(baseName);
List<Video> segments = VideoManager.getVideosFromDir(context, segmentDirPath);
if (segments == null) {
Log.e(I_TAG, String.format("Failed to split video, returning whole video %s", baseName));
return new ArrayList<>(Collections.singletonList(VideoManager.getVideoFromPath(context, filePath)));
}
return VideoManager.getVideosFromDir(context, segmentDirPath);
}
// Segment filename format is "baseName!segIndex!segTotal.ext"
private static void splitVideo(String filePath, int segNum) {
if (segNum < 2) {
return;
}
String baseName = FilenameUtils.getBaseName(filePath);
setDuration(filePath);
double segTime = getDuration() / segNum;
// Round segment time up to ensure that the number of split videos doesn't exceed segNum
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.CEILING);
String segTimeString = df.format(segTime);
String outDir = FileManager.getSegmentDirPath(baseName);
Log.v(TAG, String.format("Splitting %s with %ss long segments", filePath, segTimeString));
ArrayList<String> ffmpegArgs = new ArrayList<>(Arrays.asList(
"-y",
"-i", filePath,
"-map", "0",
"-c", "copy",
"-f", "segment",
"-reset_timestamps", "1",
"-g", "0",
"-segment_time", segTimeString,
String.format(Locale.ENGLISH, "%s/%s%c%%03d%c%d.%s",
outDir,
baseName,
SEGMENT_SEPARATOR,
SEGMENT_SEPARATOR,
segNum,
FilenameUtils.getExtension(filePath)
)
));
executeFfmpeg(ffmpegArgs);
}
}
| 5,571 | 35.418301 | 113 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/VideoManager.java | package com.example.edgedashanalytics.util.video;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.util.file.DeviceExternalStorage;
import com.example.edgedashanalytics.util.file.FileManager;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class VideoManager {
private final static String TAG = VideoManager.class.getSimpleName();
private final static String MIME_TYPE = "video/mp4";
private VideoManager() {
}
public static List<Video> getAllVideoFromExternalStorageFolder(Context context, File file) {
Log.v(TAG, "getAllVideoFromExternalStorageFolder");
String[] projection = {
Media._ID,
Media.DATA,
Media.DISPLAY_NAME,
Media.SIZE,
Media.MIME_TYPE
};
if (DeviceExternalStorage.externalStorageIsReadable()) {
String selection = Media.DATA + " LIKE ? ";
String[] selectArgs = new String[]{"%" + file.getAbsolutePath() + "%"};
Log.d("VideoManager", file.getAbsolutePath());
return getVideosFromExternalStorage(context, projection, selection, selectArgs, Media.DEFAULT_SORT_ORDER);
}
return new ArrayList<>();
}
static List<Video> getVideosFromDir(Context context, String dirPath) {
File dir = new File(dirPath);
return getVideosFromDir(context, dir);
}
private static List<Video> getVideosFromDir(Context context, File dir) {
if (!dir.isDirectory()) {
Log.e(TAG, String.format("%s is not a directory", dir.getAbsolutePath()));
return null;
}
Log.v(TAG, String.format("Retrieving videos from %s", dir.getAbsolutePath()));
File[] videoFiles = dir.listFiles();
if (videoFiles == null) {
Log.e(TAG, String.format("Could not access contents of %s", dir.getAbsolutePath()));
return null;
}
List<String> vidPaths = Arrays.stream(videoFiles)
.map(File::getAbsolutePath).filter(FileManager::isMp4).collect(Collectors.toList());
List<Video> videos = new ArrayList<>();
for (String vidPath : vidPaths) {
videos.add(getVideoFromPath(context, vidPath));
}
return videos;
}
private static Video getVideoFromFile(Context context, File file) {
if (file == null) {
Log.e(TAG, "Null file");
return null;
}
String[] projection = {
Files.FileColumns._ID,
Files.FileColumns.DATA,
Files.FileColumns.DISPLAY_NAME,
Files.FileColumns.SIZE,
Files.FileColumns.MIME_TYPE
};
String selection = Files.FileColumns.DATA + "=?";
String[] selectionArgs = new String[]{file.getAbsolutePath()};
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
uri = Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
uri = Media.EXTERNAL_CONTENT_URI;
}
Cursor videoCursor = context.getContentResolver().query(
uri, projection, selection, selectionArgs, Media.DEFAULT_SORT_ORDER);
if (videoCursor == null || !videoCursor.moveToFirst()) {
// Log.d(TAG, "videoCursor is null");
return null;
}
Video video = videoFromCursor(videoCursor);
videoCursor.close();
if (video == null) {
Log.v(TAG, String.format("Video (%s) is null", file.getAbsolutePath()));
}
return video;
}
public static Video getVideoFromPath(Context context, String path) {
Log.v(TAG, String.format("Retrieving video from %s", path));
Video video = getVideoFromFile(context, new File(path));
if (video != null) {
return video;
} else {
Uri uri;
ContentValues values = new ContentValues();
values.put(Files.FileColumns.TITLE, FilenameUtils.getBaseName(path));
values.put(Files.FileColumns.MIME_TYPE, MIME_TYPE);
values.put(Files.FileColumns.DISPLAY_NAME, "player");
values.put(Files.FileColumns.DATE_ADDED, System.currentTimeMillis());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(Files.FileColumns.DATE_TAKEN, System.currentTimeMillis());
uri = Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
uri = Media.EXTERNAL_CONTENT_URI;
}
values.put(Files.FileColumns.DATA, path);
context.getContentResolver().insert(uri, values);
return getVideoFromFile(context, new File(path));
}
}
public static List<Video> getAllVideosFromExternalStorage(Context context, String[] projection) {
Log.v(TAG, "getAllVideosFromExternalStorage");
if (DeviceExternalStorage.externalStorageIsReadable()) {
return getVideosFromExternalStorage(context, projection, null, null, null);
}
return new ArrayList<>();
}
private static List<Video> getVideosFromExternalStorage(Context context, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
Cursor videoCursor = context.getContentResolver().query(Media.EXTERNAL_CONTENT_URI,
projection, selection, selectionArgs, sortOrder);
if (videoCursor != null) {
List<Video> videos = new ArrayList<>(videoCursor.getCount());
getVideosFromCursor(videoCursor, videos);
videoCursor.close();
Log.d(TAG, String.format("%d videos return", videos.size()));
return videos;
} else {
return null;
}
}
private static void getVideosFromCursor(Cursor videoCursor, List<Video> videos) {
boolean cursorIsNotEmpty = videoCursor.moveToFirst();
if (cursorIsNotEmpty) {
do {
Video video = videoFromCursor(videoCursor);
if (video != null) {
videos.add(video);
Log.d(TAG, video.toString());
} else {
Log.w(TAG, "Video is null");
}
} while (videoCursor.moveToNext());
}
}
private static Video videoFromCursor(Cursor cursor) {
Video video = null;
try {
int idIndex = cursor.getColumnIndex(Files.FileColumns._ID);
int nameIndex = cursor.getColumnIndex(Files.FileColumns.DISPLAY_NAME);
int dataIndex = cursor.getColumnIndex(Files.FileColumns.DATA);
int sizeIndex = cursor.getColumnIndex(Files.FileColumns.SIZE);
if (idIndex < 0 || nameIndex < 0 || dataIndex < 0 || sizeIndex < 0) {
Log.w(TAG, "videoFromCursor error: index is below zero");
return null;
}
String id = cursor.getString(idIndex);
String name = cursor.getString(nameIndex);
String data = cursor.getString(dataIndex);
BigInteger size;
try {
String sizeString = cursor.getString(sizeIndex);
size = new BigInteger(sizeString);
} catch (NullPointerException e) {
Log.w(TAG, "videoFromCursor error: Could not retrieve video file size, setting to zero");
size = new BigInteger("0");
}
video = new Video(id, name, data, MIME_TYPE, size);
} catch (Exception e) {
Log.w(TAG, String.format("videoFromCursor error: \n%s", e.getMessage()));
}
return video;
}
}
| 8,244 | 37.171296 | 118 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/eventhandler/VideoEventHandler.java | package com.example.edgedashanalytics.util.video.eventhandler;
import com.example.edgedashanalytics.event.video.AddEvent;
import com.example.edgedashanalytics.event.video.RemoveEvent;
public interface VideoEventHandler {
void onAdd(AddEvent event);
void onRemove(RemoveEvent event);
}
| 296 | 26 | 62 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/eventhandler/RawVideosEventHandler.java | package com.example.edgedashanalytics.util.video.eventhandler;
import android.util.Log;
import com.example.edgedashanalytics.data.video.VideosRepository;
import com.example.edgedashanalytics.event.video.AddEvent;
import com.example.edgedashanalytics.event.video.RemoveByNameEvent;
import com.example.edgedashanalytics.event.video.RemoveEvent;
import com.example.edgedashanalytics.event.video.Type;
import com.example.edgedashanalytics.event.video.VideoEvent;
import com.example.edgedashanalytics.util.file.FileManager;
import org.greenrobot.eventbus.Subscribe;
public class RawVideosEventHandler implements VideoEventHandler {
private static final String TAG = RawVideosEventHandler.class.getSimpleName();
private final VideosRepository repository;
public RawVideosEventHandler(VideosRepository repository) {
this.repository = repository;
}
@Subscribe
@Override
public void onAdd(AddEvent event) {
nullCheck(event);
if (event.type == Type.RAW) {
try {
repository.insert(event.video);
} catch (Exception e) {
Log.e(TAG, String.format("onAdd error: \n%s", e.getMessage()));
}
}
}
@Subscribe
@Override
public void onRemove(RemoveEvent event) {
nullCheck(event);
if (event.type == Type.RAW) {
try {
repository.delete(event.video.getData());
} catch (Exception e) {
Log.e(TAG, String.format("onRemove error: \n%s", e.getMessage()));
}
}
}
@Subscribe
public void onRemoveByName(RemoveByNameEvent event) {
if (event == null) {
Log.e(TAG, "Null event");
return;
}
if (repository == null) {
Log.e(TAG, "Null repository");
return;
}
if (event.name == null) {
Log.e(TAG, "Null name");
}
if (event.type == Type.RAW) {
try {
String path = String.format("%s/%s", FileManager.getRawDirPath(), event.name);
repository.delete(path);
} catch (Exception e) {
Log.e(TAG, String.format("removeByName error: \n%s", e.getMessage()));
}
}
}
private void nullCheck(VideoEvent event) {
if (event == null) {
Log.e(TAG, "Null event");
return;
}
if (repository == null) {
Log.e(TAG, "Null repository");
return;
}
if (event.video == null) {
Log.e(TAG, "Null video");
}
}
}
| 2,631 | 28.573034 | 94 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/eventhandler/ProcessingVideosEventHandler.java | package com.example.edgedashanalytics.util.video.eventhandler;
import android.util.Log;
import com.example.edgedashanalytics.data.video.VideosRepository;
import com.example.edgedashanalytics.event.video.AddEvent;
import com.example.edgedashanalytics.event.video.RemoveByNameEvent;
import com.example.edgedashanalytics.event.video.RemoveEvent;
import com.example.edgedashanalytics.event.video.Type;
import com.example.edgedashanalytics.event.video.VideoEvent;
import com.example.edgedashanalytics.util.file.FileManager;
import org.greenrobot.eventbus.Subscribe;
public class ProcessingVideosEventHandler implements VideoEventHandler {
private static final String TAG = ProcessingVideosEventHandler.class.getSimpleName();
private final VideosRepository repository;
public ProcessingVideosEventHandler(VideosRepository repository) {
this.repository = repository;
}
@Subscribe
@Override
public void onAdd(AddEvent event) {
nullCheck(event);
if (event.type == Type.PROCESSING) {
try {
repository.insert(event.video);
} catch (Exception e) {
Log.e(TAG, String.format("onAdd error: \n%s", e.getMessage()));
}
}
}
@Subscribe
@Override
public void onRemove(RemoveEvent event) {
nullCheck(event);
if (event.type == Type.PROCESSING) {
try {
repository.delete(event.video.getData());
} catch (Exception e) {
Log.e(TAG, String.format("onRemove error: \n%s", e.getMessage()));
}
}
}
@Subscribe
public void onRemoveByName(RemoveByNameEvent event) {
if (event == null) {
Log.e(TAG, "Null event");
return;
}
if (repository == null) {
Log.e(TAG, "Null repository");
return;
}
if (event.name == null) {
Log.e(TAG, "Null name");
}
if (event.type == Type.PROCESSING) {
try {
String path = String.format("%s/%s", FileManager.getRawDirPath(), event.name);
repository.delete(path);
} catch (Exception e) {
Log.e(TAG, String.format("removeByName error: \n%s", e.getMessage()));
}
}
}
private void nullCheck(VideoEvent event) {
if (event == null) {
Log.e(TAG, "Null event");
return;
}
if (repository == null) {
Log.e(TAG, "Null repository");
return;
}
if (event.video == null) {
Log.e(TAG, "Null video");
}
}
}
| 2,673 | 29.044944 | 94 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/eventhandler/ResultEventHandler.java | package com.example.edgedashanalytics.util.video.eventhandler;
import android.util.Log;
import com.example.edgedashanalytics.data.result.ResultRepository;
import com.example.edgedashanalytics.event.result.AddResultEvent;
import com.example.edgedashanalytics.event.result.RemoveResultEvent;
import com.example.edgedashanalytics.event.result.ResultEvent;
import org.greenrobot.eventbus.Subscribe;
public class ResultEventHandler {
private static final String TAG = ResultEventHandler.class.getSimpleName();
private final ResultRepository repository;
public ResultEventHandler(ResultRepository repository) {
this.repository = repository;
}
@Subscribe
public void onAdd(AddResultEvent event) {
nullCheck(event);
try {
repository.insert(event.result);
} catch (Exception e) {
Log.e(TAG, String.format("onAdd error: \n%s", e.getMessage()));
}
}
@Subscribe
public void onRemove(RemoveResultEvent event) {
nullCheck(event);
try {
repository.delete(event.result.getData());
} catch (Exception e) {
Log.e(TAG, String.format("onRemove error: \n%s", e.getMessage()));
}
}
private void nullCheck(ResultEvent event) {
if (event == null) {
Log.e(TAG, "Null event");
return;
}
if (repository == null) {
Log.e(TAG, "Null repository");
return;
}
if (event.result == null) {
Log.e(TAG, "Null result");
}
}
}
| 1,575 | 27.142857 | 79 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/Frame.java | package com.example.edgedashanalytics.util.video.analysis;
@SuppressWarnings({"unused"})
public abstract class Frame {
public int frame;
}
| 144 | 19.714286 | 58 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/Hazard.java | package com.example.edgedashanalytics.util.video.analysis;
import android.graphics.Rect;
import androidx.annotation.NonNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
class Hazard {
private final String category;
private final float score;
private final boolean danger;
private final Rect bBox;
@JsonCreator
Hazard(@JsonProperty("category") String category,
@JsonProperty("score") float score,
@JsonProperty("danger") boolean danger,
@JsonProperty("bBox") Rect bBox) {
this.category = category;
this.score = score;
this.danger = danger;
this.bBox = bBox;
}
@NonNull
@Override
public String toString() {
return "Hazard{" +
"category='" + category + '\'' +
", score=" + score +
", danger=" + danger +
", bBox=" + bBox +
'}';
}
}
| 995 | 25.210526 | 58 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/BodyPart.java | package com.example.edgedashanalytics.util.video.analysis;
// https://github.com/tensorflow/examples/blob/master/lite/examples/pose_estimation/android/app/src/main/java/org/tensorflow/lite/examples/poseestimation/data/BodyPart.kt
public enum BodyPart {
NOSE,
LEFT_EYE,
RIGHT_EYE,
LEFT_EAR,
RIGHT_EAR,
LEFT_SHOULDER,
RIGHT_SHOULDER,
LEFT_ELBOW,
RIGHT_ELBOW,
LEFT_WRIST,
RIGHT_WRIST,
LEFT_HIP,
RIGHT_HIP,
LEFT_KNEE,
RIGHT_KNEE,
LEFT_ANKLE,
RIGHT_ANKLE;
public static final BodyPart[] AS_ARRAY = BodyPart.values();
public static final int LOWER_INDEX = LEFT_HIP.ordinal();
}
| 650 | 24.038462 | 170 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/OuterFrame.java | package com.example.edgedashanalytics.util.video.analysis;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@SuppressWarnings({"FieldCanBeLocal", "unused"})
public class OuterFrame extends Frame {
private final List<Hazard> hazards;
@JsonCreator
OuterFrame(@JsonProperty("frame") int frame, @JsonProperty("hazards") List<Hazard> hazards) {
this.frame = frame;
this.hazards = hazards;
}
}
| 505 | 27.111111 | 97 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/InnerFrame.java | package com.example.edgedashanalytics.util.video.analysis;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@SuppressWarnings({"FieldCanBeLocal", "unused"})
public class InnerFrame extends Frame {
private final boolean distracted;
private final float fullScore;
private final List<KeyPoint> keyPoints;
@JsonCreator
InnerFrame(@JsonProperty("frame") int frame,
@JsonProperty("distracted") boolean distracted,
@JsonProperty("fullScore") float fullScore,
@JsonProperty("keyPoints") List<KeyPoint> keyPoints) {
this.frame = frame;
this.distracted = distracted;
this.fullScore = fullScore;
this.keyPoints = keyPoints;
}
}
| 803 | 31.16 | 69 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/AnalysisTools.java | package com.example.edgedashanalytics.util.video.analysis;
import android.content.Context;
import android.util.Log;
import com.example.edgedashanalytics.event.result.AddResultEvent;
import com.example.edgedashanalytics.event.video.AddEvent;
import com.example.edgedashanalytics.event.video.RemoveEvent;
import com.example.edgedashanalytics.event.video.Type;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.util.file.FileManager;
import org.greenrobot.eventbus.EventBus;
import java.util.LinkedHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class AnalysisTools {
private final static String TAG = AnalysisTools.class.getSimpleName();
private final static ExecutorService executor = Executors.newSingleThreadExecutor();
private final static LinkedHashMap<String, Future<?>> analysisFutures = new LinkedHashMap<>();
private static InnerAnalysis innerAnalysis = null;
private static OuterAnalysis outerAnalysis = null;
public static void processVideo(Video video, Context context) {
Log.d(TAG, String.format("Analysing %s", video.getName()));
if (innerAnalysis == null || outerAnalysis == null) {
innerAnalysis = new InnerAnalysis(context);
outerAnalysis = new OuterAnalysis(context);
}
final String output = FileManager.getResultPathFromVideoName(video.getName());
Future<?> future = executor.submit(processRunnable(video, output));
analysisFutures.put(video.getData(), future);
EventBus.getDefault().post(new AddEvent(video, Type.PROCESSING));
EventBus.getDefault().post(new RemoveEvent(video, Type.RAW));
}
private static Runnable processRunnable(Video video, String outPath) {
return () -> {
VideoAnalysis videoAnalysis = video.isInner() ? innerAnalysis : outerAnalysis;
videoAnalysis.analyse(video.getData(), outPath);
analysisFutures.remove(video.getData());
Result result = new Result(outPath);
EventBus.getDefault().post(new AddResultEvent(result));
EventBus.getDefault().post(new RemoveEvent(video, Type.PROCESSING));
};
}
public static void cancelProcess(String videoPath) {
Future<?> future = analysisFutures.remove(videoPath);
if (future != null) {
Log.i(TAG, String.format("Cancelling processing of %s", videoPath));
future.cancel(false);
} else {
Log.e(TAG, String.format("Cannot cancel processing of %s", videoPath));
}
}
}
| 2,719 | 37.309859 | 98 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/KeyPoint.java | package com.example.edgedashanalytics.util.video.analysis;
import android.graphics.PointF;
import androidx.annotation.NonNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
// https://github.com/tensorflow/examples/blob/master/lite/examples/pose_estimation/android/app/src/main/java/org/tensorflow/lite/examples/poseestimation/data/KeyPoint.kt
class KeyPoint {
final BodyPart bodyPart;
final float score;
PointF coordinate;
@JsonCreator
KeyPoint(@JsonProperty("bodyPart") BodyPart bodyPart,
@JsonProperty("coordinate") PointF coordinate,
@JsonProperty("score") float score) {
this.bodyPart = bodyPart;
this.score = score;
this.coordinate = coordinate;
}
@NonNull
@Override
public String toString() {
return "KeyPoint{" +
"bodyPart=" + bodyPart +
", score=" + score +
", coordinate=" + coordinate +
'}';
}
}
| 1,036 | 28.628571 | 170 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/OuterAnalysis.java | package com.example.edgedashanalytics.util.video.analysis;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.R;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.support.common.FileUtil;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.label.Category;
import org.tensorflow.lite.task.core.BaseOptions;
import org.tensorflow.lite.task.vision.detector.Detection;
import org.tensorflow.lite.task.vision.detector.ObjectDetector;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.StringJoiner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
// https://www.tensorflow.org/lite/models/object_detection/overview
// https://tfhub.dev/tensorflow/collections/lite/task-library/object-detector/1
// https://www.tensorflow.org/lite/performance/best_practices
// https://www.tensorflow.org/lite/guide/android
// https://www.tensorflow.org/lite/inference_with_metadata/task_library/object_detector
// https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/running_on_mobile_tf2.md
public class OuterAnalysis extends VideoAnalysis {
private static final String TAG = OuterAnalysis.class.getSimpleName();
// Different models have different maximum detection limits
// MobileNet's is 10, EfficientDet's is 25
private static final int MAX_DETECTIONS = -1;
private static final float MIN_SCORE = 0.2f;
private static int inputSize;
private static final BlockingQueue<ObjectDetector> detectorQueue = new LinkedBlockingQueue<>(THREAD_NUM);
// Include or exclude bicycles?
private static final ArrayList<String> vehicleCategories = new ArrayList<>(Arrays.asList(
"bicycle", "car", "motorcycle", "bus", "truck"
));
public OuterAnalysis(Context context) {
super(context);
if (!detectorQueue.isEmpty()) {
return;
}
String defaultModel = context.getString(R.string.default_object_model_key);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String modelFilename = pref.getString(context.getString(R.string.object_model_key), defaultModel);
BaseOptions baseOptions;
if (modelFilename.equals(defaultModel)) {
baseOptions = BaseOptions.builder().setNumThreads(TF_THREAD_NUM).useNnapi().build();
} else {
baseOptions = BaseOptions.builder().setNumThreads(TF_THREAD_NUM).build();
}
ObjectDetector.ObjectDetectorOptions objectDetectorOptions = ObjectDetector.ObjectDetectorOptions.builder()
.setBaseOptions(baseOptions)
.setMaxResults(MAX_DETECTIONS)
.setScoreThreshold(MIN_SCORE)
.build();
try (Interpreter interpreter = new Interpreter(FileUtil.loadMappedFile(context, modelFilename))) {
inputSize = interpreter.getInputTensor(0).shape()[1];
} catch (IOException e) {
Log.w(I_TAG, String.format("Model failure:\n %s", e.getMessage()));
}
for (int i = 0; i < THREAD_NUM; i++) {
try {
detectorQueue.add(ObjectDetector.createFromFileAndOptions(
context, modelFilename, objectDetectorOptions));
} catch (IOException e) {
Log.w(I_TAG, String.format("Model failure:\n %s", e.getMessage()));
}
}
}
OuterFrame processFrame(Bitmap bitmap, int frameIndex, float scaleFactor) {
ObjectDetector detector;
try {
detector = detectorQueue.poll(200, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.w(I_TAG, String.format("Cannot acquire detector for frame %s:\n %s", frameIndex, e.getMessage()));
return null;
}
if (detector == null) {
Log.w(I_TAG, String.format("Detector for frame %s is null", frameIndex));
return null;
}
List<Detection> detectionList = detector.detect(TensorImage.fromBitmap(bitmap));
try {
detectorQueue.put(detector);
} catch (InterruptedException e) {
Log.w(TAG, String.format("Unable to return detector to queue:\n %s", e.getMessage()));
}
List<Hazard> hazards = new ArrayList<>(detectionList.size());
for (Detection detection : detectionList) {
List<Category> categoryList = detection.getCategories();
if (categoryList == null || categoryList.size() == 0) {
continue;
}
Category category = categoryList.get(0);
RectF detBox = detection.getBoundingBox();
Rect boundingBox = new Rect(
(int) (detBox.left * scaleFactor),
(int) (detBox.top * scaleFactor),
(int) (detBox.right * scaleFactor),
(int) (detBox.bottom * scaleFactor)
);
int origWidth = (int) (bitmap.getWidth() * scaleFactor);
int origHeight = (int) (bitmap.getHeight() * scaleFactor);
hazards.add(new Hazard(
category.getLabel(),
category.getScore(),
isDanger(boundingBox, category.getLabel(), origWidth, origHeight),
boundingBox
));
}
if (verbose) {
String resultHead = String.format(
Locale.ENGLISH,
"Analysis completed for frame: %04d\nDetected hazards: %02d\n",
frameIndex, hazards.size()
);
StringBuilder builder = new StringBuilder(resultHead);
for (Hazard hazard : hazards) {
builder.append(" ");
builder.append(hazard.toString());
}
builder.append('\n');
String resultMessage = builder.toString();
Log.v(TAG, resultMessage);
}
return new OuterFrame(frameIndex, hazards);
}
private boolean isDanger(Rect boundingBox, String category, int imageWidth, int imageHeight) {
if (vehicleCategories.contains(category)) {
// Check tailgating
Rect tailgateZone = getTailgateZone(imageWidth, imageHeight);
return tailgateZone.contains(boundingBox) || tailgateZone.intersect(boundingBox);
} else {
// Check obstruction
Rect dangerZone = getDangerZone(imageWidth, imageHeight);
return dangerZone.contains(boundingBox) || dangerZone.intersect(boundingBox);
}
}
private Rect getDangerZone(int imageWidth, int imageHeight) {
int dangerLeft = imageWidth / 4;
int dangerRight = (imageWidth / 4) * 3;
int dangerTop = (imageHeight / 10) * 4;
return new Rect(dangerLeft, dangerTop, dangerRight, imageHeight);
}
private Rect getTailgateZone(int imageWidth, int imageHeight) {
int tailLeft = imageWidth / 3;
int tailRight = (imageWidth / 3) * 2;
int tailTop = (imageHeight / 4) * 3;
// Exclude driving car's bonnet, assuming it always occupies the same space
// Realistically, due to dash cam position/angle, bonnets will occupy differing proportion of the video
int tailBottom = imageHeight - imageHeight / 10;
return new Rect(tailLeft, tailTop, tailRight, tailBottom);
}
void setup(int width, int height) {
// Doesn't need setup
}
float getScaleFactor(int width) {
return width / (float) inputSize;
}
public void printParameters() {
StringJoiner paramMessage = new StringJoiner("\n ");
paramMessage.add("Outer analysis parameters:");
paramMessage.add(String.format("MAX_DETECTIONS: %s", MAX_DETECTIONS));
paramMessage.add(String.format("MIN_SCORE: %s", MIN_SCORE));
paramMessage.add(String.format("TensorFlow Threads: %s", TF_THREAD_NUM));
paramMessage.add(String.format("Analysis Threads: %s", THREAD_NUM));
Log.i(I_TAG, paramMessage.toString());
}
}
| 8,556 | 37.895455 | 115 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/InnerAnalysis.java | package com.example.edgedashanalytics.util.video.analysis;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.Log;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.R;
import org.apache.commons.lang3.ArrayUtils;
import org.tensorflow.lite.DataType;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.support.common.FileUtil;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.image.ops.ResizeOp;
import org.tensorflow.lite.support.image.ops.ResizeWithCropOrPadOp;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
// https://www.tensorflow.org/lite/examples/pose_estimation/overview
// https://www.tensorflow.org/lite/tutorials/pose_classification
// https://github.com/tensorflow/examples/tree/master/lite/examples/pose_estimation/android
// https://github.com/tensorflow/examples/blob/master/lite/examples/pose_estimation/android/app/src/main/java/org/tensorflow/lite/examples/poseestimation/ml/MoveNet.kt
public class InnerAnalysis extends VideoAnalysis {
private static final String TAG = InnerAnalysis.class.getSimpleName();
private static final float MIN_SCORE = 0.2f;
private static int inputWidth;
private static int inputHeight;
private static int[] outputShape;
private static RectF cropRegion;
private static final BlockingQueue<Interpreter> interpreterQueue = new LinkedBlockingQueue<>(THREAD_NUM);
private static final BlockingQueue<ImageProcessor> processorQueue = new LinkedBlockingQueue<>(THREAD_NUM);
public InnerAnalysis(Context context) {
super(context);
if (!interpreterQueue.isEmpty()) {
return;
}
String defaultModel = context.getString(R.string.default_pose_model_key);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
String modelFilename = pref.getString(context.getString(R.string.pose_model_key), defaultModel);
Interpreter.Options options = new Interpreter.Options();
options.setUseXNNPACK(true);
options.setNumThreads(TF_THREAD_NUM);
for (int i = 0; i < THREAD_NUM; i++) {
try {
interpreterQueue.add(new Interpreter(FileUtil.loadMappedFile(context, modelFilename), options));
} catch (IOException e) {
Log.w(I_TAG, String.format("Model failure:\n %s", e.getMessage()));
}
}
try (Interpreter interpreter = interpreterQueue.peek()) {
if (interpreter != null) {
inputWidth = interpreter.getInputTensor(0).shape()[1];
inputHeight = interpreter.getInputTensor(0).shape()[2];
outputShape = interpreter.getOutputTensor(0).shape();
}
}
}
InnerFrame processFrame(Bitmap bitmap, int frameIndex, float scaleFactor) {
float totalScore = 0;
int numKeyPoints = outputShape[2];
RectF rect = new RectF(
cropRegion.left * bitmap.getWidth(),
cropRegion.top * bitmap.getHeight(),
cropRegion.right * bitmap.getWidth(),
cropRegion.bottom * bitmap.getHeight()
);
Bitmap detectBitmap = Bitmap.createBitmap((int) rect.width(), (int) rect.height(),
Bitmap.Config.ARGB_8888);
// Might just be for visualisation, may be unnecessary
Canvas canvas = new Canvas(detectBitmap);
canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);
ImageProcessor imageProcessor;
try {
imageProcessor = processorQueue.poll(200, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.w(I_TAG, String.format("Cannot acquire processor for frame %s:\n %s", frameIndex, e.getMessage()));
return null;
}
if (imageProcessor == null) {
Log.w(I_TAG, String.format("Processor for frame %s is null", frameIndex));
return null;
}
TensorImage inputTensor = imageProcessor.process(TensorImage.fromBitmap(bitmap));
try {
processorQueue.put(imageProcessor);
} catch (InterruptedException e) {
Log.w(TAG, String.format("Unable to return processor to queue:\n %s", e.getMessage()));
}
TensorBuffer outputTensor = TensorBuffer.createFixedSize(outputShape, DataType.FLOAT32);
float widthRatio = detectBitmap.getWidth() / (float) inputWidth;
float heightRatio = detectBitmap.getHeight() / (float) inputHeight;
Interpreter interpreter;
try {
interpreter = interpreterQueue.poll(200, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.w(I_TAG, String.format("Cannot acquire interpreter for frame %s:\n %s", frameIndex, e.getMessage()));
return null;
}
if (interpreter == null) {
Log.w(I_TAG, String.format("Interpreter for frame %s is null", frameIndex));
return null;
}
interpreter.run(inputTensor.getBuffer(), outputTensor.getBuffer().rewind());
try {
interpreterQueue.put(interpreter);
} catch (InterruptedException e) {
Log.w(TAG, String.format("Unable to return interpreter to queue:\n %s", e.getMessage()));
}
float[] output = outputTensor.getFloatArray();
List<Float> positions = new ArrayList<>();
List<KeyPoint> keyPoints = new ArrayList<>();
// Don't bother keeping results for keyPoints of lower body parts,
// lower body part indexes start at BodyPart.LOWER_INDEX
for (int a = 0; a < numKeyPoints && a < BodyPart.LOWER_INDEX; a++) {
float x = output[a * 3 + 1] * inputWidth * widthRatio;
float y = output[a * 3] * inputHeight * heightRatio;
positions.add(x);
positions.add(y);
float score = output[a * 3 + 2];
keyPoints.add(new KeyPoint(BodyPart.AS_ARRAY[a], new PointF(x, y), score));
totalScore += score;
}
// Adjust keypoint coordinates to align with original bitmap dimensions
Matrix matrix = new Matrix();
float[] points = ArrayUtils.toPrimitive(positions.toArray(new Float[0]), 0f);
matrix.postTranslate(rect.left, rect.top);
matrix.mapPoints(points);
for (int i = 0; i < keyPoints.size(); i++) {
keyPoints.get(i).coordinate = new PointF(points[i * 2] * scaleFactor, points[i * 2 + 1] * scaleFactor);
}
if (verbose) {
String resultHead = String.format(Locale.ENGLISH,
"Analysis completed for frame: %04d\nKeyPoints:\n", frameIndex);
StringBuilder builder = new StringBuilder(resultHead);
for (KeyPoint keyPoint : keyPoints) {
builder.append(" ");
builder.append(keyPoint.toString());
builder.append('\n');
}
builder.append('\n');
String resultMessage = builder.toString();
Log.v(TAG, resultMessage);
}
int origWidth = (int) (bitmap.getWidth() * scaleFactor);
int origHeight = (int) (bitmap.getHeight() * scaleFactor);
boolean distracted = isDistracted(keyPoints, origWidth, origHeight);
return new InnerFrame(frameIndex, distracted, totalScore, keyPoints);
}
void setup(int width, int height) {
if (!processorQueue.isEmpty()) {
return;
}
int size = Math.min(height, width);
cropRegion = initRectF(width, height);
for (int i = 0; i < THREAD_NUM; i++) {
processorQueue.add(new ImageProcessor.Builder()
.add(new ResizeWithCropOrPadOp(size, size))
.add(new ResizeOp(inputHeight, inputWidth, ResizeOp.ResizeMethod.BILINEAR))
.build());
}
}
/**
* Defines the default crop region.
* The function provides the initial crop region (pads the full image from both
* sides to make it a square image) when the algorithm cannot reliably determine
* the crop region from the previous frame.
*/
private RectF initRectF(int imageWidth, int imageHeight) {
float xMin;
float yMin;
float width;
float height;
if (imageWidth > imageHeight) {
width = 1f;
height = imageWidth / (float) imageHeight;
xMin = 0f;
yMin = (imageHeight / 2f - imageWidth / 2f) / imageHeight;
} else {
height = 1f;
width = imageHeight / (float) imageWidth;
yMin = 0f;
xMin = (imageWidth / 2f - imageHeight / 2f) / imageWidth;
}
return new RectF(xMin, yMin, xMin + width, yMin + height);
}
/**
* Looking down, looking back (not reversing), drinking, eating, using a phone
* Fairly basic, not very sophisticated
*/
private boolean isDistracted(List<KeyPoint> keyPoints, int imageWidth, int imageHeight) {
Map<BodyPart, KeyPoint> keyDict = keyPoints.stream().collect(Collectors.toMap(k -> k.bodyPart, k -> k));
boolean handsOccupied = false;
KeyPoint wristL = keyDict.get(BodyPart.LEFT_WRIST);
KeyPoint wristR = keyDict.get(BodyPart.RIGHT_WRIST);
if (wristL != null && wristL.score >= MIN_SCORE) {
handsOccupied = areHandsOccupied(wristL, imageHeight);
}
if (wristR != null && wristR.score >= MIN_SCORE) {
handsOccupied = handsOccupied || areHandsOccupied(wristR, imageHeight);
}
KeyPoint eyeL = keyDict.get(BodyPart.LEFT_EYE);
KeyPoint eyeR = keyDict.get(BodyPart.RIGHT_EYE);
KeyPoint earL = keyDict.get(BodyPart.LEFT_EAR);
KeyPoint earR = keyDict.get(BodyPart.RIGHT_EAR);
boolean eyesOccupied = areEyesOccupied(eyeL, earL) || areEyesOccupied(eyeR, earR);
return handsOccupied || eyesOccupied;
}
/**
* If wrists are above 1/4 video height, then they aren't on the steering wheel and the driver is likely occupied
* with something such as drinking or talking on the phone
*/
private boolean areHandsOccupied(KeyPoint wrist, int imageHeight) {
if (wrist == null) {
return false;
}
if (!(wrist.bodyPart.equals(BodyPart.LEFT_WRIST) || wrist.bodyPart.equals(BodyPart.RIGHT_WRIST))) {
Log.w(TAG, "Passed incorrect body part to areHandsOccupied");
return false;
}
// Y coordinates are top-down, not bottom-up
return wrist.coordinate.y < (imageHeight * 0.75);
}
/**
* When looking straight ahead (watching the road), the eyes are positioned above the ears
* When looking down (such as glancing at a phone), the eyes are vertically closer to the ears
*/
private boolean areEyesOccupied(KeyPoint eye, KeyPoint ear) {
if (eye == null || ear == null) {
return false;
}
if (!(eye.bodyPart.equals(BodyPart.LEFT_EYE) || eye.bodyPart.equals(BodyPart.RIGHT_EYE)) ||
!(ear.bodyPart.equals(BodyPart.LEFT_EAR) || ear.bodyPart.equals(BodyPart.RIGHT_EAR))) {
Log.w(TAG, "Passed incorrect body part to areEyesOccupied");
return false;
}
double dist = ear.coordinate.y - eye.coordinate.y;
double threshold = ear.coordinate.y / 20.0;
return dist < threshold;
}
float getScaleFactor(int width) {
return width / (float) inputWidth;
}
public void printParameters() {
StringJoiner paramMessage = new StringJoiner("\n ");
paramMessage.add("Inner analysis parameters:");
paramMessage.add(String.format("MIN_SCORE: %s", MIN_SCORE));
paramMessage.add(String.format("TensorFlow Threads: %s", TF_THREAD_NUM));
paramMessage.add(String.format("Analysis Threads: %s", THREAD_NUM));
Log.i(I_TAG, paramMessage.toString());
}
}
| 12,717 | 38.132308 | 167 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/video/analysis/VideoAnalysis.java | package com.example.edgedashanalytics.util.video.analysis;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.util.Log;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.util.TimeManager;
import com.example.edgedashanalytics.util.file.JsonManager;
import com.example.edgedashanalytics.util.hardware.PowerMonitor;
import com.example.edgedashanalytics.util.video.FfmpegTools;
import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public abstract class VideoAnalysis {
private static final String TAG = VideoAnalysis.class.getSimpleName();
private static final boolean DEFAULT_VERBOSE = false;
final static int TF_THREAD_NUM = 4;
final static int THREAD_NUM = 2;
final boolean verbose;
private static double stopDivisor = 1.0;
private static Long timeout = null;
/**
* Set up default parameters
*/
VideoAnalysis(Context context) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
this.verbose = pref.getBoolean(context.getString(R.string.verbose_output_key), DEFAULT_VERBOSE);
stopDivisor = Double.parseDouble(pref.getString(
context.getString(R.string.early_stop_divisor_key), String.valueOf(stopDivisor)));
}
abstract Frame processFrame(Bitmap bitmap, int frameIndex, float scaleFactor);
abstract void setup(int width, int height);
abstract float getScaleFactor(int width);
public abstract void printParameters();
public static double getEsdAdjust(String filename, Instant end, boolean isConnected) {
if (stopDivisor <= 0) {
return 0;
}
final double baseEsdStep = 0.2;
final double margin = 0.1;
final double increaseScale;
final double decreaseScale;
if (isConnected) {
increaseScale = 2.0;
decreaseScale = 0.5;
} else {
increaseScale = 10.0;
decreaseScale = 0.01;
}
long turnaround = Duration.between(TimeManager.getStartTime(filename), end).toMillis();
double difference = (turnaround / (double) FfmpegTools.getDurationMillis()) - 1;
if (difference >= -margin && difference <= 0) {
return 0;
} else if (difference > 0) {
return difference * baseEsdStep * increaseScale;
} else { // difference < -margin
return difference * baseEsdStep * decreaseScale;
}
}
public static void adjustEsd(double adjust) {
if (stopDivisor <= 0) {
return;
}
if (stopDivisor + adjust < 1) {
stopDivisor = 1;
} else {
stopDivisor += adjust;
}
Log.d(I_TAG, String.format("Changed ESD to %.4f", stopDivisor));
timeout = (long) (FfmpegTools.getDurationMillis() / stopDivisor);
}
public void analyse(String inPath, String outPath) {
processVideo(inPath, outPath);
}
private void processVideo(String inPath, String outPath) {
File videoFile = new File(inPath);
String videoName = videoFile.getName();
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(videoFile.getAbsolutePath());
} catch (Exception e) {
Log.e(I_TAG, String.format("Failed to set data source for %s: %s\n %s",
videoName, e.getClass().getSimpleName(), e.getMessage()));
return;
}
String totalFramesString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT);
if (totalFramesString == null) {
Log.e(TAG, String.format("Could not retrieve metadata from %s", videoName));
return;
}
int totalFrames = Integer.parseInt(totalFramesString);
Instant startTime = Instant.now();
long startPower = PowerMonitor.getTotalPowerConsumption();
String startString = String.format("Starting analysis of %s, %s frames", videoName, totalFrames);
Log.d(I_TAG, startString);
final List<Frame> frames = Collections.synchronizedList(new ArrayList<>(totalFrames));
ExecutorService frameExecutor = Executors.newFixedThreadPool(THREAD_NUM);
ExecutorService loopExecutor = Executors.newSingleThreadExecutor();
loopExecutor.submit(processFramesLoop(retriever, totalFrames, frames, frameExecutor));
boolean complete = false;
if (timeout == null) {
if (stopDivisor <= 0) {
// Ten minutes in milliseconds
timeout = 600000L;
} else {
FfmpegTools.setDuration(inPath);
timeout = (long) (FfmpegTools.getDurationMillis() / stopDivisor);
}
}
try {
loopExecutor.shutdown();
complete = loopExecutor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
if (stopDivisor < 0) {
// Guarantee complete processing
frameExecutor.shutdown();
//noinspection ResultOfMethodCallIgnored
frameExecutor.awaitTermination(timeout * 60, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException e) {
Log.e(I_TAG, String.format("Interrupted analysis of %s:\n %s", videoName, e.getMessage()));
}
if (!complete) {
frameExecutor.shutdown();
int completedFrames = frames.size();
Log.w(I_TAG, String.format("Stopped processing early for %s at %s frames, %s remaining",
videoName, completedFrames, totalFrames - completedFrames));
}
synchronized (frames) {
JsonManager.writeResultsToJson(outPath, frames);
}
frameExecutor.shutdown();
String time = TimeManager.getDurationString(startTime);
long powerConsumption = PowerMonitor.getPowerConsumption(startPower);
String endString = String.format(Locale.ENGLISH, "Completed analysis of %s in %ss, %dnW consumed",
videoName, time, powerConsumption);
Log.d(I_TAG, endString);
PowerMonitor.printSummary();
}
private Runnable processFramesLoop(MediaMetadataRetriever retriever, int totalFrames,
List<Frame> frames, ExecutorService executor) {
return () -> {
String videoWidthString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
String videoHeightString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
int videoWidth = Integer.parseInt(videoWidthString);
int videoHeight = Integer.parseInt(videoHeightString);
float scaleFactor = getScaleFactor(videoWidth);
int scaledWidth = (int) (videoWidth / scaleFactor);
int scaledHeight = (int) (videoHeight / scaleFactor);
setup(scaledWidth, scaledHeight);
// MediaMetadataRetriever is inconsistent, seems to only reliably with x264, may fail with other codecs
for (int i = 0; i < totalFrames; i++) {
final Bitmap bitmap = retriever.getFrameAtIndex(i);
final int k = i;
executor.execute(() -> frames.add(processFrame(
Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, false), k, scaleFactor)
));
}
};
}
}
| 7,991 | 36.172093 | 116 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/file/FileManager.java | package com.example.edgedashanalytics.util.file;
import static org.apache.commons.io.FilenameUtils.getBaseName;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.util.video.FfmpegTools;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FileManager {
private static final String TAG = FileManager.class.getSimpleName();
private static final String VIDEO_EXTENSION = "mp4";
private static final String RESULT_EXTENSION = "json";
private static final String RAW_DIR_NAME = "raw";
private static final String RESULTS_DIR_NAME = "results";
private static final String NEARBY_DIR_NAME = ".nearby";
private static final String SEGMENT_DIR_NAME = "segment";
private static final String SEGMENT_RES_DIR_NAME = String.format("%s-res", SEGMENT_DIR_NAME);
private static final String LOG_DIR_NAME = "out";
private static final File MOVIE_DIR = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
private static final File DOWN_DIR = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
private static final File DOC_DIR = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
private static final File RAW_DIR = new File(MOVIE_DIR, RAW_DIR_NAME);
private static final File RESULTS_DIR = new File(MOVIE_DIR, RESULTS_DIR_NAME);
private static final File NEARBY_DIR = new File(DOWN_DIR, NEARBY_DIR_NAME);
private static final File SEGMENT_DIR = new File(MOVIE_DIR, SEGMENT_DIR_NAME);
private static final File SEGMENT_RES_DIR = new File(MOVIE_DIR, SEGMENT_RES_DIR_NAME);
private static final File LOG_DIR = new File(DOC_DIR, LOG_DIR_NAME);
private static final List<File> DIRS = Arrays.asList(
RAW_DIR, RESULTS_DIR, NEARBY_DIR, SEGMENT_DIR, SEGMENT_RES_DIR, LOG_DIR);
public static String getRawDirPath() {
return RAW_DIR.getAbsolutePath();
}
public static String getResultDirPath() {
return RESULTS_DIR.getAbsolutePath();
}
public static String getNearbyDirPath() {
return NEARBY_DIR.getAbsolutePath();
}
public static String getSegmentDirPath() {
return SEGMENT_DIR.getAbsolutePath();
}
public static String getSegmentDirPath(String subDir) {
return makeDirectory(SEGMENT_DIR, subDir).getAbsolutePath();
}
public static String getSegmentResDirPath() {
return SEGMENT_RES_DIR.getAbsolutePath();
}
static String getSegmentResDirPath(String subDir) {
return makeDirectory(SEGMENT_RES_DIR, subDir).getAbsolutePath();
}
public static String getSegmentResSubDirPath(String videoName) {
String baseVideoName = FfmpegTools.getBaseName(videoName);
return makeDirectory(SEGMENT_RES_DIR, baseVideoName).getAbsolutePath();
}
public static String getLogDirPath() {
return LOG_DIR.getAbsolutePath();
}
public static void initialiseDirectories() {
for (File dir : DIRS) {
makeDirectory(dir);
}
}
private static File makeDirectory(File dirPath) {
if (!DeviceExternalStorage.externalStorageIsWritable()) {
Log.e(TAG, "External storage is not readable");
return null;
}
if (dirPath.exists()) {
Log.v(TAG, String.format("Directory already exists: %s", dirPath));
return dirPath;
}
try {
if (dirPath.mkdirs()) {
Log.v(TAG, String.format("Created new directory: %s", dirPath));
return dirPath;
} else {
Log.e(TAG, String.format("Failed to create new directory: %s", dirPath));
}
} catch (SecurityException e) {
Log.e(TAG, String.format("makeDirectory error: \n%s", e.getMessage()));
}
return null;
}
private static File makeDirectory(File dir, String subDirName) {
return makeDirectory(new File(dir, subDirName));
}
public static boolean isMp4(String filename) {
int extensionStartIndex = filename.lastIndexOf('.') + 1;
return filename.regionMatches(true, extensionStartIndex, VIDEO_EXTENSION, 0, VIDEO_EXTENSION.length());
}
private static boolean isJson(String filename) {
int extensionStartIndex = filename.lastIndexOf('.') + 1;
return filename.regionMatches(true, extensionStartIndex, RESULT_EXTENSION, 0, RESULT_EXTENSION.length());
}
public static boolean isInner(String filename) {
return FilenameUtils.getBaseName(filename).startsWith("inn");
}
public static boolean isOuter(String filename) {
return FilenameUtils.getBaseName(filename).startsWith("out");
}
public static void cleanDirectories(Context context) {
Log.v(TAG, "Cleaning directories");
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
List<File> dirs = pref.getBoolean(context.getString(R.string.remove_raw_key), false) ?
DIRS.stream().filter(d -> !d.equals(LOG_DIR)).collect(Collectors.toList()) :
DIRS.stream().filter(d -> !d.equals(LOG_DIR) && !d.equals(RAW_DIR)).collect(Collectors.toList());
for (File dir : dirs) {
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
Log.e(TAG, String.format("Failed to delete %s", dir.getAbsolutePath()));
Log.e(TAG, String.format("cleanVideoDirectories error: \n%s", e.getMessage()));
}
}
}
public static void clearLogs() {
try {
Log.v(TAG, "Clearing logs");
FileUtils.deleteDirectory(LOG_DIR);
} catch (IOException e) {
Log.e(TAG, String.format("Failed to clear logs: \n%s", e.getMessage()));
}
}
public static String getFilenameFromPath(String filePath) {
return filePath.substring(filePath.lastIndexOf('/') + 1);
}
public static String getResultNameFromVideoName(String filename) {
return String.format("%s.%s", getBaseName(filename), RESULT_EXTENSION);
}
public static String getVideoNameFromResultName(String filename) {
return String.format("%s.%s", getBaseName(filename), VIDEO_EXTENSION);
}
public static String getResultPathFromVideoName(String filename) {
return String.format("%s/%s", getResultDirPath(), getResultNameFromVideoName(filename));
}
public static String getResultPathOrSegmentResPathFromVideoName(String filename) {
if (FfmpegTools.isSegment(filename)) {
return String.format("%s/%s", FileManager.getSegmentResSubDirPath(filename),
getResultNameFromVideoName(filename));
} else {
return getResultPathFromVideoName(filename);
}
}
public static List<Result> getResultsFromDir(String dirPath) {
File dir = new File(dirPath);
if (!dir.isDirectory()) {
Log.e(TAG, String.format("%s is not a directory", dir.getAbsolutePath()));
return null;
}
Log.v(TAG, String.format("Retrieving results from %s", dir.getAbsolutePath()));
File[] resultFiles = dir.listFiles();
if (resultFiles == null) {
Log.e(TAG, String.format("Could not access contents of %s", dir.getAbsolutePath()));
return null;
}
List<String> resultPaths = Arrays.stream(resultFiles)
.map(File::getAbsolutePath).filter(FileManager::isJson).collect(Collectors.toList());
List<Result> results = new ArrayList<>();
for (String resultPath : resultPaths) {
results.add(new Result(resultPath));
}
return results;
}
static List<String> getChildPaths(File dir) {
File[] files = dir.listFiles();
if (files == null) {
Log.e(TAG, String.format("Could not access contents of %s", dir.getAbsolutePath()));
return null;
}
return Arrays.stream(files).map(File::getAbsolutePath).sorted(String::compareTo).collect(Collectors.toList());
}
public static void makeDummyResult(String filename) {
try {
boolean result = new File(getResultPathOrSegmentResPathFromVideoName(filename)).createNewFile();
if (!result) {
Log.e(TAG, String.format("File already exists: %s", filename));
}
} catch (IOException e) {
Log.e(TAG, String.format("Failed to create dummy result '%s': \n%s", filename, e.getMessage()));
}
}
}
| 9,072 | 37.121849 | 120 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/file/JsonManager.java | package com.example.edgedashanalytics.util.file;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.util.Log;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.util.TimeManager;
import com.example.edgedashanalytics.util.video.analysis.Frame;
import com.example.edgedashanalytics.util.video.analysis.InnerFrame;
import com.example.edgedashanalytics.util.video.analysis.OuterFrame;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class JsonManager {
private static final String TAG = JsonManager.class.getSimpleName();
private static final ObjectMapper mapper = JsonMapper.builder()
.disable(MapperFeature.AUTO_DETECT_IS_GETTERS)
.visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.build();
private static final ObjectWriter writer = mapper.writer();
private static final ObjectReader innerReader = mapper.readerFor(InnerFrame.class);
private static final ObjectReader outerReader = mapper.readerFor(OuterFrame.class);
public static void writeResultsToJson(String jsonFilePath, List<Frame> frames) {
try {
writer.writeValue(new FileOutputStream(jsonFilePath),
frames.stream()
.filter(Objects::nonNull)
.sorted(Comparator.comparingInt(f -> f.frame))
.collect(Collectors.toList()));
} catch (Exception e) {
Log.e(I_TAG, String.format("Failed to write results file: %s\n %s",
e.getClass().getSimpleName(), e.getMessage()));
}
}
public static Result mergeResults(String parentName) {
Instant start = Instant.now();
String baseName = FilenameUtils.getBaseName(parentName);
List<String> resultPaths = FileManager.getChildPaths(new File(FileManager.getSegmentResDirPath(baseName)));
Log.v(TAG, String.format("Starting merge of results of %s", baseName));
if (resultPaths == null) {
return null;
}
String outPath = String.format("%s/%s", FileManager.getResultDirPath(), parentName);
try {
List<Frame> frames = FileManager.isInner(baseName) ?
getInnerFrames(resultPaths) : getOuterFrames(resultPaths);
writer.writeValue(new FileOutputStream(outPath), frames);
String time = TimeManager.getDurationString(start);
Log.d(I_TAG, String.format("Merged results of %s in %ss", baseName, time));
return new Result(outPath);
} catch (IOException e) {
Log.e(TAG, String.format("Results merge error: \n%s", e.getMessage()));
}
return null;
}
private static List<Frame> getInnerFrames(List<String> resultPaths) throws IOException {
int offset = 0;
List<Frame> allFrames = new ArrayList<>();
for (String resultPath : resultPaths) {
MappingIterator<InnerFrame> map = innerReader.readValues(new FileInputStream(resultPath));
List<InnerFrame> frames = map.readAll();
if (frames.isEmpty()) {
continue;
}
for (InnerFrame frame : frames) {
frame.frame += offset;
}
offset = frames.get(frames.size() - 1).frame + 1;
allFrames.addAll(frames);
}
return allFrames;
}
private static List<Frame> getOuterFrames(List<String> resultPaths) throws IOException {
int offset = 0;
List<Frame> allFrames = new ArrayList<>();
for (String resultPath : resultPaths) {
MappingIterator<OuterFrame> map = outerReader.readValues(new FileInputStream(resultPath));
List<OuterFrame> frames = map.readAll();
if (frames.isEmpty()) {
continue;
}
for (OuterFrame frame : frames) {
frame.frame += offset;
}
offset = frames.get(frames.size() - 1).frame + 1;
allFrames.addAll(frames);
}
return allFrames;
}
public static String writeToString(Object object) {
try {
return writer.writeValueAsString(object);
} catch (JsonProcessingException e) {
return null;
}
}
public static Object readFromString(String json, Class<?> classType) {
try {
return mapper.readValue(json, classType);
} catch (JsonProcessingException e) {
return null;
}
}
}
| 5,375 | 35.324324 | 115 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/file/DeviceExternalStorage.java | package com.example.edgedashanalytics.util.file;
import android.os.Environment;
public class DeviceExternalStorage {
static boolean externalStorageIsWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public static boolean externalStorageIsReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
}
| 528 | 32.0625 | 108 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/dashcam/DashCam.java | package com.example.edgedashanalytics.util.dashcam;
import static com.example.edgedashanalytics.page.main.MainActivity.I_TAG;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.SimpleArrayMap;
import androidx.preference.PreferenceManager;
import com.example.edgedashanalytics.R;
import com.example.edgedashanalytics.event.video.AddEvent;
import com.example.edgedashanalytics.event.video.Type;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.util.TimeManager;
import com.example.edgedashanalytics.util.file.FileManager;
import com.example.edgedashanalytics.util.hardware.PowerMonitor;
import com.example.edgedashanalytics.util.video.VideoManager;
import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.EnqueueAction;
import com.tonyodev.fetch2.Error;
import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchConfiguration;
import com.tonyodev.fetch2.FetchListener;
import com.tonyodev.fetch2.NetworkType;
import com.tonyodev.fetch2.Priority;
import com.tonyodev.fetch2.Request;
import com.tonyodev.fetch2core.DownloadBlock;
import com.tonyodev.fetch2core.Downloader;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
// TODO: convert to singleton
public class DashCam {
private static final String TAG = DashCam.class.getSimpleName();
// BlackVue
// private static final String baseUrl = "http://10.99.77.1/";
// private static final String videoDirUrl = baseUrl + "Record/";
// VIOFO
private static final String baseUrl = "http://192.168.1.254/DCIM/MOVIE/";
private static final String videoDirUrl = baseUrl;
// Video stream: rtsp://192.168.1.254
private static final Set<String> downloads = new HashSet<>();
private static final SimpleArrayMap<String, Long> downloadPowers = new SimpleArrayMap<>();
private static Fetch fetch = null;
// bytes per second / 1000, aka MB/s
public static long latestDownloadSpeed = 0;
private static boolean dualDownload = false;
public static final int concurrentDownloads = 2;
private static final long updateInterval = 10000;
private static final int retryAttempts = 5;
// Two subsets of videos, each comprised of 400 segments, every video is exactly two seconds in length
private static int testSubsetCount = 400;
private static List<String> testVideos;
public static void setup(Context context) {
if (fetch == null) {
FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(context)
.setDownloadConcurrentLimit(concurrentDownloads)
.setProgressReportingInterval(updateInterval)
.setAutoRetryMaxAttempts(retryAttempts)
.build();
fetch = Fetch.Impl.getInstance(fetchConfiguration);
clearDownloads();
}
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
dualDownload = pref.getBoolean(context.getString(R.string.dual_download_key), dualDownload);
testSubsetCount = Integer.parseInt(pref.getString(
context.getString(R.string.test_video_count_key), String.valueOf(testSubsetCount)));
testVideos = IntStream.rangeClosed(1, testSubsetCount)
.mapToObj(i -> String.format(Locale.ENGLISH, "%04d", i))
.flatMap(num -> Stream.of(String.format("inn_%s.mp4", num), String.format("out_%s.mp4", num)))
.sorted(DashCam::testVideoComparator)
.collect(Collectors.toList());
}
public static void clearDownloads() {
fetch.cancelAll();
fetch.removeAll();
}
public static int getTestVideoCount() {
return testSubsetCount * 2;
}
public static void startDownloadAll(Context context) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Consumer<Video> downloadCallback = (video) -> EventBus.getDefault().post(new AddEvent(video, Type.RAW));
executor.submit(downloadAll(downloadCallback, context));
}
private static Runnable downloadAll(Consumer<Video> downloadCallback, Context context) {
return () -> {
List<String> allFiles = getViofoFilenames();
if (allFiles == null) {
Log.e(I_TAG, "Dash cam file list is null");
return;
}
for (String filename : allFiles) {
String videoUrl = String.format("%s%s", videoDirUrl, filename);
downloadVideo(videoUrl, downloadCallback, context);
}
};
}
private static List<String> getBlackvueFilenames() {
Document doc;
try {
doc = Jsoup.connect(baseUrl + "blackvue_vod.cgi").get();
} catch (IOException e) {
Log.e(I_TAG, "Could not connect to dash cam");
return null;
}
List<String> allFiles = new ArrayList<>();
String raw = doc.select("body").text();
Pattern pat = Pattern.compile(Pattern.quote("Record/") + "(.*?)" + Pattern.quote(",s:"));
Matcher match = pat.matcher(raw);
while (match.find()) {
allFiles.add(match.group(1));
}
allFiles.sort(Comparator.comparing(String::toString));
return allFiles;
}
private static List<String> getViofoFilenames() {
Document doc;
try {
doc = Jsoup.connect(baseUrl).get();
} catch (IOException e) {
Log.e(I_TAG, "Could not connect to dash cam");
return null;
}
List<String> allFiles = new ArrayList<>();
String raw = doc.select("body").text();
Pattern pat = Pattern.compile("(\\S+\\.MP4)");
Matcher match = pat.matcher(raw);
while (match.find()) {
allFiles.add(match.group(1));
}
allFiles.sort(Comparator.comparing(String::toString));
return allFiles;
}
/**
* Old method of downloading videos through {@link FileUtils#copyURLToFile}
* TODO: replace usages with {@link DashCam#downloadVideo(String)}
*/
private static void downloadVideo(String url, Consumer<Video> downloadCallback, Context context) {
String filename = FileManager.getFilenameFromPath(url);
String filePath = String.format("%s/%s", FileManager.getRawDirPath(), filename);
Log.v(TAG, String.format("Started download: %s", filename));
Instant start = Instant.now();
try {
FileUtils.copyURLToFile(new URL(url), new File(filePath));
} catch (IOException e) {
Log.w(TAG, String.format("Video download error, retrying: \n%s", e.getMessage()));
return;
}
Video video = VideoManager.getVideoFromPath(context, filePath);
if (video == null) {
try {
String errorMessage = String.format("Failed to download %s, retrying in 5s", filename);
Log.w(TAG, errorMessage);
Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show();
Thread.sleep(5000);
} catch (InterruptedException e) {
Log.e(TAG, String.format("Thread interrupted: \n%s", e.getMessage()));
}
return;
}
downloads.add(filename);
String time = TimeManager.getDurationString(start);
Log.i(I_TAG, String.format("Successfully downloaded %s in %ss", filename, time));
downloadCallback.accept(video);
}
private static void downloadVideo(String url) {
String filename = FileManager.getFilenameFromPath(url);
String filePath = String.format("%s/%s", FileManager.getRawDirPath(), filename);
downloads.add(filename);
final Request request = new Request(url, filePath);
request.setPriority(Priority.HIGH);
request.setNetworkType(NetworkType.ALL);
request.setEnqueueAction(EnqueueAction.REPLACE_EXISTING);
fetch.enqueue(request,
updatedRequest -> Log.d(I_TAG, String.format("Enqueued %s", FilenameUtils.getName(request.getFile()))),
error -> Log.d(I_TAG, String.format("Enqueueing error: %s", error)));
}
public static Runnable downloadLatestVideos(Consumer<Video> downloadCallback, Context context) {
return () -> {
Log.v(TAG, "Starting downloadLatestVideos");
List<String> allVideos = getBlackvueFilenames();
if (allVideos == null || allVideos.size() == 0) {
Log.e(I_TAG, "Couldn't download videos");
return;
}
List<String> newVideos = new ArrayList<>(CollectionUtils.disjunction(allVideos, downloads));
newVideos.sort(Comparator.comparing(String::toString));
if (newVideos.size() != 0) {
// Get oldest new video
String toDownload = newVideos.get(0);
downloads.add(toDownload);
downloadVideo(videoDirUrl + toDownload, downloadCallback, context);
} else {
Log.d(TAG, "No new videos");
}
};
}
public static Runnable downloadTestVideos() {
return () -> {
List<String> newVideos = new ArrayList<>(CollectionUtils.disjunction(testVideos, downloads));
newVideos.sort(DashCam::testVideoComparator);
if (newVideos.size() != 0) {
downloadVideo(videoDirUrl + newVideos.get(0));
if (dualDownload && newVideos.size() > 1) {
downloadVideo(videoDirUrl + newVideos.get(1));
}
} else {
Log.v(TAG, "All test videos queued for download");
}
};
}
private static boolean popTestDownload() {
if (!testVideos.isEmpty()) {
String filename = testVideos.remove(0);
downloads.add(filename);
downloadVideo(videoDirUrl + filename);
return true;
} else {
return false;
}
}
public static void downloadTestVideosLoop(Context context) {
fetch.addListener(getFetchListener(context, v -> {
if (v != null) {
EventBus.getDefault().post(new AddEvent(v, Type.RAW));
}
}));
Instant start = Instant.now();
ScheduledExecutorService downloadExecutor = Executors.newSingleThreadScheduledExecutor();
Runnable downloadRunnable = () -> {
if (!popTestDownload()) {
downloadExecutor.shutdown();
String time = TimeManager.getDurationString(start);
Log.i(TAG, String.format("All test videos scheduled for download in %ss", time));
}
if (dualDownload) {
popTestDownload();
}
};
String defaultDelay = "1000";
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
int delay = Integer.parseInt(pref.getString(context.getString(R.string.download_delay_key), defaultDelay));
downloadExecutor.scheduleWithFixedDelay(downloadRunnable, 0, delay, TimeUnit.MILLISECONDS);
}
public static int testVideoComparator(String videoA, String videoB) {
String prefixA = videoA.substring(0, 3);
String prefixB = videoB.substring(0, 3);
int suffixA = Integer.parseInt(StringUtils.substringBetween(videoA, "_", "."));
int suffixB = Integer.parseInt(StringUtils.substringBetween(videoB, "_", "."));
// Order sequentially based on suffix index
if (suffixA != suffixB) {
return suffixA - suffixB;
}
// Order "out" before "inn"
return -prefixA.compareTo(prefixB);
}
public static void setDownloadCallback(Context context, Consumer<Video> downloadCallback) {
fetch.addListener(getFetchListener(context, downloadCallback));
}
// public static Bitmap getLiveBitmap() {
// FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
// retriever.setDataSource("rtsp://192.168.1.254");
//
// return retriever.getFrameAtTime();
// }
private static FetchListener getFetchListener(Context context, Consumer<Video> downloadCallback) {
return new FetchListener() {
public void onStarted(@NonNull Download d, @NonNull List<? extends DownloadBlock> list, int i) {
String filename = FileManager.getFilenameFromPath(d.getFile());
TimeManager.addStartTime(filename);
downloadPowers.put(filename, PowerMonitor.getTotalPowerConsumption());
Log.d(I_TAG, String.format("Started download: %s", filename));
}
@Override
public void onCompleted(@NonNull Download d) {
Video video = VideoManager.getVideoFromPath(context, d.getFile());
String videoName = video.getName();
String time;
long power;
Instant start = TimeManager.getStartTime(videoName);
if (start != null) {
time = TimeManager.getDurationString(start);
} else {
Log.e(I_TAG, String.format("Could not record download time of %s", videoName));
time = "0.000";
}
if (downloadPowers.containsKey(videoName)) {
power = PowerMonitor.getPowerConsumption(downloadPowers.remove(videoName));
} else {
Log.e(TAG, String.format("Could not record download power consumption of %s", videoName));
power = 0;
}
Log.i(I_TAG, String.format("Successfully downloaded %s in %ss, %dnW consumed", videoName, time, power));
downloadCallback.accept(video);
}
public void onProgress(@NonNull Download d, long etaMilli, long bytesPerSec) {
latestDownloadSpeed = bytesPerSec / 1000;
Log.v(TAG, String.format("Downloading %s, Progress: %3s%%, ETA: %2ss, MB/s: %4s",
FileManager.getFilenameFromPath(d.getUrl()),
d.getProgress(), etaMilli / 1000, latestDownloadSpeed
));
}
public void onAdded(@NonNull Download d) {
// Stop condition for queuing test video downloads.
// Won't work for non-test download scenarios, will need alternative stopping method.
if (downloads.size() == testVideos.size()) {
Log.v(TAG, "All test videos queued for download, stopping queuing thread");
downloadCallback.accept(null);
}
}
public void onError(@NonNull Download d, @NonNull Error error, @Nullable Throwable throwable) {
Downloader.Response response = error.getHttpResponse();
String responseString = response != null ? response.getErrorResponse() : "No response";
Log.e(I_TAG, String.format("Error downloading %s (attempt %s):\n%s\n%s",
FileManager.getFilenameFromPath(d.getUrl()), d.getAutoRetryAttempts(), error, responseString));
}
// @formatter:off
public void onQueued(@NonNull Download d, boolean b) {}
public void onWaitingNetwork(@NonNull Download d) {}
public void onDownloadBlockUpdated(@NonNull Download d, @NonNull DownloadBlock dBlock, int i) {}
public void onPaused(@NonNull Download d) {}
public void onResumed(@NonNull Download d) {}
public void onCancelled(@NonNull Download d) {}
public void onRemoved(@NonNull Download d) {}
public void onDeleted(@NonNull Download d) {}
// @formatter:on
};
}
}
| 16,979 | 38.952941 | 120 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/hardware/HardwareInfo.java | package com.example.edgedashanalytics.util.hardware;
import static com.example.edgedashanalytics.util.hardware.PowerMonitor.getBatteryLevel;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import androidx.annotation.NonNull;
import com.example.edgedashanalytics.util.file.JsonManager;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.IOException;
import java.io.RandomAccessFile;
public class HardwareInfo {
private static final String TAG = HardwareInfo.class.getSimpleName();
public final int cpuCores;
public final long cpuFreq;
private final long totalRam;
public final long availRam;
private final long totalStorage;
public final long availStorage;
public final int batteryLevel;
@JsonCreator
public HardwareInfo(@JsonProperty("cpuCores") int cpuCores, @JsonProperty("cpuFreq") long cpuFreq,
@JsonProperty("totalRam") long totalRam,
@JsonProperty("availRam") long availRam,
@JsonProperty("totalStorage") long totalStorage,
@JsonProperty("availStorage") long availStorage,
@JsonProperty("batteryLevel") int batteryLevel) {
this.cpuCores = cpuCores;
this.cpuFreq = cpuFreq;
this.totalRam = totalRam;
this.availRam = availRam;
this.totalStorage = totalStorage;
this.availStorage = availStorage;
this.batteryLevel = batteryLevel;
}
public HardwareInfo(Context context) {
cpuCores = getCpuCoreCount();
cpuFreq = getCpuFreq();
totalRam = getTotalRam(context);
availRam = getAvailRam(context);
totalStorage = getTotalStorage();
availStorage = getAvailStorage();
batteryLevel = getBatteryLevel(context);
}
/**
* @return CPU clock speed in Hz
*/
private long getCpuFreq() {
long maxFreq = -1;
for (int i = 0; i < cpuCores; i++) {
String filepath = "/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq";
try (RandomAccessFile raf = new RandomAccessFile(filepath, "r")) {
String line = raf.readLine();
if (line != null) {
long freq = Long.parseLong(line);
if (freq > maxFreq) {
maxFreq = freq;
}
}
} catch (IOException e) {
Log.e(TAG, String.format("Could not retrieve CPU frequency: \n%s", e.getMessage()));
}
}
return maxFreq;
}
private int getCpuCoreCount() {
return Runtime.getRuntime().availableProcessors();
}
/**
* @return total size of RAM in bytes
*/
private long getTotalRam(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memInfo);
return memInfo.totalMem;
}
/**
* @return size of available RAM in bytes
*/
private long getAvailRam(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memInfo);
return memInfo.availMem;
}
/**
* @return total storage size in bytes
*/
private long getTotalStorage() {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
return stat.getBlockSizeLong() * stat.getBlockCountLong();
}
/**
* @return size of available storage in bytes
*/
private long getAvailStorage() {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
return stat.getBlockSizeLong() * stat.getAvailableBlocksLong();
}
@NonNull
@Override
public String toString() {
return "HardwareInfo{" +
"cpuFreq=" + cpuFreq +
", cpuCores=" + cpuCores +
", totalRam=" + totalRam +
", availRam=" + availRam +
", totalStorage=" + totalStorage +
", availStorage=" + availStorage +
", batteryLevel=" + batteryLevel +
'}';
}
public String toJson() {
return JsonManager.writeToString(this);
}
public static HardwareInfo fromJson(String json) {
return (HardwareInfo) JsonManager.readFromString(json, HardwareInfo.class);
}
public static int compareProcessing(HardwareInfo hwi1, HardwareInfo hwi2) {
int cpuFreqComp = Long.compare(hwi1.cpuFreq, hwi2.cpuFreq);
int cpuCoreComp = Integer.compare(hwi1.cpuCores, hwi2.cpuCores);
int ramComp = Long.compare(hwi1.totalRam, hwi2.totalRam);
double cpuDiff = Math.abs(hwi1.cpuFreq - hwi2.cpuFreq);
// First check if max CPU frequencies are within 1% of each other
if ((cpuDiff / hwi1.cpuFreq) < 0.01) {
if (cpuCoreComp != 0) {
return cpuCoreComp;
} else {
return ramComp;
}
} else {
if (cpuFreqComp != 0) {
return cpuFreqComp;
} else if (cpuCoreComp != 0) {
return cpuCoreComp;
} else {
return ramComp;
}
}
}
}
| 5,698 | 32.327485 | 111 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/util/hardware/PowerMonitor.java | package com.example.edgedashanalytics.util.hardware;
import static android.content.Context.BATTERY_SERVICE;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.util.Log;
import java.util.Locale;
import java.util.StringJoiner;
public class PowerMonitor {
private static final String TAG = PowerMonitor.class.getSimpleName();
private static BroadcastReceiver batteryReceiver = null;
private static long total = 0;
private static int count = 0;
private static boolean running = false;
public static void startPowerMonitor(Context con) {
if (batteryReceiver == null) {
batteryReceiver = new BroadcastReceiver() {
private final BatteryManager batteryManager = (BatteryManager) con.getSystemService(BATTERY_SERVICE);
public void onReceive(Context context, Intent intent) {
// Assumed to be millivolts
long voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
// Net charge in microamperes,
// positive is net value entering battery, negative is net discharge from battery
// Samsung phones seem to provide milliamperes instead: https://stackoverflow.com/a/66933765
long current = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
// Log.v(TAG, String.format("%d", Math.abs(voltage * current)));
count++;
// millivolts * microamperes = nanowatts
total += voltage * current;
}
};
}
if (running) {
Log.v(TAG, "Power Monitor is already running");
} else {
Log.v(TAG, "Starting Power Monitor");
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
con.registerReceiver(batteryReceiver, filter);
running = true;
}
}
public static void stopPowerMonitor(Context context) {
if (running) {
Log.v(TAG, "Stopping Power Monitor");
context.unregisterReceiver(batteryReceiver);
running = false;
} else {
Log.v(TAG, "Power Monitor is not running");
}
}
public static long getTotalPowerConsumption() {
return total;
}
/**
* Calculates the power consumed while performing a task.
* Requires providing a power measurement recorded prior to starting said task.
* May report 0 power consumption if no power changes are recorded by device during a task.
*/
public static long getPowerConsumption(Long startingPower) {
if (startingPower == null) {
Log.e(TAG, "Starting power is null");
return 0;
}
return Math.abs(total - startingPower);
}
/**
* May not be that useful, as only records average power consumption per measurement.
* Different devices may have different power measurement timings, devices with more frequent measurements
* will have lower "average" power consumption than devices will less frequent measurements.
*/
private static double getAveragePower() {
if (count == 0) {
return total;
} else {
return total / (double) count;
}
}
public static long getAveragePowerMilliWatts() {
long milliDigits = 1000000;
if (count == 0) {
return total / milliDigits;
} else {
return (total / count) / milliDigits;
}
}
public static void printSummary() {
StringJoiner message = new StringJoiner("\n ");
message.add("Power usage:");
message.add(String.format(Locale.ENGLISH, "Count: %d", count));
message.add(String.format(Locale.ENGLISH, "Total: %dnW", total));
message.add(String.format(Locale.ENGLISH, "Average: %.4fnW", getAveragePower()));
Log.d(TAG, message.toString());
}
public static void printBatteryLevel(Context context) {
Log.d(TAG, String.format(Locale.ENGLISH, "Battery level: %d%%", getBatteryLevel(context)));
}
/**
* @return percentage of battery level as an integer
*/
public static int getBatteryLevel(Context context) {
BatteryManager batteryManager = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
}
}
| 4,634 | 36.08 | 117 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/video/AddEvent.java | package com.example.edgedashanalytics.event.video;
import com.example.edgedashanalytics.model.Video;
public class AddEvent extends VideoEvent {
public AddEvent(Video video, Type type) {
super(video, type);
}
}
| 228 | 21.9 | 50 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/video/VideoEvent.java | package com.example.edgedashanalytics.event.video;
import com.example.edgedashanalytics.model.Video;
public class VideoEvent {
public final Video video;
public final Type type;
VideoEvent(Video video, Type type) {
this.video = video;
this.type = type;
}
}
| 291 | 19.857143 | 50 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/video/RemoveByNameEvent.java | package com.example.edgedashanalytics.event.video;
public class RemoveByNameEvent {
public final String name;
public final Type type;
public RemoveByNameEvent(String name, Type type) {
this.name = name;
this.type = type;
}
}
| 259 | 20.666667 | 54 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/video/RemoveEvent.java | package com.example.edgedashanalytics.event.video;
import com.example.edgedashanalytics.model.Video;
public class RemoveEvent extends VideoEvent {
public RemoveEvent(Video video, Type type) {
super(video, type);
}
}
| 234 | 22.5 | 50 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/video/Type.java | package com.example.edgedashanalytics.event.video;
public enum Type {
RAW, PROCESSING
}
| 93 | 14.666667 | 50 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/result/AddResultEvent.java | package com.example.edgedashanalytics.event.result;
import com.example.edgedashanalytics.model.Result;
public class AddResultEvent extends ResultEvent {
public AddResultEvent(Result result) {
super(result);
}
}
| 229 | 22 | 51 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/result/ResultEvent.java | package com.example.edgedashanalytics.event.result;
import com.example.edgedashanalytics.model.Result;
public class ResultEvent {
public final Result result;
ResultEvent(Result result) {
this.result = result;
}
}
| 236 | 18.75 | 51 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/event/result/RemoveResultEvent.java | package com.example.edgedashanalytics.event.result;
import com.example.edgedashanalytics.model.Result;
public class RemoveResultEvent extends ResultEvent {
public RemoveResultEvent(Result result) {
super(result);
}
}
| 235 | 22.6 | 52 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/video/VideosRepository.java | package com.example.edgedashanalytics.data.video;
import androidx.lifecycle.LiveData;
import com.example.edgedashanalytics.model.Video;
import java.util.List;
public interface VideosRepository {
LiveData<List<Video>> getVideos();
void insert(Video video);
void delete(int position);
void delete(String path);
void update(Video video, int position);
}
| 379 | 18 | 49 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/video/ProcessingVideosRepository.java | package com.example.edgedashanalytics.data.video;
import androidx.lifecycle.MutableLiveData;
import com.example.edgedashanalytics.model.Video;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ProcessingVideosRepository implements VideosRepository {
private List<Video> videos = new ArrayList<>();
private final MutableLiveData<List<Video>> result = new MutableLiveData<>();
public ProcessingVideosRepository() {
}
@Override
public MutableLiveData<List<Video>> getVideos() {
List<Video> videos = new ArrayList<>();
result.setValue(videos);
return result;
}
@Override
public void insert(Video video) {
videos.add(video);
result.postValue(videos);
}
@Override
public void delete(int position) {
videos.remove(position);
result.postValue(videos);
}
@Override
public void delete(String path) {
videos = videos.stream().filter(e -> !e.getData().equalsIgnoreCase(path)).collect(Collectors.toList());
result.postValue(videos);
}
@Override
public void update(Video video, int position) {
videos.set(position, video);
result.postValue(videos);
}
}
| 1,264 | 24.3 | 111 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/video/ExternalStorageVideosRepository.java | package com.example.edgedashanalytics.data.video;
import android.content.Context;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.example.edgedashanalytics.model.Video;
import com.example.edgedashanalytics.util.video.VideoManager;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ExternalStorageVideosRepository implements VideosRepository {
private final static String TAG = ExternalStorageVideosRepository.class.getSimpleName();
private Context context;
private File videoDirectory;
private List<Video> videos = new ArrayList<>();
private final MutableLiveData<List<Video>> result = new MutableLiveData<>();
public ExternalStorageVideosRepository(Context context, String path) {
if (path == null) {
Log.w(TAG, "Null path");
return;
}
this.context = context;
this.videoDirectory = new File(path);
Log.v(TAG, String.format("Created repo: %s", videoDirectory.getAbsolutePath()));
}
@Override
public MutableLiveData<List<Video>> getVideos() {
videos = VideoManager.getAllVideoFromExternalStorageFolder(context.getApplicationContext(), videoDirectory);
videos.sort(Comparator.comparing(Video::getName));
result.setValue(videos);
return result;
}
@Override
public void insert(Video video) {
videos.add(video);
result.postValue(videos);
}
@Override
public void delete(int position) {
videos.remove(position);
result.postValue(videos);
}
@Override
public void delete(String path) {
videos = videos.stream().filter(e -> !e.getData().equalsIgnoreCase(path)).collect(Collectors.toList());
result.postValue(videos);
}
@Override
public void update(Video video, int position) {
videos.set(position, video);
result.postValue(videos);
}
}
| 2,019 | 28.275362 | 116 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/video/VideoViewModelFactory.java | package com.example.edgedashanalytics.data.video;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
public class VideoViewModelFactory implements ViewModelProvider.Factory {
private final Application application;
private final VideosRepository repository;
public VideoViewModelFactory(Application application, VideosRepository repository) {
this.application = application;
this.repository = repository;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
//noinspection unchecked
return (T) new VideoViewModel(application, repository);
}
}
| 748 | 28.96 | 88 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/video/VideoViewModel.java | package com.example.edgedashanalytics.data.video;
import android.app.Application;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import com.example.edgedashanalytics.model.Video;
import java.util.List;
public class VideoViewModel extends ViewModel {
private final VideosRepository repository;
private final LiveData<List<Video>> videos;
VideoViewModel(Application application, VideosRepository videosRepository) {
super();
repository = videosRepository;
videos = repository.getVideos();
}
public LiveData<List<Video>> getVideos() {
return videos;
}
public void insert(Video video) {
repository.insert(video);
}
public void remove(int position) {
repository.delete(position);
}
public void update(Video video, int position) {
repository.update(video, position);
}
}
| 905 | 22.842105 | 80 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/result/ResultViewModelFactory.java | package com.example.edgedashanalytics.data.result;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
public class ResultViewModelFactory implements ViewModelProvider.Factory {
private final Application application;
private final ResultRepository repository;
public ResultViewModelFactory(Application application, ResultRepository repository) {
this.application = application;
this.repository = repository;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
//noinspection unchecked
return (T) new ResultViewModel(application, repository);
}
}
| 752 | 29.12 | 89 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/result/ResultViewModel.java | package com.example.edgedashanalytics.data.result;
import android.app.Application;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import com.example.edgedashanalytics.model.Result;
import java.util.List;
public class ResultViewModel extends ViewModel {
private final ResultRepository repository;
private final LiveData<List<Result>> liveData;
ResultViewModel(Application application, ResultRepository resultRepository) {
super();
repository = resultRepository;
liveData = repository.getResults();
}
public LiveData<List<Result>> getResults() {
return liveData;
}
public void insert(Result result) {
repository.insert(result);
}
public void remove(int position) {
repository.delete(position);
}
public void update(Result result, int position) {
repository.update(result, position);
}
}
| 925 | 23.368421 | 81 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/data/result/ResultRepository.java | package com.example.edgedashanalytics.data.result;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.example.edgedashanalytics.model.Result;
import com.example.edgedashanalytics.util.file.FileManager;
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class ResultRepository {
private final static String TAG = ResultRepository.class.getSimpleName();
private List<Result> results = new ArrayList<>();
private final MutableLiveData<List<Result>> liveData = new MutableLiveData<>();
public ResultRepository() {
}
public MutableLiveData<List<Result>> getResults() {
results = retrieveResults();
results.sort(Comparator.comparing(Result::getName));
liveData.setValue(results);
return liveData;
}
private List<Result> retrieveResults() {
List<Result> results = new ArrayList<>();
File resultDir = new File(FileManager.getResultDirPath());
File[] resultFiles = resultDir.listFiles();
if (resultFiles == null) {
Log.e(TAG, "Could not retrieve result files");
return results;
}
for (File resultFile : resultFiles) {
Result result = new Result(resultFile.getAbsolutePath());
results.add(result);
}
return results;
}
public void insert(Result result) {
results.add(result);
liveData.postValue(results);
}
public void delete(int position) {
results.remove(position);
liveData.postValue(results);
}
public void delete(String path) {
results = results.stream().filter(e -> !e.getData().equalsIgnoreCase(path)).collect(Collectors.toList());
liveData.postValue(results);
}
void update(Result result, int position) {
results.set(position, result);
liveData.postValue(results);
}
}
| 1,978 | 27.681159 | 113 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/model/Result.java | package com.example.edgedashanalytics.model;
import android.os.Parcel;
import androidx.annotation.NonNull;
import com.example.edgedashanalytics.util.file.FileManager;
public class Result extends Content {
public static final Creator<Result> CREATOR = new Creator<>() {
@Override
public Result createFromParcel(Parcel in) {
return new Result(in);
}
@Override
public Result[] newArray(int size) {
return new Result[size];
}
};
public Result(String data, String name) {
super(data, name);
}
public Result(String data) {
super(data, FileManager.getFilenameFromPath(data));
}
private Result(Parcel in) {
super(in.readString(), in.readString());
}
@Override
public int describeContents() {
return 0;
}
@NonNull
@Override
public String toString() {
return "Result{" +
"data='" + data + '\'' +
", name='" + name + '\'' +
'}';
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(data);
dest.writeString(name);
}
}
| 1,193 | 21.111111 | 67 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/model/Video.java | package com.example.edgedashanalytics.model;
import android.content.ContentValues;
import android.content.Context;
import android.os.Build;
import android.os.Parcel;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import com.example.edgedashanalytics.util.file.FileManager;
import java.math.BigInteger;
import java.util.Objects;
public class Video extends Content {
private final String id;
private final BigInteger size;
private final boolean visible;
private final String mimeType;
public static final Creator<Video> CREATOR = new Creator<>() {
@Override
public Video createFromParcel(Parcel parcel) {
return new Video(parcel);
}
@Override
public Video[] newArray(int i) {
return new Video[i];
}
};
public Video(String id, String name, String data, String mimeType, BigInteger size) {
super(data, name);
this.id = id;
this.size = size;
this.mimeType = mimeType;
this.visible = true;
}
public Video(String id, String name, String data, String mimeType, BigInteger size, boolean visible) {
super(data, name);
this.id = id;
this.size = size;
this.mimeType = mimeType;
this.visible = visible;
}
public Video(Video video) {
super(video.data, video.name);
this.id = video.id;
this.size = video.size;
this.mimeType = video.mimeType;
this.visible = video.visible;
}
public Video(Video video, boolean visible) {
super(video.data, video.name);
this.id = video.id;
this.size = video.size;
this.mimeType = video.mimeType;
this.visible = visible;
}
private Video(Parcel in) {
super(in.readString(), in.readString());
this.id = in.readString();
String size = in.readString();
this.size = new BigInteger(Objects.requireNonNullElse(size, "-1"));
this.mimeType = in.readString();
this.visible = in.readByte() != 0;
}
public String getId() {
return id;
}
public BigInteger getSize() {
return size;
}
public boolean isVisible() {
return visible;
}
public String getMimeType() {
return mimeType;
}
public boolean isInner() {
return FileManager.isInner(getData());
}
public boolean isOuter() {
return FileManager.isOuter(getData());
}
@NonNull
@Override
public String toString() {
return "Video{" +
"data='" + data + '\'' +
", name='" + name + '\'' +
", id='" + id + '\'' +
", size=" + size +
", visible=" + visible +
", mimeType='" + mimeType + '\'' +
'}';
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(data);
parcel.writeString(name);
parcel.writeString(id);
parcel.writeString(size.toString());
parcel.writeString(mimeType);
parcel.writeByte(visible ? (byte) 1 : 0);
}
// Insert a new video's values into the MediaStore using an existing video as a basis
public void insertMediaValues(Context context, String path) {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.TITLE, name);
values.put(MediaStore.Video.Media.MIME_TYPE, mimeType);
values.put(MediaStore.Video.Media.DISPLAY_NAME, "player");
values.put(MediaStore.Video.Media.DESCRIPTION, "");
values.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis());
}
values.put(MediaStore.Video.Media.DATA, path);
context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
}
}
| 4,103 | 27.699301 | 106 | java |
EdgeDashAnalytics | EdgeDashAnalytics-master/app/src/main/java/com/example/edgedashanalytics/model/Content.java | package com.example.edgedashanalytics.model;
import android.os.Parcelable;
public abstract class Content implements Parcelable {
final String data;
final String name;
Content(String data, String name) {
this.data = data;
this.name = name;
}
public String getData() {
return data;
}
public String getName() {
return name;
}
}
| 394 | 16.954545 | 53 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/Main.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
/*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm;
import java.util.Arrays;
/**
* Main is the top level interface to the FuzzM tool suite.
* The suite currently consists only of FuzzM.
*
*/
public class Main {
public static final String VERSION = "0.2";
public static void main(String[] args) {
if (args.length > 0) {
String entryPoint = args[0];
String[] subArgs = Arrays.copyOfRange(args, 1, args.length);
switch (entryPoint) {
case "-fuzzm":
FuzzMMain.main(subArgs);
System.exit(0);
break;
}
}
System.out.println("FuzzM Suite " + VERSION);
System.out.println("Available entry points: -fuzzm");
System.exit(1);
}
}
| 1,053 | 22.422222 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/FuzzMConfiguration.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import fuzzm.heuristic.Features;
import fuzzm.lustre.AddSignals;
import fuzzm.lustre.BindPre;
import fuzzm.lustre.NormalizeIDs;
import fuzzm.lustre.RemoveEnumTypes;
import fuzzm.solver.Solver;
import fuzzm.solver.SolverName;
import fuzzm.util.FuzzMInterval;
import fuzzm.util.IntervalVector;
import fuzzm.util.TypedName;
import jkind.ExitCodes;
import jkind.Main;
import jkind.lustre.NamedType;
import jkind.lustre.Program;
import jkind.lustre.VarDecl;
import jkind.translation.Translate;
/**
* The essential FuzzM configuration derived from the FuzzM settings.
*
*/
public class FuzzMConfiguration {
public Path fuzzingDirectory;
public String modelName;
public Program model;
public List<VarDecl> inputNames;
//public Path inputSpecFile;
public final Path fuzzFile;
public final int solutions;
public String target;
public List<SolverName> userSolvers;
private IntervalVector span;
public final boolean noVectors;
public final boolean Proof;
public final boolean constraints;
//public boolean properties;
//public boolean asteroid;
public final boolean throttle;
public String configDescription;
//public boolean unbiased;
public FuzzMConfiguration(FuzzMSettings settings) {
model = processModel(settings.filename);
Path modelFile = Paths.get(settings.filename);
modelName = baseModelName(modelFile);
fuzzingDirectory = workingDirectory(modelName,settings);
/*
String inputSpecFileName = modelName + ".inputs";
inputSpecFile = fuzzingDirectory.resolve(inputSpecFileName);
try {
Files.deleteIfExists(inputSpecFile);
Files.createFile(inputSpecFile);}
catch (IOException e) {}
*/
inputNames = processInputs();
fuzzFile = fuzzingDirectory.resolve("fuzz.lus");
solutions = settings.solutions;
employResources(fuzzingDirectory);
target = settings.target;
userSolvers = settings.userSolvers;
noVectors = settings.noVectors;
constraints = settings.constraints;
//properties = settings.properties;
//asteroid = settings.asteroid;
throttle = settings.throttle;
//unbiased = settings.unbiased;
// This singular span instance will be updated when we learn the true bounds
// on each of the inputs.
span = new IntervalVector();
for (VarDecl vd: inputNames) {
span.put(new TypedName(vd.id,(NamedType) vd.type),new FuzzMInterval((NamedType) vd.type));
}
configDescription = settings.configDescription;
Proof = settings.Proof;
}
public IntervalVector getSpan() {
return span;
}
public void setSpan(IntervalVector span) {
this.span = span;
}
public Features extractFeatures() {
return new Features(this);
}
public Solver configureSolver() {
return new Solver(userSolvers,fuzzingDirectory,"fuzz",inputNames);
}
private List<VarDecl> processInputs() {
Path InputFileName = fuzzingDirectory.resolve("fuzz.inputs");
try {
FileWriter fw = new FileWriter(InputFileName.toFile());
for (VarDecl vdecl: model.getMainNode().inputs) {
fw.write(vdecl.id + " ");
}
fw.write("\n");
fw.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(ExitCodes.UNCAUGHT_EXCEPTION);
}
return model.getMainNode().inputs;
}
private static void copyResourceToDirectory(String resourceName, Path fuzzingDirectory) {
InputStream infile = FuzzMConfiguration.class.getResourceAsStream("/resources/" + resourceName);
Path outfile = fuzzingDirectory.resolve(resourceName);
try {
Files.copy(infile, outfile);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private static void employResources(Path fuzzingDirectory) {
//copyResourceToDirectory("Makefile", fuzzingDirectory);
copyResourceToDirectory("xml2vector.py", fuzzingDirectory);
}
private static Program processModel(String filename) {
Program program = null;
try {
program = Main.parseLustre(filename);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
program = Translate.translate(program);
program = RemoveEnumTypes.program(program);
program = BindPre.program(program);
//program = DropProperties.drop(program);
program = NormalizeIDs.normalize(program);
// Deprecated: these were used primarily for property synthesis.
// There is a bug in bindLocals with (pre (if .. then 0 else 1))
//
// program = LocalBindings.bindLocals(program);
// program = LiftBooleans.lift(program);
// Add k-counter. We add the top level signal _k that starts at zero
// and simply increments in each time step. _k can be used by other
// signals to perform multi-cycle computation.
program = AddSignals.addTime(program);
// Note: the done signal is deprecated.
//
// Find/Add "done" signal. We look for a top level signal called
// "done" (by default). It should be a boolean signal. It should
// be a "single shot" meaning that it should be true for only one
// cycle. If no such signal is found, we create one. The created
// signal assumes a single step transaction. After finding/creating
// the signal we bind it to _done.
// program = AddSignals.add_done(program, FuzzmName.done);
return program;
}
private static String baseModelName(Path model) {
String modelFileName = model.getFileName().toString();
int dotIndex=modelFileName.lastIndexOf('.');
String oname = modelFileName;
if(dotIndex>=0) { // to prevent exception if there is no dot
oname=modelFileName.substring(0,dotIndex);
}
return oname;
}
private static Path workingDirectory(String modelName, FuzzMSettings settings) {
Path tempParent = Paths.get(settings.wdirName);
Path res = null;
try {
String prefix = "fuzzm_" + modelName + "_";
res = Files.createTempDirectory(tempParent,prefix);
} catch (IOException e) {
e.printStackTrace();
System.exit(ExitCodes.UNCAUGHT_EXCEPTION);
}
File z = res.toFile();
z.deleteOnExit();
z.setWritable(true,false);
z.setReadable(true,false);
z.setExecutable(true,false);
return res;
}
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete(); // The directory is empty now and can be deleted.
}
public void exit() {
try {deleteDir(fuzzingDirectory.toFile());} catch (Throwable t) {}
}
public void start() {
}
}
| 7,100 | 29.74026 | 104 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/DefaultOptions.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm;
import org.apache.commons.cli.Options;
/**
* DefaultOptions extends Options providing an addOption()
* method that accepts an additional default value argument.
*
*/
public class DefaultOptions extends Options {
private static final long serialVersionUID = 1L;
public DefaultOptions addOption(String opt, boolean hasArg, String description, Object defaultValue) {
String defaultValueString = (defaultValue == null) ? "null" : defaultValue.toString();
String altDescription = description + " [" + defaultValueString + "]";
addOption(opt,hasArg,altDescription);
return this;
}
}
| 820 | 29.407407 | 103 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/FuzzMMain.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm;
import fuzzm.engines.Director;
/**
* FuzzMMain is the interface to the FuzzM functionality.
*
*/
public class FuzzMMain {
public static void main(String[] args) {
try {
FuzzMSettings settings = new FuzzMSettings();
settings.parse(args);
FuzzMConfiguration cfg = new FuzzMConfiguration(settings);
cfg.start();
new Director(cfg).run();
cfg.exit();
System.exit(0);
} catch (Throwable t) {
t.printStackTrace();
System.err.println("");
System.err.println(t.getLocalizedMessage());
System.exit(-1);
}
}
}
| 774 | 19.945946 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/ArgumentParser.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm;
import java.math.BigInteger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
/**
* A refactoring of the JKind ArgumentParser class.
*
*/
public abstract class ArgumentParser {
public String filename = null;
protected static final String VERSION = "version";
protected static final String HELP = "help";
protected String name;
public ArgumentParser(String name) {
this.name = name;
}
public void parseArguments(String[] args) {
CommandLineParser parser = new BasicParser();
try {
parseCommandLine(parser.parse(getOptions(), args));
} catch (Throwable t) {
throw new IllegalArgumentException(t);
}
}
protected DefaultOptions getOptions() {
DefaultOptions options = new DefaultOptions();
options.addOption(VERSION, false, "display version information");
options.addOption(HELP, false, "print this message");
return options;
}
protected void parseCommandLine(CommandLine line) {
if (line.hasOption(VERSION)) {
System.out.println(name + " " + Main.VERSION);
System.exit(0);
}
if (line.hasOption(HELP)) {
printHelp();
System.exit(0);
}
String[] input = line.getArgs();
if (input.length != 1) {
throw new IllegalArgumentException("Invalid Arguments");
}
filename = input[0];
}
public final void parse(String[] args) {
try {
parseArguments(args);
checkSettings();
} catch (IllegalArgumentException t) {
System.err.println("");
System.err.println(t.getMessage());
System.err.println("");
printHelp();
System.exit(1);
}
}
protected void checkSettings() {
if (filename == null) {
throw new IllegalArgumentException("Uninitialized Settings");
}
}
protected void printHelp() {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(name.toLowerCase() + " [options] <input>", getOptions());
}
protected static int parseNonnegativeInt(String text) {
BigInteger bi = new BigInteger(text);
if (bi.compareTo(BigInteger.ZERO) < 0) {
return 0;
} else if (bi.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
return Integer.MAX_VALUE;
} else {
return bi.intValue();
}
}
protected static void ensureExclusive(CommandLine line, String opt1, String opt2) {
if (line.hasOption(opt1) && line.hasOption(opt2)) {
throw new IllegalArgumentException("cannot use option -" + opt1 + " with option -"
+ opt2);
}
}
}
| 2,728 | 24.504673 | 85 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/FuzzMSettings.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import fuzzm.solver.SolverName;
import fuzzm.util.Debug;
/**
* The user-provided settings for FuzzM.
*
*/
public class FuzzMSettings extends ArgumentParser {
public String configDescription = "";
private static final String SOLUTIONS = "solutions";
static final int solutions_default = -1;
public int solutions = solutions_default; // Default: Run forever
private static final String WDIR = "wdir";
static final String wdirName_default = wdirDefault();
public String wdirName = wdirName_default; // Working directory
//private static final String DONE = "done";
//public static final String doneName_default = "done";
//public String doneName = doneName_default;
private static final String TARGET = "amqp";
public static final String target_default = null;
String target = target_default;
private static final String SOLVER = "solver";
public static final SolverName solver_default = null;
List<SolverName> userSolvers = new ArrayList<SolverName>();
private static final String NOVECTORS = "no_vectors";
public static final boolean noVectors_default = false;
boolean noVectors = noVectors_default;
private static final String PROOF = "proof";
public static final boolean Proof_default = false;
boolean Proof = Proof_default;
private static final String CONSTRAINTS = "constraints";
public static final boolean constraints_default = false;
boolean constraints = constraints_default;
//private static final String PROPERTIES = "properties";
//public static final boolean properties_default = true;
//boolean properties = properties_default;
//private static final String ASTEROID = "asteroid";
//public static final boolean asteroid_default = false;
//boolean asteroid = asteroid_default;
//private static final String UNBIASED = "unbiased";
//public static final boolean unbiased_default = false;
//boolean unbiased = unbiased_default;
private static final String THROTTLE = "throttle";
public static final boolean throttle_default = false;
boolean throttle = throttle_default;
private static String wdirDefault() {
return Paths.get(".").toAbsolutePath().normalize().toString();
}
public FuzzMSettings() {
this("FuzzM");
}
protected FuzzMSettings(String name) {
super(name);
}
@Override
protected DefaultOptions getOptions() {
DefaultOptions options = super.getOptions();
options.addOption(SOLUTIONS, true, "Total number of constraint solutions to attempt (-1 = forever)",solutions_default);
options.addOption(WDIR, true, "Path to temporary working directory",wdirName_default);
//options.addOption(DONE, true, "Top level \"done\" signal name",doneName_default);
options.addOption(TARGET, true, "URL of AMQP server",target_default);
options.addOption(SOLVER, true, "Use Only Specified Solver",solver_default);
options.addOption(NOVECTORS, false, "Suppress test vector generation (debug)",noVectors_default);
options.addOption(PROOF, false, "Generate a validating proof script (debug)",Proof_default);
options.addOption(CONSTRAINTS, false, "Treat Lustre properties as constraints",constraints_default);
//options.addOption(PROPERTIES, false, "Fuzz only model properties",properties_default);
//options.addOption(ASTEROID, false, "Use asteroid space metric",asteroid_default);
options.addOption(THROTTLE, false, "Throttle vector generation (debug)",throttle_default);
//options.addOption(UNBIASED, false, "Disable bias when choosing values on an interval",unbiased_default);
return options;
}
@Override
protected void parseCommandLine(CommandLine line) {
super.parseCommandLine(line);
if (line.hasOption(SOLUTIONS)) {
solutions = parseNonnegativeInt(line.getOptionValue(SOLUTIONS));
}
if (line.hasOption(WDIR)) {
wdirName = line.getOptionValue(WDIR);
}
//if (line.hasOption(DONE)) {
// doneName = ID.encodeString(line.getOptionValue(DONE));
//}
if (line.hasOption(TARGET)) {
target = line.getOptionValue(TARGET);
}
if (line.hasOption(NOVECTORS)) {
noVectors = true;
}
if (line.hasOption(PROOF)) {
Proof = true;
Debug.setProof(true);
}
if (line.hasOption(SOLVER)) {
String solverName[] = line.getOptionValues(SOLVER);
try {
for (String name: solverName) {
userSolvers.add(SolverName.valueOf(name.toUpperCase()));
}
} catch (IllegalArgumentException e) {
String names = SolverName.availableSolvers.stream().map(Object::toString).collect(Collectors.joining(", "));
throw new IllegalArgumentException("Solver Must be one of: " + names);
}
}
// if (line.hasOption(PROPERTIES)) {
// properties = true;
// }
if (line.hasOption(CONSTRAINTS)) {
constraints = true;
}
// if (line.hasOption(ASTEROID)) {
// asteroid = true;
// }
if (line.hasOption(THROTTLE)) {
throttle = true;
}
// if (line.hasOption(UNBIASED)) {
// unbiased = true;
// }
List<String> toIgnore = Arrays.asList(WDIR,VERSION,HELP);
// TODO: I don't understand the need for this unchecked conversion .. Java? anyone?
@SuppressWarnings("unchecked")
Iterator<Option> itOp = line.iterator();
while(itOp.hasNext()){
Option o = itOp.next();
String name = o.getOpt();
if(toIgnore.contains(name)){
continue;
}
configDescription += name;
if(o.getArgs() != -1){
configDescription += ("=" + o.getValue());
}
configDescription += "_";
} // end while(hasNext)
} // end parseCommandLine
@Override
protected void checkSettings() {
super.checkSettings();
}
}
| 6,100 | 29.813131 | 121 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/solver/PathUtils.java | /*
* Derived From: SciJava Common shared library for SciJava software.
*
* Copyright (C) 2009 - 2017 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package fuzzm.solver;
import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
public class PathUtils {
/** Gets the name of the operating system. */
public static String osName() {
final String osName = System.getProperty("os.name");
return osName == null ? "Unknown" : osName;
}
public static boolean isWindows() {
return osName().startsWith("Win");
}
/**
* Gets the base location of the given class.
* <p>
* If the class is directly on the file system (e.g.,
* "/path/to/my/package/MyClass.class") then it will return the base directory
* (e.g., "file:/path/to").
* </p>
* <p>
* If the class is within a JAR file (e.g.,
* "/path/to/my-jar.jar!/my/package/MyClass.class") then it will return the
* path to the JAR (e.g., "file:/path/to/my-jar.jar").
* </p>
*
* @param c The class whose location is desired.
* @see FileUtils#urlToFile(URL) to convert the result to a {@link File}.
*/
public static URL getLocation(final Class<?> c) throws MalformedURLException {
URL url = ClassLoader.getSystemClassLoader().getResource(".");
if (url != null) return url;
if (c == null) return null; // could not load the class
// try the easy way first
try {
final URL codeSourceLocation =
c.getProtectionDomain().getCodeSource().getLocation();
if (codeSourceLocation != null) return codeSourceLocation;
}
catch (final SecurityException e) {
// NB: Cannot access protection domain.
}
catch (final NullPointerException e) {
// NB: Protection domain or code source is null.
}
// NB: The easy way failed, so we try the hard way. We ask for the class
// itself as a resource, then strip the class's path from the URL string,
// leaving the base path.
// get the class's raw resource path
final URL classResource = c.getResource(c.getSimpleName() + ".class");
if (classResource == null) return null; // cannot find class resource
final String urlString = classResource.toString();
final String suffix = c.getCanonicalName().replace('.', '/') + ".class";
if (!urlString.endsWith(suffix)) return null; // weird URL
// strip the class's path from the URL string
final String base = urlString.substring(0, urlString.length() - suffix.length());
String path = base;
// remove the "jar:" prefix and "!/" suffix, if present
if (path.startsWith("jar:")) path = path.substring(4, path.length() - 2);
return new URL(path);
}
/**
* Converts the given URL string to its corresponding {@link File}.
*
* @param url The URL to convert.
* @return A file path suitable for use with e.g. {@link FileInputStream}
* @throws IllegalArgumentException if the URL does not correspond to a file.
*/
public static File urlToFile(final String url) {
String path = url;
if (path.startsWith("jar:")) {
// remove "jar:" prefix and "!/" suffix
final int index = path.indexOf("!/");
path = path.substring(4, index);
}
try {
if (isWindows() && path.matches("file:[A-Za-z]:.*")) {
path = "file:/" + path.substring(5);
}
return new File(new URL(path).toURI());
}
catch (final MalformedURLException e) {
// NB: URL is not completely well-formed.
}
catch (final URISyntaxException e) {
// NB: URL is not completely well-formed.
}
if (path.startsWith("file:")) {
// pass through the URL as-is, minus "file:" prefix
path = path.substring(5);
return new File(path);
}
throw new IllegalArgumentException("Invalid URL: " + url);
}
/**
* Computes the Absolute Path to either the running Jar file.
*
* @return An Absolute File Path String.
*/
public static String pathToRunningJar() {
try {
URL url = getLocation(PathUtils.class);
if (url == null) return ".";
return urlToFile(url.toString()).getAbsolutePath();
} catch (MalformedURLException e) {
return ".";
}
}
}
| 6,114 | 38.451613 | 89 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/solver/SolverName.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.solver;
import java.util.List;
import java.util.stream.Collectors;
import fuzzm.value.poly.GlobalState;
import jkind.SolverOption;
import jkind.engines.SolverUtil;
/**
* SolverNames enumerates the names of the various solvers supported by JKind.
*
*/
public enum SolverName {
SMTINTERPOL("smtinterpol"), YICES2("yices2"), YICES("yices"), MATHSAT("mathsat"), CVC4("cvc4"), Z3("z3");
private final String value;
private SolverName(final String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static List<SolverName> removeYICES(List<SolverName> solvers) {
// Because yices is deprecated by the developers and is
// mis-reported by JKind when yices2 is installed we don't
// consider it as an option.
solvers.remove(YICES);
return solvers;
}
public static final List<SolverName> availableSolvers = removeYICES(SolverUtil.availableSolvers().stream().map(x -> asSolverName(x)).collect(Collectors.toList()));
public static SolverName asSolverName(SolverOption solver) {
switch (solver) {
// SMTINTERPOL, Z3, YICES, YICES2, CVC4, MATHSAT;
case SMTINTERPOL: return SMTINTERPOL;
case Z3: return Z3;
case YICES2: return YICES2;
case CVC4: return CVC4;
case MATHSAT: return MATHSAT;
default : return YICES;
}
}
@Override
public String toString() {
return getValue();
}
public static SolverName randomSolver(List<SolverName> userSolvers) {
assert(availableSolvers.size() > 0);
List<SolverName> pool = (userSolvers.size() > 0) ? userSolvers : availableSolvers;
int choice = GlobalState.oracle().nextInt(pool.size());
return pool.get(choice);
}
public static SolverName randomSolver() {
assert(availableSolvers.size() > 0);
int choice = GlobalState.oracle().nextInt(availableSolvers.size());
return availableSolvers.get(choice);
}
}
| 2,247 | 28.194805 | 167 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/solver/Solver.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.solver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import fuzzm.lustre.evaluation.FunctionLookupEV;
import fuzzm.lustre.evaluation.FunctionSignature;
import fuzzm.util.Debug;
import fuzzm.util.ID;
import fuzzm.util.Rat;
import fuzzm.util.RatSignal;
import fuzzm.util.TypedName;
import jkind.lustre.NamedType;
import jkind.lustre.Program;
import jkind.lustre.VarDecl;
import jkind.util.BigFraction;
/**
* The solver class is our interface to JKind.
*
*/
public class Solver {
ProcessBuilder pb;
Path workingDirectory;
String modelName;
List<VarDecl> modelInputs;
List<SolverName> userSolvers;
public SolverName slver = SolverName.randomSolver();
String javaExec;
String jkindJarPath;
String pythonExec;
String xml2vectorPath;
public Solver(List<SolverName> userSolvers, Path workingDirectory, String modelName, List<VarDecl> inputs) {
pb = new ProcessBuilder();
pb.directory(workingDirectory.toFile());
this.workingDirectory = workingDirectory;
this.modelName = modelName;
this.modelInputs = inputs;
this.userSolvers = userSolvers;
javaExec = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
try {
try {
// See if JKind is on the system PATH
this.jkindJarPath = findFile(System.getenv("PATH"),"jkind.jar").getAbsolutePath();
} catch (FileNotFoundException e1) {
try {
// Try to use JKind from the FuzzM distribution
this.jkindJarPath = findFile(mvn_repo_path(),"jkind-uf.jar").getAbsolutePath();
} catch (FileNotFoundException e2) {
throw e1;
}
}
this.pythonExec = getExecutable("python");
this.xml2vectorPath = workingDirectory.resolve("xml2vector.py").toAbsolutePath().toString();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public void randomSolver() {
slver = SolverName.randomSolver(userSolvers);
}
private String getExecutable(String execName) throws FileNotFoundException {
String home = System.getenv(execName.toUpperCase() + "_PATH");
if (home != null) {
return home + File.separator + execName;
}
File execFile = findFile(System.getenv("PATH"),execName);
return execFile.toString();
}
private boolean runCommand(List<String> command, String location) {
pb.command(command);
int exit = -1;
boolean done = false;
try {
Process proc = pb.start();
BufferedReader stdOut = null;
BufferedReader stdErr = null;
stdOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
stdErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while (!done) {
try {
exit = proc.waitFor();
done = true;
} catch (InterruptedException e) {
System.out.println(ID.location() + "Solver : INTERRUPTED");
}
}
String line;
if (!done) {
System.err.println(location + "Command(" + command + ") failed to complete.");
}
if (exit != 0) {
System.err.println(location + "Command(" + command + ") exited with code: " + Integer.toString(exit));
}
if (Debug.isEnabled()) {
while ((line = stdOut.readLine()) != null) {
System.out.println(location + "STDOUT : " + line);
}
}
while ((line = stdErr.readLine()) != null) {
System.err.println(location + "STDERR : " + line);
}
stdOut.close();
stdErr.close();
} catch (Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
// We print to stderr but don't exit ..
System.err.println(sw.toString());
pw.close();
}
return (done && (exit == 0));
}
private void removeWarningLines(File ifile, File ofile) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(ofile));
BufferedReader br = new BufferedReader(new FileReader(ifile));
String line;
while ((line = br.readLine()) != null) {
if (!line.startsWith("Warning")) {
bw.write(line);
bw.newLine();
}
}
bw.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public static String jarPath(final Class<?> c) {
return PathUtils.pathToRunningJar();
}
private String mvn_repo_path() throws FileNotFoundException {
String path = ".";
String jar_path = jarPath(Solver.class);
// MVN repo is here: FuzzM/fuzzm/fuzzm/mvn-repo
try {
// Eclipse typically executes from FuzzM/fuzzm/fuzzm/target/classes
String eclipse_path = new File(jar_path + "/../../mvn-repo/jkind/jkind/uf").getCanonicalFile().getAbsolutePath();
//System.out.println(ID.location() + "*** Eclipse path : " + eclipse_path);
path = path + ":" + eclipse_path;
} catch (Throwable t) {
}
try {
// We store generated .jar files in FuzzM/fuzzm/fuzzm/bin
String cmd_path = new File(jar_path + "/../mvn-repo/jkind/jkind/uf").getCanonicalFile().getAbsolutePath();
//System.out.println(ID.location() + "*** Command path : " + cmd_path);
path = path + ":" + cmd_path;
} catch (Throwable t) {
}
return path;
}
public File findFile(String systemPath, String filename) throws FileNotFoundException {
String[] paths = systemPath.split(File.pathSeparator);
for (String path : paths) {
File testFile = new File(path + File.separator + filename);
if (testFile.exists()) {
return testFile;
}
}
throw new FileNotFoundException("Unable to find file: " + filename + " in " + Arrays.toString(paths));
}
public boolean runSolver(File ofile) {
SolverName slver = (this.slver == null) ? SolverName.randomSolver() : this.slver;
String[] jkindArgs = { "-jkind", "-xml", "-solver", slver.toString(), "--no_slicing", ofile.getAbsolutePath() };
List<String> jkindCommand = new ArrayList<>();
jkindCommand.add(javaExec);
jkindCommand.add("-jar");
jkindCommand.add(jkindJarPath);
jkindCommand.addAll(Arrays.asList(jkindArgs));
List<String> vectorCommand = new ArrayList<>();
vectorCommand.add(pythonExec);
vectorCommand.add(xml2vectorPath);
vectorCommand.add(ofile.getAbsolutePath().substring(0, ofile.getAbsolutePath().length() - 4));
if (runCommand(jkindCommand, ID.location())) {
File lusxmlFile = new File(ofile.getAbsolutePath() + ".xml");
File xmlFile = new File(ofile.getAbsolutePath().substring(0, ofile.getAbsolutePath().length() - 3) + "xml");
removeWarningLines(lusxmlFile, xmlFile);
if (runCommand(vectorCommand, ID.location()))
return true;
}
return false;
}
public SolverResults invoke(Program program) {
Map<String, List<String>> res = new HashMap<String, List<String>>();
FunctionLookupEV fnLookup = new FunctionLookupEV(new FunctionSignature(program.functions));
Map<Integer, String> loc = null;
// System.out.println("model : " + model);
// assert(workingDirectory != null);
// assert(modelName != null);
File ofile = workingDirectory.resolve(modelName + ".lus").toFile();
System.out.println(ID.location() + "Writing file : " + ofile.getAbsolutePath());
BufferedWriter output;
try {
output = new BufferedWriter(new FileWriter(ofile));
output.write(program.toString());
output.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
long t0 = System.currentTimeMillis();
boolean worked = runSolver(ofile);
long t1 = System.currentTimeMillis();
long duration = (t1 - t0);
if (worked) {
try {
File ifile = workingDirectory.resolve(modelName + ".inputs").toFile();
File vfile = workingDirectory.resolve(modelName + ".vector").toFile();
File ffile = workingDirectory.resolve(modelName + ".funs").toFile();
BufferedReader ibr = new BufferedReader(new FileReader(ifile));
String line = null;
line = ibr.readLine();
assert (line != null);
String[] inputNames = line.split(" ");
loc = new HashMap<Integer, String>();
int off = 0;
// The .inputs file should be generated by the fuzzer.
// The input names it contains should already be consistent with the model
for (String name : inputNames) {
res.put(name, new ArrayList<String>());
loc.put(off++, name);
}
ibr.close();
BufferedReader vbr = new BufferedReader(new FileReader(vfile));
while ((line = vbr.readLine()) != null) {
String[] values = line.split(" ");
off = 0;
for (String value : values) {
res.get(loc.get(off++)).add(value);
}
}
vbr.close();
BufferedReader fbr = new BufferedReader(new FileReader(ffile));
while ((line = fbr.readLine()) != null) {
fnLookup.addEncodedString(line);
}
fbr.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
RatSignal sln = new RatSignal();
// res is a mapping from single variables to their values over time:
// a: [1,2]
// b: [0,3]
// We need a temporal sequence of value vectors:
// [(a:1,b:0),(a:2,b:3)]
if (!res.isEmpty()) {
for (VarDecl vd : modelInputs) {
String var = vd.id;
List<String> v = res.get(var);
for (int time = 0; time < v.size(); time++) {
BigFraction decoded = Rat.BigFractionFromString(v.get(time));
sln.put(time, new TypedName(var, (NamedType) vd.type), decoded);
}
}
}
if (Debug.isEnabled()) System.out.println(ID.location() + "CEX " + sln);
return new SolverResults(duration,sln, fnLookup);
}
}
| 11,950 | 37.676375 | 128 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/solver/SolverResults.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.solver;
import fuzzm.lustre.evaluation.FunctionLookupEV;
import fuzzm.util.RatSignal;
public class SolverResults {
public RatSignal cex;
public FunctionLookupEV fns;
public long time;
public SolverResults(long time, RatSignal cex, FunctionLookupEV fns) {
this.cex = cex;
this.fns = fns;
this.time = time;
}
@Override
public String toString() {
String res = "\n";
res += fns.toString() + "\n";
res += cex.toString() + "\n";
return res;
}
}
| 694 | 18.857143 | 71 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/StepDependency.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.lustre;
import java.util.HashSet;
import java.util.Set;
import jkind.lustre.Expr;
import jkind.lustre.IdExpr;
import jkind.lustre.UnaryExpr;
import jkind.lustre.UnaryOp;
import jkind.lustre.visitors.ExprIterVisitor;
public class StepDependency extends ExprIterVisitor {
private Set<String> depSet;
private PreDependency preVisitor;
private StepDependency() {
preVisitor = new PreDependency();
depSet = new HashSet<>();
}
public Set<String> getDepSet() {
return depSet;
}
public Set<String> getPreSet() {
return preVisitor.getPreSet();
}
public static StepDependency computeDependencies(Expr e) {
StepDependency stepVisitor = new StepDependency();
e.accept(stepVisitor);
return stepVisitor;
}
@Override
public Void visit(IdExpr e) {
depSet.add(e.id);
return null;
}
@Override
public Void visit(UnaryExpr e) {
if (e.op.equals(UnaryOp.PRE)) {
e.expr.accept(preVisitor);
} else {
super.visit(e);
}
return null;
}
}
| 1,204 | 18.754098 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/MainBuilder.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.lustre;
import java.util.ArrayList;
import java.util.List;
import jkind.lustre.Node;
import jkind.lustre.Program;
import jkind.lustre.builders.ProgramBuilder;
public class MainBuilder extends ProgramBuilder {
Node mainNode;
String mainName;
List<Node> nodeList;
public MainBuilder(Program program) {
super(program);
mainName = program.main;
mainNode = program.getMainNode();
nodeList = program.nodes;
}
public MainBuilder updateMainNode(Node node) {
mainNode = node;
return this;
}
@Override
public Program build() {
List<Node> res = new ArrayList<Node>();
for (Node node: nodeList) {
if (node.id.equals(mainName)) {
res.add(mainNode);
} else {
res.add(node);
}
}
clearNodes();
addNodes(res);
return super.build();
}
}
| 1,009 | 18.423077 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/BooleanCtx.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.lustre;
import java.util.Collection;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.Expr;
import jkind.lustre.NamedType;
public class BooleanCtx extends ACExprCtx {
public BooleanCtx() {
super(NamedType.BOOL,BinaryOp.AND);
}
public BooleanCtx(Expr initialValue) {
this();
add(initialValue);
}
public BooleanCtx(Collection<Expr> initialValue) {
this();
addAll(initialValue);
}
public BooleanCtx(ExprCtx arg) {
super(BinaryOp.AND,arg);
}
public BooleanCtx implies(ExprCtx x) {
BooleanCtx res = new BooleanCtx(this);
res.eqs.addAll(x.eqs);
res.decls.addAll(x.decls);
Expr exp = new BinaryExpr(getExpr(),BinaryOp.IMPLIES,x.getExpr());
res.exprList.clear();
res.exprList.add(exp);
return res;
}
public BooleanCtx implies(Expr x) {
BooleanCtx res = new BooleanCtx(this);
Expr exp = new BinaryExpr(getExpr(),BinaryOp.IMPLIES,x);
res.exprList.clear();
res.exprList.add(exp);
return res;
}
public void and(Expr expr) {
add(expr);
}
// DAG - of course this needs to be functional ..
public BooleanCtx and(BooleanCtx arg) {
BooleanCtx arg0 = new BooleanCtx(this);
arg0.op(BinaryOp.AND,arg);
return arg0;
}
}
| 1,447 | 20.294118 | 68 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/NormalizeIDs.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.lustre;
import java.util.ArrayList;
import java.util.List;
import fuzzm.util.ID;
import jkind.lustre.Equation;
import jkind.lustre.Expr;
import jkind.lustre.Function;
import jkind.lustre.FunctionCallExpr;
import jkind.lustre.IdExpr;
import jkind.lustre.Node;
import jkind.lustre.NodeCallExpr;
import jkind.lustre.Program;
import jkind.lustre.VarDecl;
import jkind.lustre.visitors.AstMapVisitor;
public class NormalizeIDs extends AstMapVisitor {
public static Program normalize(Program program) {
return new NormalizeIDs().visit(program);
}
@Override
public Program visit(Program e) {
Program x = super.visit(e);
return new Program(x.location,x.types,x.constants,x.functions,x.nodes, ID.encodeString(x.main));
}
@Override
public Equation visit(Equation e) {
List<IdExpr> lhs = new ArrayList<IdExpr>();
for (IdExpr id: e.lhs) {
lhs.add((IdExpr) visit(id));
}
// Why can't I just visit(e.expr) ?
Expr expr = e.expr.accept(this);
return new Equation(e.location,lhs,expr);
}
@Override
public Expr visit(IdExpr e) {
String name = e.id;
return new IdExpr(e.location,ID.encodeString(name));
}
@Override
public VarDecl visit(VarDecl e) {
String name = e.id;
return new VarDecl(e.location,ID.encodeString(name), e.type);
}
@Override
public NodeCallExpr visit(NodeCallExpr e) {
NodeCallExpr x = (NodeCallExpr) super.visit(e);
String name = x.node;
return new NodeCallExpr(x.location,ID.encodeString(name),x.args);
}
@Override
public FunctionCallExpr visit(FunctionCallExpr e) {
FunctionCallExpr x = (FunctionCallExpr) super.visit(e);
String name = x.function;
return new FunctionCallExpr(x.location,ID.encodeString(name),x.args);
}
@Override
public Node visit(Node e) {
Node x = super.visit(e);
String name = x.id;
return new Node(x.location,
ID.encodeString(name),
x.inputs,
x.outputs,
x.locals,
x.equations,
x.properties,
x.assertions,
x.realizabilityInputs,
x.contract,
x.ivc);
}
@Override
public Function visit(Function e) {
Function x = super.visit(e);
String name = x.id;
return new Function(x.location,
ID.encodeString(name),
x.inputs,
x.outputs);
}
@Override
protected List<String> visitProperties(List<String> es) {
List<String> res = new ArrayList<String>();
for (String s: es) {
res.add(ID.encodeString(s));
}
return res;
}
} | 2,642 | 23.027273 | 98 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/ExprVect.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.lustre;
import java.math.BigDecimal;
import fuzzm.util.Copy;
import fuzzm.util.IntervalVector;
import fuzzm.util.Rat;
import fuzzm.util.RatVect;
import fuzzm.util.TypedName;
import fuzzm.util.Vector;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.Expr;
import jkind.lustre.NamedType;
import jkind.lustre.RealExpr;
import jkind.util.BigFraction;
public class ExprVect extends Vector<Expr> implements Copy<ExprVect> {
private static final long serialVersionUID = 9058509602605173261L;
public ExprVect() {
super();
}
public ExprVect(ExprVect arg) {
super();
for (TypedName key: arg.keySet()) {
put(key,arg.get(key));
}
}
public ExprVect(RatVect v) {
super();
for (TypedName key: v.keySet()) {
put(key,Rat.toExpr(v.get(key)));
}
}
public ExprVect(IntervalVector v) {
super();
for (TypedName key: v.keySet()) {
put(key,Rat.cast(key.name,key.type));
}
}
private static boolean isZero(Expr term) {
if (term instanceof RealExpr) {
BigDecimal value = ((RealExpr) term).value;
return (value.signum() == 0);
}
return false;
}
public ACExprCtx dot(Vector<Expr> x) {
ACExprCtx acc = new ACExprCtx(NamedType.REAL,BinaryOp.PLUS);
for (TypedName key: keySet()) {
Expr left = get(key);
Expr right = x.get(key);
if (! (isZero(left) || isZero(right))) {
acc.add(new BinaryExpr(get(key),BinaryOp.MULTIPLY,x.get(key)));
}
}
return acc;
}
@Override
public ExprVect mul(BigFraction M) {
ExprVect res = new ExprVect();
for (TypedName key: keySet()) {
res.put(key,new BinaryExpr(get(key),BinaryOp.MULTIPLY,Rat.toExpr(M)));
}
return res;
}
@Override
public ExprVect add(Vector<Expr> x) {
ExprVect res = new ExprVect();
for (TypedName key: keySet()) {
res.put(key,new BinaryExpr(get(key),BinaryOp.PLUS,x.get(key)));
}
return res;
}
@Override
public ExprVect sub(Vector<Expr> x) {
ExprVect res = new ExprVect();
for (TypedName key: keySet()) {
res.put(key,new BinaryExpr(get(key),BinaryOp.MINUS,x.get(key)));
}
return res;
}
@Override
public Expr get(TypedName key) {
if (containsKey(key)) {
return super.get(key);
}
// NOTE: we assume that the only place we would do this is
// in the context of, say, a dot product computation where
// the values are rational.
return new RealExpr(BigDecimal.ZERO);
}
@Override
public ExprVect copy() {
return new ExprVect(this);
}
}
| 2,665 | 21.403361 | 73 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/FuzzProgram.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.lustre;
import fuzzm.util.Debug;
import fuzzm.util.FuzzmName;
import fuzzm.util.ID;
import fuzzm.util.IDString;
import jkind.lustre.Equation;
import jkind.lustre.IdExpr;
import jkind.lustre.Location;
import jkind.lustre.NamedType;
import jkind.lustre.Node;
import jkind.lustre.Program;
import jkind.lustre.VarDecl;
import jkind.lustre.builders.NodeBuilder;
public class FuzzProgram {
public static Program fuzz(Program program, BooleanCtx constraint) {
Node main = program.getMainNode();
main = fuzz(main,constraint);
MainBuilder mb = new MainBuilder(program);
mb.updateMainNode(main);
return mb.build();
}
private static Node fuzz(Node node, ExprCtx constraint) {
NodeBuilder NodeB = new NodeBuilder(node);
NodeB = NodeB.clearProperties();
NodeB = NodeB.clearIvc();
IDString pname = FuzzmName.fuzzProperty;
NodeB = NodeB.addLocal(new VarDecl(Location.NULL,pname.name(),NamedType.BOOL));
NodeB = NodeB.addEquations(constraint.eqs);
NodeB = NodeB.addLocals(constraint.decls);
if (Debug.isEnabled()) System.out.println(ID.location() + "Constraint: " + constraint.getExpr());
NodeB = NodeB.addEquation(new Equation(new IdExpr(pname.name()),constraint.getExpr()));
NodeB = NodeB.addProperty(pname.name());
Node z = NodeB.build();
return z;
}
}
| 1,514 | 29.3 | 99 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.